51 Commits

Author SHA1 Message Date
514ba6bae1 v2.1.2 pom 2025-05-21 15:35:25 -04:00
6c93637dbb Merge branch 'develop' into stable 2025-05-21 15:35:03 -04:00
65d80dc82d throttle sync 2025-05-21 15:34:22 -04:00
4859473938 v2.1.1 pom 2025-05-19 09:44:57 -04:00
99f5a7702c Merge branch 'develop' into stable 2025-05-19 09:44:36 -04:00
880da07a84 added /app/rest support for non-UI requests 2025-05-19 09:44:23 -04:00
9412957e89 Merge branch 'develop' into stable 2025-05-09 19:02:43 -04:00
faba551a2d v2.1.x; added APS API support 2025-05-09 19:02:12 -04:00
84d1b4ea2f clearer/property variable naming and ordering 2025-05-07 09:17:27 -04:00
187e558177 removed auth-ext.group.admins.externalId in favor of auth-ext.externalId 2025-05-07 08:51:41 -04:00
c38c1d28df updated docs 2025-05-07 08:50:25 -04:00
9c67dad207 v2.0.2 pom 2025-05-05 18:19:10 -04:00
55619d6b4a Merge branch 'develop' into stable 2025-05-05 18:18:53 -04:00
d631cc5f12 externalize only groups that the user should belong to 2025-05-05 13:38:50 -04:00
0a10b06cc8 sync.externalId to externalId 2025-05-05 11:41:49 -04:00
76ce7e42d4 added multiext runtime dep 2025-05-05 11:19:46 -04:00
0b032f1f7f Merge branch 'develop' into stable 2025-05-05 11:18:56 -04:00
790836194e removed Bootstrapper in favor of multiext 2025-05-05 11:17:40 -04:00
dde6dbcdb0 bitbucket.org to git.inteligr8.com 2025-05-04 20:20:50 -04:00
3d3a7433c5 Merge branch 'develop' into stable 2025-05-04 20:16:17 -04:00
5dfdf8452d refactored for v24+ 2025-05-04 20:11:15 -04:00
9c7641b858 v1.4.3 pom 2025-04-19 18:19:07 -04:00
0e34f589c3 Merge branch 'develop' into stable 2025-04-19 18:18:49 -04:00
dcd7e987f1 updated to shade keycloak library (not in APS v24.x+) 2025-04-19 18:17:34 -04:00
a73543d2a6 v1.4.1 pom 2025-02-12 14:35:41 -05:00
cd472b9269 Merge branch 'develop' into stable 2025-02-12 14:34:10 -05:00
e7f2e2ee0c steps to reduce bean name conflicts 2025-02-12 14:33:58 -05:00
bf848b009c v1.4.0 pom 2024-10-15 15:56:54 -04:00
52b86c0de4 Merge branch 'develop' into stable 2024-10-15 15:56:38 -04:00
b34093bb85 jakarta upgrade for APS v24.x+; v1.4.x pom 2024-10-15 15:56:03 -04:00
8bc0a7e520 Merge branch 'develop' into stable 2024-06-21 13:17:16 -04:00
263b8d553e maven inteligr8 to central 2024-06-21 13:17:03 -04:00
0601b2b2b2 Merge branch 'develop' into stable 2024-06-21 13:11:04 -04:00
9013228ee2 building against v2.4.4 and jdk17 2024-06-21 13:09:36 -04:00
1b8ec77860 upgrade versions 2023-10-13 09:12:02 -04:00
ec35b8bb19 add docs 2022-10-03 11:52:09 -04:00
93af3639cc Merge branch 'develop' into stable 2022-07-28 15:25:32 -04:00
6d0441a7b0 excluding aspose/aoservices 2022-07-28 15:24:35 -04:00
0d402f6014 Merge branch 'develop' into stable 2022-07-01 12:15:48 -04:00
f000f1b134 updated README 2022-07-01 12:15:30 -04:00
e7b6bd644e Merge branch 'develop' into stable 2022-07-01 12:14:32 -04:00
25093cd822 using first version for most compatibility 2022-07-01 12:07:00 -04:00
70ff0b5c5c added APS v2.x compatibility 2022-07-01 12:06:30 -04:00
343e1b65b9 added password resetter 2022-01-24 15:29:17 -05:00
d10ff1103d added password resetter 2022-01-24 15:27:59 -05:00
f5eefdb544 flipped org/cap inclusion because caps are fewer 2021-11-10 14:31:39 -05:00
28a6f4d101 allowing for more dynamic organization/capability sync control 2021-11-10 13:56:42 -05:00
07a5ed959a moved distman to repo; pruned repos 2021-09-01 14:50:13 -04:00
14487b62eb v1.2.1 pom 2021-08-31 19:55:19 -04:00
e87a6b68a7 Merge branch 'develop' into stable 2021-08-31 19:54:53 -04:00
19f21fdd5c fixed group multi-match snafu on startup 2021-08-31 19:54:39 -04:00
39 changed files with 3222 additions and 1433 deletions

157
COPYING.LESSER.md Normal file
View File

@@ -0,0 +1,157 @@
### GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the
terms and conditions of version 3 of the GNU General Public License,
supplemented by the additional permissions listed below.
#### 0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the
GNU General Public License.
"The Library" refers to a covered work governed by this License, other
than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
#### 1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
#### 2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
- a) under this License, provided that you make a good faith effort
to ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
- b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
#### 3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a
header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
- a) Give prominent notice with each copy of the object code that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the object code with a copy of the GNU GPL and this
license document.
#### 4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken
together, effectively do not restrict modification of the portions of
the Library contained in the Combined Work and reverse engineering for
debugging such modifications, if you also do each of the following:
- a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the Combined Work with a copy of the GNU GPL and this
license document.
- c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
- d) Do one of the following:
- 0) Convey the Minimal Corresponding Source under the terms of
this License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
- 1) Use a suitable shared library mechanism for linking with
the Library. A suitable mechanism is one that (a) uses at run
time a copy of the Library already present on the user's
computer system, and (b) will operate properly with a modified
version of the Library that is interface-compatible with the
Linked Version.
- e) Provide Installation Information, but only if you would
otherwise be required to provide such information under section 6
of the GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the Application
with a modified version of the Linked Version. (If you use option
4d0, the Installation Information must accompany the Minimal
Corresponding Source and Corresponding Application Code. If you
use option 4d1, you must provide the Installation Information in
the manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.)
#### 5. Combined Libraries.
You may place library facilities that are a work based on the Library
side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
- a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities, conveyed under the terms of this License.
- b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
#### 6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
as you received it specifies that a certain numbered version of the
GNU Lesser General Public License "or any later version" applies to
it, you have the option of following the terms and conditions either
of that published version or of any later version published by the
Free Software Foundation. If the Library as you received it does not
specify a version number of the GNU Lesser General Public License, you
may choose any version of the GNU Lesser General Public License ever
published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

675
COPYING.md Normal file
View File

@@ -0,0 +1,675 @@
### GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom
to share and change all versions of a program--to make sure it remains
free software for all its users. We, the Free Software Foundation, use
the GNU General Public License for most of our software; it applies
also to any other work released this way by its authors. You can apply
it to your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you
have certain responsibilities if you distribute copies of the
software, or if you modify it: responsibilities to respect the freedom
of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so. This is fundamentally incompatible with the
aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those
domains in future versions of the GPL, as needed to protect the
freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish
to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL
assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS
#### 0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
#### 1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
#### 2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
#### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU General Public
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that numbered version or
of any later version published by the Free Software Foundation. If the
Program does not specify a version number of the GNU General Public
License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU General Public License can be used, that proxy's public
statement of acceptance of a version permanently authorizes you to
choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
#### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, your
program's commands might be different; for a GUI interface, you would
use an "about box".
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
GNU Lesser General Public License instead of this License. But first,
please read <https://www.gnu.org/licenses/why-not-lgpl.html>.

131
README.md
View File

@@ -1,14 +1,19 @@
# Keycloak Extension for Activiti
# Auth Extension for APS (Activiti App)
This library was created to expand the functionality of keycloak integration within the APS (Activiti App) application. It includes a similar implementation for core Activiti (Activiti Engine), but the core functional is not delivered with that OOTB application at this time.
This library was originally created to expand the functionality of Keycloak integration within the Alfresco Process Services (APS) application. It has expanded to support general OAuth, closing gaps that remain in the implementation provided by Alfresco. This is useless for the open source Activiti product.
The Activiti App delivers SSO capability and that is about it. The user must already exist and group synchronization may only happen outside of the context of authentication. Namely over another protocol (LDAP).
APS delivers SSO capability and that is about it. It has a few shortcomings:
This module expands SSO to include user creation and group synchronization. Group synchronization uses the standard access token for Open ID Connect. These groups are termed "roles".
- The user must already exist in APS, which means they must be sync'd in from LDAP.
- The user roles are for their session only and not synchronized with APS Organizations. This prevents the user from being included in task candidate group assignments and other group features.
This extension aims to resolve those issues.
The older version of this extension was specific to Keycloak and was named `keycloak-activiti-app-ext`. See the [`develop-v1.4.x` branch](https://git.inteligr8.com/inteligr8/auth-activiti-app-ext/src/branch/develop-v1.4.x/) for details specific to it.
## Installation
The installation is simple. Just include the JAR in the classpath of your Activiti App application. This is best done by not chaning the `activiti-app.war` file, but instead including it within the classpath using your web container configuration. For Apache Tomcat, you would add or modify the following context file: `conf/Catalina/localhost/activiti-app.xml`. Its related contents would be:
The installation is simple. Just include the JAR in the classpath of your APS application. This is best done by not chaning the `activiti-app.war` file, but instead including it within the classpath using your web container configuration. For Apache Tomcat, you would add or modify the following context file: `conf/Catalina/localhost/activiti-app.xml`. Its related contents would be:
```xml
<Context>
@@ -18,50 +23,94 @@ The installation is simple. Just include the JAR in the classpath of your Activ
</Context>
```
Notice the use of `PostResources` instead of `PreResources`. This library needs to be loaded after the web application. This is the best way to load any other extensions or customization to the Activiti App, including `JavaDelegate` implementations.
Notice the use of `PostResources` instead of `PreResources`. This library needs to be loaded after the web application. This is the best way to load any other extensions or customization to the Activiti App, including `JavaDelegate` implementations. If you use the `-security` switch, you will need to give this path permissions in the `catalina.policy` file:
```properties
grant codeBase "file:${catalina.base}/ext/-" {
permission java.security.AllPermissions
}
```
### Dependencies
This extension requires the [`multiext-activiti-app-ext`](https://git.inteligr8.com/inteligr8/multiext-activiti-app-ext). Without it, APS will fail to startup. It is very small and requires no additional configuration.
## Support Matrix
| Activiti App Extension | Activiti App |
| --------------------------------------- | --------------- |
| `keycloak-activiti-app-ext` v1.0 - v1.2 | v1.11.x |
| `keycloak-activiti-app-ext` v1.3 - v1.4 | v1.11.x - v2.x |
| `auth-activiti-app-ext` v2.0+ | v24.x+ |
## Configuration
The library is highly configurable. You configure it with properties specified in the `activiti-app.properties` file, which exists somewhere in the root of the classpath. That is typically in the `lib` folder. The properties to configure are enumerated in the table below.
The library is highly configurable. You configure it with properties specified in the `activiti-app.properties` file, which exists somewhere in the root of the classpath. That is typically in the `lib` folder. Or you could specify these options with `-D` switches on startup of the web container. The properties to configure are enumerated in the table below.
### Common
This will only work if OAuth is being used. That would be the case if `activiti.identity-service.enabled` or `security.oauth2.authentication.enabled` is `true`.
| Property | Default | Description |
| ---------------------------------------------- | --------- | ----------- |
| `keycloak-ext.ais.enabled` | `false` | Enable AIS integration, overriding and extending the OOTB AIS provider. |
| `keycloak-ext.ootbSecurityConfig.enabled` | `true` | Enable OOTB functionality as if this module were not installed. This adapter operates at priority `0`. This means it only works if other adapters are disabled (default). |
| `keycloak-ext.default.admins.users` | | A default set of administrators to add to the administration role on application startup. |
| `keycloak-ext.clearNewUserDefaultGroups` | `true` | When creating a new user, clear any default groups added to that user. This will not impact existing users. |
| `keycloak-ext.resource.include.regex.patterns` | | OIDC provides roles in the realm and all permitted clients/resources. By default all resources are included. You can limit it with regular expressions with this property. |
| `keycloak-ext.group.format.regex.patterns` | | Reformat roles that match the specified regular expressions. The replacements are specified in another property. Multiple expressions may be specified by using commas. Whitespace is not stripped. |
| `keycloak-ext.group.format.regex.replacements` | | Reformat roles with the specified replacement expressions. The regular expressions are specified in another property. Multiple expressions may be specified by using commas. Whitespace is not stripped. |
| `keycloak-ext.group.include.regex.patterns` | | If specified, only the roles that match the specified regular expressions will be considered; otherwise all roles are included. |
| `keycloak-ext.group.exclude.regex.patterns` | | If specified, the roles that match the specified regular expressions will be ignored. This overrides any role explicitly included. |
| `keycloak-ext.syncInternalGroup` | `false` | If an internal group with the same name already exists, use that group instead of creating a new one with the same name. Also register that internal group as external. |
The following properties are used across the functionalities of this extension.
### For Activiti App Only
| Property | Default | Description |
| --------------------------------- | --------- | ----------- |
| `auth-ext.externalId` | `oauth` | This will serve as the external ID for users and as the prefix for the external ID of groups created or searched by this extension. Anything without an external ID is considered internal. So mismatched external IDs are never considered for anything by this extension. |
| `auth-ext.tenant` | | A preselected tenant for all operations in this extension. Only required if there are multiple tenants. |
| `auth-ext.sync.resyncInMillis` | `300000` | To prevent too many sync checks, how long between seeing the EXACT same token should we wait before doing another sync. The only time this matters is if the user is manually added to or removed from groups in APS by other means. Or those groups are deleted. |
| Property | Default | Description |
| ----------------------------------------- | -------------- | ----------- |
| `keycloak-ext.syncGroupAs` | `organization` | When creating a new group, should it be a functional (`organization`) group or a system (`capability`) group? |
| `keycloak-ext.external.id` | `ais` | When creating a new group or registering an internal group as external, use this ID as a prefix to the external group ID. |
### OAuth Authentication/Authorization
### Rare
The following properties were added to increase the configurability of the built-in OAuth capabilities of APS. The default in this extension adds the `microprofile-jwt` scope, which is key to providing groups/roles/entitlements.
| Property | Default | Description |
| ----------------------------------------- | --------------- | ----------- |
| `keycloak-ext.ais.priority` | `-10` | The order of configurable adapters to use with the application. Only the lowest priority enabled adapter will be used. Values of `1`+ will only load if the OOTB adapter is disabled. |
| `keycloak-ext.group.admins.validate` | `false` | Whether or not to validate the existence and capabilities of an administrators group on appliation startup. This is only applicable for when one is accidently removed and no one has the rights to create one. |
| `keycloak-ext.group.admins.name` | `admins` | The name of an administrators group to potentially add and default users on application startup. |
| `keycloak-ext.group.admins.externalId` | `admins` | The name of an administrators group to potentially add and default users on application startup. |
| `keycloak-ext.createMissingUser` | `true` | Before authentication, check to make sure the user exists as an APS user; if they don't, create the user. |
| `keycloak-ext.createMissingGroup` | `true` | Before authorization, check to make sure groups exist for the roles the user claims; if they don't, create the groups. |
| `keycloak-ext.syncGroupAdd` | `true` | If the user belongs to a role but not its corresponding group, add the user to the group. |
| `keycloak-ext.syncGroupRemove` | `true` | If the user belongs to a group but does not have the corresponding role, remove the user from the group. |
| Property | Default |
| ---------------------------------------------- | --------- |
| `auth-ext.oauth.scopes` | `openid`, `profile`, `email`, `microprofile-jwt` |
### Untested
### OAuth Synchronization
| Property | Default | Description |
| ----------------------------------------- | --------------- | ----------- |
| `keycloak-ext.keycloak.enabled` | `false` | Enable Keycloak integration, overriding and extending the OOTB Keycloak provider (*untested*). |
| `keycloak-ext.keycloak.priority` | `-5` | The order of configurable adapters to use with the application. Only the lowest priority enabled adapter will be used. Values of `1`+ will only load if the OOTB adapter is disabled. |
The following properties provide the core functionality of this extension. That is role synchronization.
| Property | Default | Description |
| --------------------------------------------- | ------------ | ----------- |
| `auth-ext.sync.user.createMissing` | `true` | If the user is authenticated, the user may be created in APS. |
| `auth-ext.sync.user.requireOidcGroup` | | This is only applicable when `createMissing` is `true`. If this is unset or the OAuth Authorization Server gives the user the specified group/role, then the user record will be created in APS. |
| `auth-ext.sync.user.clearNewUserGroups` | `true` | This is only applicable when `createMissing` is `true`. All default APS groups will be deleted from the new user record. |
| `auth-ext.sync.group.createMissing` | `true` | If a filtered and translated OIDC group has no corresponding APS group, a group will be created in APS. See `auth-ext.sync.group.capabilities.patterns` for whether that group will be an APS Organization or APS Capability. |
| `auth-ext.sync.group.additions` | `true` | If the user isn't in an APS group but OAuth claims the OIDC group, then add them to it. |
| `auth-ext.sync.group.removals` | `true` | If the user is in APS group but OAuth claims no OIDC group, then remove them from it. |
| `auth-ext.sync.group.internal` | `false` | When considering groups for creation or user membership, include internal groups. Internal groups are ones without an `externalId`. |
| `auth-ext.sync.group.internal.externalize` | `false` | This is only applicable when `internal` is `true`. If an internal group is encountered during the operation of this extension, make it external with the current `externalId`. |
| `auth-ext.sync.group.tenantize` | `false` | If a group without a tenant is encountered during the operation of this extension, make it part of the selected tenant. |
| `auth-ext.sync.group.include.patterns` | | A comma delimited set of regular expression patterns on what OIDC groups to include. This is processed before `translate` processing. A blank value matches everything. If anything is specified, then only matches could possibly be included. Any matches of the `exclude` property patterns always override though. |
| `auth-ext.sync.group.exclude.patterns` | | A comma delimited set of regular expression patterns on what OIDC groups to exclude. This is processed before `translate` processing. A blank value matches nothing (includes all that pass the `include` constraint). If anything is specified and `include` is empty, then all non-matches are included. If both are specified, `exclude` matches override `include` matches. |
| `auth-ext.sync.group.translate.patterns` | | A comma delimited set of regular expression patterns for the translation (reformatting) of OIDC groups to APS groups. This list corresponds to the `replacements` property and must have the same number of commas. |
| `auth-ext.sync.group.translate.replacements` | | A comma delimited set of regular expression replacement strings for the translation (reformatting) of OIDC groups to APS groups. This list corresponds to the `patterns` property and must have the same number of commas. |
| `auth-ext.sync.group.capability.patterns` | `Superusers` | A comma delimited set of regular expression patterns on what translated OIDC groups to associate with APS Capability Groups instead of APS Organization Groups (default). This is processed after `translate` processing. |
### Authentication Data Fixers
#### Administrator Password Fixer
This fixer does not execute unless the `auth-ext.reset.admin.password` property is explicitly set. It is meant to be set for a single run to fix scenarios when a non-OAuth administrator cannot access the system. This is useful when your OAuth configuration isn't working and you need to reset your non-OAuth administrator's password.
| Property | Default |
| --------------------------------- | ------------------------ |
| `auth-ext.reset.admin.username` | `admin@app.activiti.com` |
| `auth-ext.reset.admin.password` | |
#### Administrator Members Fixer
This fixer does not execute unless the `auth-ext.default.admin-users` property is explicitly set. It is meant to be set for a single run to add both non-OAuth and OAuth users to an administrator group. This is useful when OAuth is misconfigured and all administrators lose their administrator rights.
| Property | Default | Description |
| ------------------------------------ | ------------ | ----------- |
| `auth-ext.default.admins.users` | | A comma delimited list of user emails. |
| `auth-ext.group.admins.name` | `Superusers` | The APS Group (Capability or Organization) for the specified users to be members. |
#### Administrator Group Fixer
This fixer does not execute unless the `auth-ext.group.admins.validate` property is set to `true`. It is meant to be set for a single run to correct the specified group for administration access. This is useful if you accidentally delete the administrative APS Capability Group, typically called `Administrator` or `Superusers`.
| Property | Default | Description |
| ----------------------------------------- | ------------------------ | ----------- |
| `auth-ext.group.admins.validate` | `false` |
| `auth-ext.group.admins.name` | `Superusers` | The APS Capability Group of which to grant all capabilities. |

178
dependency-reduced-pom.xml Normal file
View File

@@ -0,0 +1,178 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8.activiti</groupId>
<artifactId>keycloak-activiti-app-ext</artifactId>
<name>Keycloak Authentication &amp; Authorization for APS</name>
<version>1.4-SNAPSHOT</version>
<description>An Alfresco Process Service App extension providing improved Keycloak/AIS support.</description>
<url>https://bitbucket.org/inteligr8/keycloak-activiti-app-ext</url>
<developers>
<developer>
<id>brian.long</id>
<name>Brian Long</name>
<email>brian@inteligr8.com</email>
<url>https://twitter.com/brianmlong</url>
</developer>
</developers>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007</name>
<url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
</license>
</licenses>
<scm>
<connection>scm:git:https://bitbucket.org/inteligr8/keycloak-activiti-app-ext.git</connection>
<developerConnection>scm:git:git@bitbucket.org:inteligr8/keycloak-activiti-app-ext.git</developerConnection>
<url>https://bitbucket.org/inteligr8/keycloak-activiti-app-ext</url>
</scm>
<organization>
<name>Inteligr8</name>
<url>https://www.inteligr8.com</url>
</organization>
<build>
<plugins>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.0</version>
<executions>
<execution>
<id>shade-jar</id>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<relocations>
<relocation>
<pattern />
<shadedPattern>shaded.keycloak.</shadedPattern>
<excludes>
<exclude>com.activiti.conf.*</exclude>
<exclude>com.activiti.extension.conf.*</exclude>
<exclude>com.inteligr8.activiti.**</exclude>
<exclude>META-INF/**/*</exclude>
</excludes>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>ossrh-release</id>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>source</id>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>javadoc</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<show>public</show>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.7.0</version>
<executions>
<execution>
<id>ossrh-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://s01.oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
</profile>
</profiles>
<repositories>
<repository>
<id>alfresco-private</id>
<url>https://artifacts.alfresco.com/nexus/content/groups/private</url>
</repository>
<repository>
<id>activiti-releases</id>
<url>https://artifacts.alfresco.com/nexus/content/repositories/activiti-enterprise-releases</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
<version>6.3.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.activiti</groupId>
<artifactId>activiti-app</artifactId>
<version>24.3.0</version>
<classifier>classes</classifier>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>aspose-transformation</artifactId>
<groupId>com.activiti</groupId>
</exclusion>
<exclusion>
<artifactId>aoservices</artifactId>
<groupId>org.alfresco.officeservices</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<maven.compiler.source>17</maven.compiler.source>
<keycloak.version>23.0.7</keycloak.version>
<maven.compiler.target>17</maven.compiler.target>
<slf4j.version>1.7.36</slf4j.version>
<spring-security-oauth2.version>6.3.2</spring-security-oauth2.version>
<aps.version>24.3.0</aps.version>
</properties>
</project>

399
pom.xml
View File

@@ -1,98 +1,301 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8.activiti</groupId>
<artifactId>keycloak-activiti-app-ext</artifactId>
<version>1.2.0</version>
<name>Keycloak Authentication &amp; Authorization for APS</name>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.release>11</maven.compiler.release>
<aps.version>1.11.1.1</aps.version>
<keycloak.version>6.0.1</keycloak.version>
<spring-security-oauth2.version>2.0.17.RELEASE</spring-security-oauth2.version>
<slf4j.version>1.7.26</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring-security-oauth2.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>${keycloak.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.activiti</groupId>
<artifactId>activiti-app</artifactId>
<version>${aps.version}</version>
<classifier>classes</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.activiti</groupId>
<artifactId>activiti-app-logic</artifactId>
<version>${aps.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.repaint.maven</groupId>
<artifactId>tiles-maven-plugin</artifactId>
<version>2.21</version>
<extensions>true</extensions>
<configuration>
<filtering>true</filtering>
<tiles>
<tile>com.inteligr8:maven-public-deploy-tile:[1.0.0,2.0.0)</tile>
</tiles>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>alfresco-public</id>
<url>https://artifacts.alfresco.com/nexus/content/repositories/public</url>
</repository>
<repository>
<id>activiti-releases</id>
<url>https://artifacts.alfresco.com/nexus/content/repositories/activiti-enterprise-releases</url>
</repository>
<repository>
<id>inteligr8-releases</id>
<url>https://repos.inteligr8.com/nexus/repository/inteligr8-private</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>inteligr8-releases</id>
<url>https://repos.inteligr8.com/nexus/repository/inteligr8-public</url>
</repository>
<snapshotRepository>
<id>inteligr8-snapshots</id>
<url>https://repos.inteligr8.com/nexus/repository/inteligr8-snapshots</url>
</snapshotRepository>
</distributionManagement>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8.activiti</groupId>
<artifactId>auth-activiti-app-ext</artifactId>
<version>2.1.2</version>
<name>Authentication &amp; Authorization for APS</name>
<description>An Alfresco Process Service App extension providing improved authentication and authorization support.</description>
<url>https://git.inteligr8.com/inteligr8/auth-activiti-app-ext</url>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007</name>
<url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
</license>
</licenses>
<scm>
<connection>scm:git:https://git.inteligr8.com/inteligr8/auth-activiti-app-ext.git</connection>
<developerConnection>scm:git:git@git.inteligr8.com:inteligr8/auth-activiti-app-ext.git</developerConnection>
<url>https://git.inteligr8.com/inteligr8/auth-activiti-app-ext</url>
</scm>
<organization>
<name>Inteligr8</name>
<url>https://www.inteligr8.com</url>
</organization>
<developers>
<developer>
<id>brian.long</id>
<name>Brian Long</name>
<email>brian@inteligr8.com</email>
<url>https://twitter.com/brianmlong</url>
</developer>
</developers>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.release>17</maven.compiler.release>
<aps.version>25.1.1</aps.version>
<!-- for RAD -->
<tomcat-rad.version>10-2.2</tomcat-rad.version>
<aps.hotswap.enabled>false</aps.hotswap.enabled>
<aps.tomcat.opts.base>-Dspring.main.allow-circular-references=true \
-Dhibernate.dialect=org.hibernate.dialect.PostgreSQLDialect \
-Dauth-ext.external.id=keycloak \
-Dauth-ext.sync.group.translate.patterns=aps-admin \
-Dauth-ext.sync.group.translate.replacements=Superusers \
-Dauth-ext.group.admins.validate=true</aps.tomcat.opts.base>
<aps.timeout>120000</aps.timeout>
<keycloak.realm>my-app</keycloak.realm>
<oauth.client.id>aps-app-public</oauth.client.id>
<oauth.client.secret></oauth.client.secret>
</properties>
<dependencies>
<!-- Needed for Activiti App Identity Service inheritance/override -->
<!-- includes activiti-app-logic for API -->
<dependency>
<groupId>com.activiti</groupId>
<artifactId>activiti-app</artifactId>
<version>${aps.version}</version>
<classifier>classes</classifier>
<scope>provided</scope>
<exclusions>
<!-- not necessary to download for building -->
<exclusion>
<groupId>com.activiti</groupId>
<artifactId>aspose-transformation</artifactId>
</exclusion>
<exclusion>
<groupId>org.alfresco.officeservices</groupId>
<artifactId>aoservices</artifactId>
</exclusion>
<!-- very old and overrides real spring version -->
<exclusion>
<groupId>com.ryantenney.metrics</groupId>
<artifactId>metrics-spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.inteligr8.activiti</groupId>
<artifactId>multiext-activiti-app-ext</artifactId>
<version>1.0.0</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.repaint.maven</groupId>
<artifactId>tiles-maven-plugin</artifactId>
<version>2.40</version>
<extensions>true</extensions>
<configuration>
<tiles>
<!-- Documentation: https://bitbucket.org/inteligr8/ootbee-beedk/src/stable/beedk-aps-ext-rad-tile -->
<!--
<tile>com.inteligr8.ootbee:beedk-aps-ext-rad-tile:[1.1.0,2.0.0)</tile>
-->
<tile>com.inteligr8.ootbee:beedk-aps-ext-rad-tile:1.1-SNAPSHOT</tile>
</tiles>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>activiti-oauth-confidential</id>
<activation>
<property>
<name>secret</name>
</property>
</activation>
<properties>
<oauth.client.id>aps-app-confidential</oauth.client.id>
<oauth.client.secret>a-secret</oauth.client.secret>
</properties>
</profile>
<profile>
<id>activiti-oauth-legacy</id>
<activation>
<property>
<name>rad</name>
<value>!spring</value>
</property>
</activation>
<properties>
<aps.tomcat.opts>${aps.tomcat.opts.base} \
-Dactiviti.identity-service.enabled=true \
-Dactiviti.identity-service.realm=${keycloak.realm} \
-Dactiviti.identity-service.auth-server-url=http://host.docker.internal:${keycloak.server.port} \
-Dactiviti.identity-service.resource=${oauth.client.id} \
-Dactiviti.identity-service.credentials.secret=${oauth.client.secret} \
-Dactiviti.use-browser-based-logout=true \
-Dalfresco.content.sso.redirect_uri=http://loalhost:8080/activiti-app/app/rest/integration/sso/confirm-auth-request</aps.tomcat.opts>
</properties>
</profile>
<profile>
<id>activiti-oauth-spring</id>
<activation>
<property>
<name>rad</name>
<value>spring</value>
</property>
</activation>
<properties>
<aps.tomcat.opts>${aps.tomcat.opts.base} \
-Dsecurity.oauth2.authentication.enabled=true \
-Dsecurity.oauth2.client.registration.my-app.client-id=${oauth.client.id} \
-Dsecurity.oauth2.client.registration.my-app.client-secret=${oauth.client.secret} \
-Dsecurity.oauth2.client.registration.my-app.provider=aps-app \
-Dsecurity.oauth2.client.provider.aps-app.issuer_uri=http://host.docker.internal:${keycloak.server.port}/realms/${keycloak.realm}</aps.tomcat.opts>
</properties>
</profile>
<profile>
<id>rad-keycloak</id>
<activation>
<property>
<name>rad</name>
</property>
</activation>
<properties>
<!-- Due to SSL restricitons in previous versions, testing against keyclaok is near impossible. -->
<!-- This module should still work against nearly all versions of Keycloak that support the OIDC standards -->
<keycloak.server.version>26.2</keycloak.server.version>
<keycloak.server.port>8081</keycloak.server.port>
</properties>
<build>
<plugins>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.46.0</version>
<executions>
<execution>
<id>run-keycloak</id>
<phase>test-compile</phase>
<goals><goal>start</goal></goals>
<configuration>
<images>
<image>
<name>keycloak/keycloak:${keycloak.server.version}</name>
<alias>keycloak</alias>
<run>
<cmd>start-dev --import-realm</cmd>
<env>
<KC_BOOTSTRAP_ADMIN_USERNAME>admin</KC_BOOTSTRAP_ADMIN_USERNAME>
<KC_BOOTSTRAP_ADMIN_PASSWORD>admin</KC_BOOTSTRAP_ADMIN_PASSWORD>
</env>
<ports>
<port>${keycloak.server.port}:8080</port>
</ports>
<network>
<mode>custom</mode>
<name>${project.artifactId}</name>
</network>
<extraHosts>
<host>host.docker.internal:host-gateway</host>
</extraHosts>
<volumes>
<bind>
<volume>${project.basedir}/src/test/resources/keycloak-import:/opt/keycloak/data/import:ro</volume>
</bind>
</volumes>
</run>
</image>
</images>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>ossrh-release</id>
<properties>
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>source</id>
<phase>package</phase>
<goals><goal>jar-no-fork</goal></goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>javadoc</id>
<phase>package</phase>
<goals><goal>jar</goal></goals>
<configuration>
<show>public</show>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign</id>
<phase>verify</phase>
<goals><goal>sign</goal></goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.7.0</version>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://s01.oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
<executions>
<execution>
<id>ossrh-deploy</id>
<phase>deploy</phase>
<goals><goal>deploy</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<repositories>
<repository>
<id>activiti-releases</id>
<url>https://artifacts.alfresco.com/nexus/content/repositories/activiti-enterprise-releases</url>
</repository>
</repositories>
</project>

74
rad.ps1 Normal file
View File

@@ -0,0 +1,74 @@
function discoverArtifactId {
$script:ARTIFACT_ID=(mvn -q -Dexpression=project"."artifactId -DforceStdout help:evaluate)
}
function rebuild {
echo "Rebuilding project ..."
mvn process-classes
}
function start_ {
echo "Rebuilding project and starting Docker containers to support rapid application development ..."
mvn -Drad process-classes
}
function start_log {
echo "Rebuilding project and starting Docker containers to support rapid application development ..."
mvn -Drad "-Ddocker.showLogs" process-classes
}
function stop_ {
discoverArtifactId
echo "Stopping Docker containers that supported rapid application development ..."
docker container ls --filter name=${ARTIFACT_ID}-*
echo "Stopping containers ..."
docker container stop (docker container ls -q --filter name=${ARTIFACT_ID}-*)
echo "Removing containers ..."
docker container rm (docker container ls -aq --filter name=${ARTIFACT_ID}-*)
}
function tail_logs {
param (
$container
)
discoverArtifactId
docker container logs -f (docker container ls -q --filter name=${ARTIFACT_ID}-${container})
}
function list {
discoverArtifactId
docker container ls --filter name=${ARTIFACT_ID}-*
}
switch ($args[0]) {
"start" {
start_
}
"start_log" {
start_log
}
"stop" {
stop_
}
"restart" {
stop_
start_
}
"rebuild" {
rebuild
}
"tail" {
tail_logs $args[1]
}
"containers" {
list
}
default {
echo "Usage: .\rad.ps1 [ start | start_log | stop | restart | rebuild | tail {container} | containers ]"
}
}
echo "Completed!"

71
rad.sh Normal file
View File

@@ -0,0 +1,71 @@
#!/bin/bash
discoverArtifactId() {
local ARTIFACT_ID=`mvn -q -Dexpression=project.artifactId -DforceStdout help:evaluate`
}
rebuild() {
echo "Rebuilding project ..."
mvn process-test-classes
}
start() {
echo "Rebuilding project and starting Docker containers to support rapid application development ..."
mvn -Drad process-test-resources
}
start_log() {
echo "Rebuilding project and starting Docker containers to support rapid application development ..."
mvn -Drad -Ddocker.showLogs process-test-classes
}
stop() {
discoverArtifactId
echo "Stopping Docker containers that supported rapid application development ..."
docker container ls --filter name="^/${ARTIFACT_ID}"
echo "Stopping containers ..."
docker container stop `docker container ls -q --filter name="^/${ARTIFACT_ID}"`
echo "Removing containers ..."
docker container rm `docker container ls -aq --filter name="^/${ARTIFACT_ID}"`
}
tail_logs() {
discoverArtifactId
docker container logs -f `docker container ls -q --filter name="^/${ARTIFACT_ID}-$1$"`
}
list() {
discoverArtifactId
docker container ls --filter name="^/${ARTIFACT_ID}"
}
case "$1" in
start)
start
;;
start_log)
start_log
;;
stop)
stop
;;
restart)
stop
start
;;
rebuild)
rebuild
;;
tail)
tail_logs $2
;;
containers)
list
;;
*)
echo "Usage: ./rad.sh [ start | start_log | stop | restart | rebuild | tail {container} | containers ]"
exit 1
esac
echo "Completed!"

View File

@@ -1,57 +0,0 @@
package com.activiti.conf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import com.inteligr8.activiti.ActivitiSecurityConfigAdapter;
/**
* This class/bean executes the OOTB security configuration without the
* override, so you can still use its OOTB features. This will allow you to
* enable/disable features, chain them, and uset he OOTB features as a
* fallback or failsafe.
*
* This class must be in the com.activiti.conf package so it can use protected
* fields and methods of the OOTB class instance.
*
* @author brian@inteligr8.com
* @see com.activiti.conf.SecurityConfiguration
*/
@Component
public class ActivitiOotbSecurityConfigurationAdapter implements ActivitiSecurityConfigAdapter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${keycloak-ext.ootbSecurityConfig.enabled:true}")
private boolean enabled;
@Autowired
private SecurityConfiguration ootbSecurityConfig;
@Override
public boolean isEnabled() {
return this.enabled;
}
public int getPriority() {
return 0;
}
@Override
public void configureGlobal(AuthenticationManagerBuilder authmanBuilder, UserDetailsService userDetailsService) {
this.logger.trace("configureGlobal()");
this.logger.info("Using OOTB authentication");
// unset override (which has already been called in order to get here)
this.ootbSecurityConfig.securityConfigOverride = null;
this.ootbSecurityConfig.configureGlobal(authmanBuilder);
}
}

View File

@@ -0,0 +1,35 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.activiti.extension.conf;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FullyQualifiedAnnotationBeanNameGenerator;
/**
* A means for injecting packages to scan for the Spring context.
*
* @author brian@inteligr8.com
*/
@Configuration
@ComponentScan(
basePackages = {
"com.inteligr8.activiti.auth"
},
nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class
)
public class AuthExtSpringComponentScanner {
}

View File

@@ -1,10 +0,0 @@
package com.activiti.extension.conf;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"com.inteligr8.activiti"})
public class KeycloakExtSpringComponentScanner {
}

View File

@@ -1,128 +0,0 @@
package com.inteligr8.activiti;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.activiti.domain.idm.Group;
import com.activiti.domain.idm.GroupCapability;
import com.activiti.domain.idm.Tenant;
import com.activiti.service.api.GroupService;
/**
* This class/bean overrides the APS security configuration with a collection
* of implementations. The OOTB extension only provides one override. This
* uses that extension point, but delegates it out to multiple possible
* implementations.
*
* Order cannot be controlled, so it should not be assumed in any adapter
* implementation.
*
* @author brian@inteligr8.com
*/
@Component
public class ActivitiAppAdminGroupFixer implements DataFixer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final List<String> adminCapabilities = Arrays.asList(
"access-all-models-in-tenant",
"access-editor",
"access-reports",
"publish-app-to-dashboard",
"tenant-admin",
"tenant-admin-api",
"upload-license");
@Autowired(required = false)
private GroupService groupService;
@Autowired
private TenantFinderService tenantFinderService;
@Value("${keycloak-ext.group.admins.name:admins}")
private String adminGroupName;
@Value("${keycloak-ext.group.admins.externalId:#{null}}")
private String adminGroupExternalId;
@Value("${keycloak-ext.group.admins.validate:false}")
private boolean validateAdministratorsGroup;
@Override
public void fix() {
this.logger.trace("fix()");
if (this.logger.isTraceEnabled())
this.logGroups();
if (this.validateAdministratorsGroup)
this.validateAdmins();
}
private void logGroups() {
if (this.groupService == null)
return;
Collection<Tenant> tenants = this.tenantFinderService.getTenants();
for (Tenant tenant : tenants) {
this.logger.trace("Tenant: {} => {}", tenant.getId(), tenant.getName());
this.logger.trace("Functional groups: {}", this.toGroupNames(this.groupService.getFunctionalGroups(tenant.getId())));
this.logger.trace("System groups: {}", this.toGroupNames(this.groupService.getSystemGroups(tenant.getId())));
}
this.logger.trace("Tenant: null");
this.logger.trace("Functional groups: {}", this.toGroupNames(this.groupService.getFunctionalGroups(null)));
this.logger.trace("System groups: {}", this.toGroupNames(this.groupService.getSystemGroups(null)));
}
private void validateAdmins() {
if (this.groupService == null)
return;
Long tenantId = this.tenantFinderService.findTenantId();
Group group = this.groupService.getGroupByExternalIdAndTenantId(this.adminGroupExternalId, tenantId);
if (group == null) {
List<Group> groups = this.groupService.getGroupByNameAndTenantId(this.adminGroupName, tenantId);
if (!groups.isEmpty())
group = groups.iterator().next();
}
if (group == null) {
this.logger.info("Creating group: {} ({})", this.adminGroupName, this.adminGroupExternalId);
if (this.adminGroupExternalId != null) {
group = this.groupService.createGroupFromExternalStore(
this.adminGroupExternalId, tenantId, Group.TYPE_SYSTEM_GROUP, null, this.adminGroupName, new Date());
} else {
group = this.groupService.createGroup(this.adminGroupName, tenantId, Group.TYPE_SYSTEM_GROUP, null);
}
}
this.logger.debug("Checking group capabilities: {}", group.getName());
Group groupWithCaps = this.groupService.getGroup(group.getId(), false, true, false, false);
Set<String> adminCaps = new HashSet<>(this.adminCapabilities);
for (GroupCapability cap : groupWithCaps.getCapabilities())
adminCaps.remove(cap.getName());
if (!adminCaps.isEmpty()) {
this.logger.info("Granting group '{}' capabilities: {}", group.getName(), adminCaps);
this.groupService.addCapabilitiesToGroup(group.getId(), new ArrayList<>(adminCaps));
}
}
private Collection<String> toGroupNames(Collection<Group> groups) {
List<String> groupNames = new ArrayList<>(groups.size());
for (Group group : groups)
groupNames.add(group.getName() + " [" + group.getExternalId() + "]");
return groupNames;
}
}

View File

@@ -1,86 +0,0 @@
package com.inteligr8.activiti;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.activiti.domain.idm.Group;
import com.activiti.domain.idm.User;
import com.activiti.service.api.GroupService;
import com.activiti.service.api.UserService;
/**
* This class/bean overrides the APS security configuration with a collection
* of implementations. The OOTB extension only provides one override. This
* uses that extension point, but delegates it out to multiple possible
* implementations.
*
* Order cannot be controlled, so it should not be assumed in any adapter
* implementation.
*
* @author brian@inteligr8.com
*/
@Component
public class ActivitiAppAdminMembersFixer implements DataFixer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired(required = false)
private UserService userService;
@Autowired(required = false)
private GroupService groupService;
@Autowired
private TenantFinderService tenantFinderService;
@Value("${keycloak-ext.default.admins.users:#{null}}")
private String adminUserStrs;
@Value("${keycloak-ext.group.admins.name:admins}")
private String adminGroupName;
@Value("${keycloak-ext.group.admins.externalId:#{null}}")
private String adminGroupExternalId;
@Override
public void fix() {
this.logger.trace("fix()");
if (this.adminUserStrs != null && this.adminUserStrs.length() > 0)
this.associateAdmins();
}
private void associateAdmins() {
if (this.userService == null || this.groupService == null)
return;
List<String> adminUsers = Arrays.asList(this.adminUserStrs.split(","));
if (adminUsers.isEmpty())
return;
Long tenantId = this.tenantFinderService.findTenantId();
List<Group> groups;
Group group1 = this.groupService.getGroupByExternalIdAndTenantId(this.adminGroupExternalId, tenantId);
if (group1 != null) {
groups = Arrays.asList(group1);
} else {
groups = this.groupService.getGroupByNameAndTenantId(this.adminGroupName, tenantId);
}
this.logger.debug("Found {} admin group(s)", groups.size());
for (String email : adminUsers) {
User user = this.userService.findUserByEmail(email);
this.logger.debug("Adding {} to admin group(s)", user.getEmail());
for (Group group : groups)
this.groupService.addUserToGroup(group, user);
}
}
}

View File

@@ -1,38 +0,0 @@
package com.inteligr8.activiti;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* @author brian@inteligr8.com
*/
public interface ActivitiSecurityConfigAdapter extends Comparable<ActivitiSecurityConfigAdapter> {
/**
* Is the adapter enabled? This allows for configurable enablement.
*
* @return true if enabled; false otherwise
*/
boolean isEnabled();
/**
* The lower the value, the higher the priority. The OOTB security
* configuration uses priority 0. Use negative values to supersede it.
* Anything with equal priorities should be considered unordered and may
* execute in a random order.
*
* @return A priority; may be negative or positive
*/
int getPriority();
/**
* @see com.activiti.api.security.AlfrescoSecurityConfigOverride
*/
void configureGlobal(AuthenticationManagerBuilder authmanBuilder, UserDetailsService userDetailsService);
@Override
default int compareTo(ActivitiSecurityConfigAdapter adapter) {
return Integer.compare(this.getPriority(), adapter.getPriority());
}
}

View File

@@ -1,7 +0,0 @@
package com.inteligr8.activiti;
public interface DataFixer {
void fix();
}

View File

@@ -1,59 +0,0 @@
package com.inteligr8.activiti;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import com.activiti.api.security.AlfrescoSecurityConfigOverride;
/**
* This class/bean overrides the APS security configuration with a collection
* of implementations. The OOTB extension only provides one override. This
* uses that extension point, but delegates it out to multiple possible
* implementations.
*
* Order cannot be controlled, so it should not be assumed in any adapter
* implementation.
*
* @author brian@inteligr8.com
*/
@Component
public class Inteligr8SecurityConfigurationRegistry implements AlfrescoSecurityConfigOverride {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private List<ActivitiSecurityConfigAdapter> adapters;
@Autowired(required = false)
private List<DataFixer> fixers;
@Override
public void configureGlobal(AuthenticationManagerBuilder authmanBuilder, UserDetailsService userDetailsService) {
this.logger.trace("configureGlobal()");
Collections.sort(this.adapters);
if (this.fixers != null) {
for (DataFixer fixer : this.fixers)
fixer.fix();
}
for (ActivitiSecurityConfigAdapter adapter : this.adapters) {
if (adapter.isEnabled()) {
this.logger.info("Security adapter enabled: {}", adapter.getClass());
adapter.configureGlobal(authmanBuilder, userDetailsService);
break;
} else {
this.logger.info("Security adapter disabled: {}", adapter.getClass());
}
}
}
}

View File

@@ -1,79 +0,0 @@
package com.inteligr8.activiti.ais;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import com.activiti.api.msmt.MsmtTenantResolver;
import com.activiti.conf.MsmtProperties;
import com.activiti.security.identity.service.authentication.provider.IdentityServiceAuthenticationProvider;
import com.inteligr8.activiti.ActivitiSecurityConfigAdapter;
import com.inteligr8.activiti.auth.Authenticator;
import com.inteligr8.activiti.auth.InterceptingAuthenticationProvider;
/**
* This class/bean injects a custom AIS authentication provider into the
* security configuration.
*
* @author brian@inteligr8.com
* @see com.activiti.security.identity.service.authentication.provider.IdentityServiceAuthenticationProvider
*/
@Component
public class IdentityServiceSecurityConfigurationAdapter implements ActivitiSecurityConfigAdapter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${keycloak-ext.ais.enabled:false}")
private boolean enabled;
// this assures execution before the OOTB impl (-10 < 0)
@Value("${keycloak-ext.ais.priority:-10}")
private int priority;
@Autowired
protected MsmtProperties msmtProperties;
@Autowired(required = false) // Only when multi-schema multi-tenant is enabled
protected MsmtTenantResolver tenantResolver;
@Autowired
@Qualifier("keycloak-ext.activiti-app.authenticator")
private Authenticator authenticator;
protected Authenticator getAuthenticator() {
return this.authenticator;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) {
this.logger.trace("configureGlobal()");
this.logger.info("Using AIS authentication extension, featuring creation of missing users and authority synchronization");
IdentityServiceAuthenticationProvider provider = new IdentityServiceAuthenticationProvider();
if (this.msmtProperties.isMultiSchemaMultiTenantEnabled())
provider.setTenantResolver(this.tenantResolver);
provider.setUserDetailsService(userDetailsService);
provider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(new InterceptingAuthenticationProvider(provider, this.getAuthenticator()));
}
}

View File

@@ -0,0 +1,144 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.activiti.auth;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.activiti.domain.idm.Group;
import com.activiti.domain.idm.GroupCapability;
import com.activiti.domain.idm.Tenant;
import com.activiti.service.api.GroupService;
import com.inteligr8.activiti.auth.service.TenantFinderService;
/**
* This class/bean attempts to fix the administrative group in APS. This may
* be used if your OAuth configuration leaves you without any administrative
* groups.
*
* @author brian@inteligr8.com
*/
@Component
public class ActivitiAppAdministratorGroupFixer implements DataFixer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final List<String> adminCapabilities = Arrays.asList(
"access-all-models-in-tenant",
"access-editor",
"access-reports",
"publish-app-to-dashboard",
"tenant-admin",
"tenant-admin-api",
"upload-license");
@Autowired(required = false)
private GroupService groupService;
@Autowired
private TenantFinderService tenantFinderService;
@Value("${auth-ext.group.admins.name:Superusers}")
private String adminGroupName;
@Value("${auth-ext.externalId:oauth}")
protected String externalIdmSource;
@Value("${auth-ext.group.admins.validate:false}")
private boolean validateAdministratorsGroup;
@Override
public void fix() {
this.logger.trace("fix()");
if (this.groupService == null)
return;
if (this.logger.isTraceEnabled())
this.logGroups();
if (this.validateAdministratorsGroup)
this.validateAdmins(this.externalIdmSource + "_" + this.adminGroupName);
}
private void logGroups() {
Collection<Tenant> tenants = this.tenantFinderService.getTenants();
for (Tenant tenant : tenants) {
this.logger.trace("Tenant: {} => {}; functional groups: {}; system groups: {}",
tenant.getId(),
tenant.getName(),
this.toGroupNames(this.groupService.getFunctionalGroups(tenant.getId())),
this.toGroupNames(this.groupService.getSystemGroups(tenant.getId())));
}
this.logger.trace("Tenant: null; functional groups: {}; system groups: {}",
this.toGroupNames(this.groupService.getFunctionalGroups(null)),
this.toGroupNames(this.groupService.getSystemGroups(null)));
}
private void validateAdmins(String adminGroupExternalId) {
Long tenantId = this.tenantFinderService.findTenantId();
this.logger.trace("Looking up group by external ID in tenant: {} [{}]", adminGroupExternalId, tenantId);
Group group = this.groupService.getGroupByExternalIdAndTenantId(adminGroupExternalId, tenantId);
if (group == null) {
this.logger.trace("Lookup up group by name in tenant: {} [{}]", this.adminGroupName, tenantId);
List<Group> groups = this.groupService.getGroupByNameAndTenantId(this.adminGroupName, tenantId);
if (!groups.isEmpty())
group = groups.iterator().next();
}
if (group == null) {
this.logger.debug("Group not found; creating system/capabilities group: {} [{}]", this.adminGroupName, adminGroupExternalId);
group = this.groupService.createGroupFromExternalStore(
this.adminGroupName, tenantId, Group.TYPE_SYSTEM_GROUP, null, adminGroupExternalId, new Date());
this.logger.info("Created group: {}: {} [{}]", group.getId(), group.getName(), group.getExternalId());
} else if (group.getExternalId() == null) {
group.setExternalId(adminGroupExternalId);
this.groupService.save(group);
this.logger.info("Externalized group: {}: {} [{}]", group.getId(), group.getName(), group.getExternalId());
}
this.logger.debug("Checking group capabilities: {}", group.getName());
Group groupWithCaps = this.groupService.getGroup(group.getId(), false, true, false, false);
Set<String> adminCaps = new HashSet<>(this.adminCapabilities);
for (GroupCapability cap : groupWithCaps.getCapabilities())
adminCaps.remove(cap.getName());
if (!adminCaps.isEmpty()) {
this.logger.info("Granting group capabilities: {} => {}", group.getName(), adminCaps);
this.groupService.addCapabilitiesToGroup(group.getId(), new ArrayList<>(adminCaps));
}
}
private Collection<String> toGroupNames(Collection<Group> groups) {
List<String> groupNames = new ArrayList<>(groups.size());
for (Group group : groups)
groupNames.add(group.getName() + " [" + group.getExternalId() + "]");
return groupNames;
}
}

View File

@@ -0,0 +1,119 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.activiti.auth;
import java.util.Arrays;
import java.util.List;
import jakarta.persistence.NonUniqueResultException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.activiti.domain.idm.Group;
import com.activiti.domain.idm.User;
import com.activiti.service.api.GroupService;
import com.activiti.service.api.UserService;
import com.inteligr8.activiti.auth.service.TenantFinderService;
/**
* This class/bean attempts to add administrators to the administrative group
* in APS. This may be used if you are accidentally left without anyone with
* administrative access.
*
* @author brian@inteligr8.com
*/
@Component
public class ActivitiAppAdministratorMembersFixer implements DataFixer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired(required = false)
private UserService userService;
@Autowired(required = false)
private GroupService groupService;
@Autowired
private TenantFinderService tenantFinderService;
@Value("${auth-ext.default.admins.users:#{null}}")
private String adminUserStrs;
@Value("${auth-ext.group.admins.name:Superusers}")
private String adminGroupName;
@Value("${auth-ext.externalId:oauth}")
private String adminGroupExternalId;
@Override
public void fix() {
this.logger.trace("fix()");
if (this.userService == null || this.groupService == null)
return;
if (this.adminUserStrs == null || this.adminUserStrs.isEmpty())
return;
List<String> adminUsers = Arrays.asList(this.adminUserStrs.split(","));
if (adminUsers.isEmpty())
return;
this.associateAdmins(adminUsers);
}
private void associateAdmins(List<String> adminUsers) {
Long tenantId = this.tenantFinderService.findTenantId();
List<Group> groups = null;
try {
this.logger.trace("Looking up group by external ID in tenant: {} [{}]", this.adminGroupExternalId, tenantId);
Group agroup = this.groupService.getGroupByExternalIdAndTenantId(this.adminGroupExternalId, tenantId);
if (agroup != null)
groups = Arrays.asList(agroup);
} catch (NonUniqueResultException nure) {
// suppress
}
if (groups == null) {
this.logger.trace("Looking up group by name in tenant: {} [{}]", this.adminGroupName, tenantId);
groups = this.groupService.getGroupByNameAndTenantId(this.adminGroupName, tenantId);
}
this.logger.trace("Considering configured admin users: {}", adminUsers);
this.logger.debug("Found {} admin group(s)", groups.size());
for (String email : adminUsers) {
this.logger.trace("Looking up configured admin user in tenant: {} [{}]", email, tenantId);
User user = this.userService.findUserByEmailAndTenantId(email, tenantId);
if (user == null) {
this.logger.warn("The user with email '{}' does not exist, so they cannot be added as an administrator", email);
} else {
this.logger.debug("Adding {} to admin group(s)", user.getEmail());
for (Group group : groups) {
if (this.groupService.addUserToGroup(group, user)) {
this.logger.info("Added {} [{}] to {} [{}]", user.getEmail(), user.getId(), group.getName(), group.getId());
} else {
this.logger.trace("User already in group: {} => {}", user.getEmail(), group.getName());
}
}
}
}
}
}

View File

@@ -0,0 +1,68 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.activiti.auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.activiti.domain.idm.User;
import com.activiti.service.api.UserService;
import com.inteligr8.activiti.auth.service.TenantFinderService;
/**
* This class/bean attempts to reset the configured user's password.
*
* @author brian@inteligr8.com
*/
@Component
public class ActivitiAppAdministratorPasswordFixer implements DataFixer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired(required = false)
private UserService userService;
@Autowired
private TenantFinderService tenantFinderService;
@Value("${auth-ext.reset.admin.username:admin@app.activiti.com}")
private String adminUsername;
@Value("${auth-ext.reset.admin.password:#{null}}")
private String adminPassword;
@Override
public void fix() {
this.logger.trace("fix()");
if (this.adminPassword == null)
return;
if (this.userService == null)
return;
this.logger.debug("Considering admin username: {}", this.adminUsername);
Long tenantId = this.tenantFinderService.findTenantId();
User adminUser = this.userService.findUserByEmailAndTenantId(this.adminUsername, tenantId);
this.logger.debug("Resolved admin username ID: {} => {}", this.adminUsername, adminUser.getId());
this.userService.changePassword(adminUser.getId(), this.adminPassword);
this.logger.info("Reset the password for admin user: {}", this.adminUsername);
}
}

View File

@@ -1,14 +0,0 @@
package com.inteligr8.activiti.auth;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
public interface Authenticator {
default void preAuthenticate(Authentication authentication) throws AuthenticationException {
}
default void postAuthenticate(Authentication authentication) throws AuthenticationException {
}
}

View File

@@ -0,0 +1,40 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.activiti.auth;
import org.springframework.context.ApplicationContext;
import com.activiti.api.boot.BootstrapConfigurer;
/**
* This interface is for defining utilities that provide data-based fixes to
* APS deployments.
*
* @author brian@inteligr8.com
*/
public interface DataFixer extends BootstrapConfigurer {
/**
* The method called when the framework wants to execute the fix. This
* will be called only on startup; and on every startup.
*/
void fix();
@Override
default void applicationContextInitialized(ApplicationContext applicationContext) {
this.fix();
}
}

View File

@@ -1,49 +0,0 @@
package com.inteligr8.activiti.auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
/**
* This class/bean provides a pre/post authentication capability to the
* Spring AuthenticationProvider. The pre-authentication hook allows us to
* circumvent the problem with authenticating missing users. The
* post-authentication hook allow us to synchronize groups/authorities.
*
* @author brian@inteligr8.com
*/
public class InterceptingAuthenticationProvider implements AuthenticationProvider {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final AuthenticationProvider provider;
private final Authenticator authenticator;
public InterceptingAuthenticationProvider(AuthenticationProvider provider, Authenticator authenticator) {
this.provider = provider;
this.authenticator = authenticator;
}
@Override
public boolean supports(Class<?> authClass) {
return this.provider.supports(authClass);
}
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
this.logger.trace("authenticate({})", auth.getName());
this.authenticator.preAuthenticate(auth);
this.logger.debug("Pre-authenticated user: {}", auth.getName());
auth = this.provider.authenticate(auth);
this.logger.debug("Authenticated user '{}' with authorities: {}", auth.getName(), auth.getAuthorities());
this.authenticator.postAuthenticate(auth);
this.logger.debug("Post-authenticated user: {}", auth.getName());
return auth;
}
}

View File

@@ -0,0 +1,146 @@
package com.inteligr8.activiti.auth.oauth;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
import com.activiti.domain.idm.Capabilities;
import com.activiti.security.ActivitiAppRequestHeaderService;
import com.activiti.security.ActivitiRestAuthorizationService;
import com.activiti.security.ProtectedPaths;
import com.activiti.security.identity.service.config.IdentityServiceEnabledCondition;
import com.inteligr8.activiti.auth.service.JwtAuthenticationProvider;
import com.nimbusds.oauth2.sdk.ParseException;
/**
* The purpose of this class is to allow for the specification of a custom set
* of scopes by an APS system administrator.
*/
@Configuration
@Conditional(IdentityServiceEnabledCondition.class)
public class IdentityServiceConfigurationOverride {
public static final String OOTB_CLIENT_REGISTRATION_BEANNAME = "clientRegistration";
public static final String OVERRIDE_CLIENT_REGISTRATION_BEANNAME = "inteligr8.clientRegistration";
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ApplicationContext appContext;
@Autowired
private JwtAuthenticationProvider jwtAuthenticationProvider;
@Autowired
private ActivitiAppRequestHeaderService appRequestHeaderService;
@Autowired
private ActivitiRestAuthorizationService restAuthorizationService;
@Bean("inteligr8.clientRegistrationRepository")
@Primary
public ClientRegistrationRepository clientRegistrationRepository() {
this.logger.trace("clientRegistrationRepository()");
ClientRegistration clientRegistration = this.appContext.getBean(OVERRIDE_CLIENT_REGISTRATION_BEANNAME, ClientRegistration.class);
this.logger.debug("Creating ClientRegistrationRepository with client registration: {}: {}", clientRegistration.getRegistrationId(), clientRegistration.getScopes());
return new InMemoryClientRegistrationRepository(clientRegistration);
}
// adding `microprofile-jwt` by default, unlike OOTB
@Value("${auth-ext.oauth.scopes:openid,profile,email,microprofile-jwt}")
protected String clientScopeStr;
@Bean(OVERRIDE_CLIENT_REGISTRATION_BEANNAME)
@Primary
public ClientRegistration clientRegistration() throws ParseException, InterruptedException {
this.logger.trace("clientRegistration()");
ClientRegistration clientRegistration = this.appContext.getBean(OOTB_CLIENT_REGISTRATION_BEANNAME, ClientRegistration.class);
this.logger.debug("Cloning OOTB ClientRegistration: {}", clientRegistration);
return ClientRegistration
.withClientRegistration(clientRegistration)
.scope(StringUtils.split(this.clientScopeStr, ", "))
.build();
}
/**
* Slightly higher priority than the one provided OOTB. This allows for
* the bean injection of the `JwtAuthenticationConverter`.
*
* This is basically a copy of what is provided OOTB, but:
*
* - The ability to configure the `JwtAuthenticationConverter`.
* - Allow non-UI access to `/app/rest/*`
*
* @see com.activiti.security.identity.service.config.IdentityServiceConfigurationApi#identityServiceApiWebSecurity
*/
@Bean("inteligr8.identityServiceApiWebSecurity")
@Order(-5)
public SecurityFilterChain identityServiceApiWebSecurity(HttpSecurity http) throws Exception {
http
.securityMatchers(matchers -> {
matchers.requestMatchers(
// same as OOTB
antMatcher(ProtectedPaths.API_URL_PATH + "/**"),
// want to also allow non-UI access to the the protected API
// we do this for anything with an `Authorization` header, as the UI uses session-based authorization
new AndRequestMatcher(new RequestHeaderRequestMatcher("Authorization"), antMatcher(ProtectedPaths.APP_URL_PATH + "/rest/**"))
);
})
.csrf(csrf -> {
csrf.disable();
})
.cors(withDefaults())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // Stores no Session for API calls
.oauth2ResourceServer(oauth2 ->
oauth2.jwt(jwtConfigurer -> {
// here is where we are injecting a Spring extendible `JwtAuthenticationConverter`.
jwtConfigurer.jwtAuthenticationConverter(this.jwtAuthenticationProvider.create());
})
)
.authorizeHttpRequests(request ->
request
// same as OOTB
.requestMatchers(antMatcher(ProtectedPaths.API_URL_PATH + "/enterprise/**"))
.access(this.appRequestHeaderService)
.requestMatchers(antMatcher(ProtectedPaths.API_URL_PATH + "/**"))
.access(this.restAuthorizationService)
// borrowed from OOTB /app/rest security
.requestMatchers(antMatcher(ProtectedPaths.APP_URL_PATH + "/rest/reporting/**"))
.hasAuthority(Capabilities.ACCESS_REPORTS)
.requestMatchers(
antMatcher(ProtectedPaths.API_URL_PATH + "/**"),
antMatcher(ProtectedPaths.APP_URL_PATH + "/rest/**")
)
.authenticated()
);
return http.build();
}
}

View File

@@ -0,0 +1,375 @@
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.activiti.auth.service;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.util.Pair;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.core.ClaimAccessor;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;
import com.activiti.domain.idm.Group;
import com.activiti.domain.idm.User;
import com.activiti.service.api.GroupService;
import com.activiti.service.api.UserService;
import jakarta.annotation.PostConstruct;
import jakarta.persistence.NonUniqueResultException;
@Component
@Lazy
public class GroupSyncService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserService userService;
@Autowired
private GroupService groupService;
@Autowired
private TenantFinderService tenantFinderService;
@Value("${auth-ext.externalId:oauth}")
protected String externalIdmSource;
@Value("${auth-ext.sync.group.createMissing:true}")
protected boolean createMissing;
@Value("${auth-ext.sync.group.additions:true}")
protected boolean syncAdditions;
@Value("${auth-ext.sync.group.removals:true}")
protected boolean syncRemovals;
@Value("${auth-ext.sync.group.internal:false}")
protected boolean syncInternalGroups;
@Value("${auth-ext.sync.group.internal.externalize:false}")
protected boolean externalizeMatchingInternalGroups;
@Value("${auth-ext.sync.group.tenantize:false}")
protected boolean retenantUntenantedGroups;
@Value("${auth-ext.sync.group.translate.patterns:#{null}}")
protected String translatePatterns;
@Value("${auth-ext.sync.group.translate.replacements:#{null}}")
protected String translateReplacements;
@Value("${auth-ext.sync.group.include.patterns:#{null}}")
protected String includePatterns;
protected final Set<Pattern> includes = new HashSet<>();
@Value("${auth-ext.sync.group.exclude.patterns:#{null}}")
protected String excludePatterns;
protected final Set<Pattern> excludes = new HashSet<>();
@Value("${auth-ext.sync.group.capability.patterns:Superusers}")
protected String capabilityPatterns;
protected final Set<Pattern> capabilities = new HashSet<>();
protected final List<Pair<Pattern, String>> translations = new LinkedList<>();
@PostConstruct
public void init() {
if (this.translatePatterns != null) {
String[] regexPatternStrs = StringUtils.split(this.translatePatterns, ',');
String[] regexReplaceStrs = this.translateReplacements == null ? new String[0] : StringUtils.split(this.translateReplacements, ",");
for (int i = 0; i < regexPatternStrs.length; i++) {
Pattern regexPattern = Pattern.compile(regexPatternStrs[i]);
String regexReplace = (i < regexReplaceStrs.length) ? regexReplaceStrs[i] : "";
this.translations.add(Pair.of(regexPattern, regexReplace));
}
}
if (this.includePatterns != null) {
String[] regexPatternStrs = StringUtils.split(this.includePatterns, ',');
for (int i = 0; i < regexPatternStrs.length; i++)
this.includes.add(Pattern.compile(regexPatternStrs[i]));
}
if (this.excludePatterns != null) {
String[] regexPatternStrs = StringUtils.split(this.excludePatterns, ',');
for (int i = 0; i < regexPatternStrs.length; i++)
this.excludes.add(Pattern.compile(regexPatternStrs[i]));
}
if (this.capabilityPatterns != null) {
String[] regexPatternStrs = StringUtils.split(this.capabilityPatterns, ',');
for (int i = 0; i < regexPatternStrs.length; i++)
this.capabilities.add(Pattern.compile(regexPatternStrs[i]));
}
}
public void sync(OidcUser oidcUser) {
this.sync(oidcUser.getEmail(), oidcUser);
}
public void sync(Jwt jwt) {
this.sync(jwt.getClaim(StandardClaimNames.EMAIL), jwt);
}
public void sync(String email, ClaimAccessor claims) {
if (!claims.hasClaim("groups")) {
this.logger.warn("There is no 'groups' claim to synchronize: {}", email);
this.logger.debug("The claims available: {}", claims.getClaims().keySet());
return;
}
Set<String> oidcGroups = new HashSet<>(claims.getClaimAsStringList("groups"));
this.logger.trace("Incoming OIDC groups: {}: {}", email, oidcGroups);
oidcGroups = this.filterGroups(oidcGroups);
Set<String> translatedGroups = this.translateGroups(oidcGroups);
this.logger.debug("Filtered/translated OIDC groups: {}: {}", email, translatedGroups);
long tenantId = this.tenantFinderService.findTenantId();
// check Activiti groups
User user = this.userService.findUserByEmailAndTenantId(email, tenantId);
if (user == null) {
user = this.userService.findUserByEmail(email);
if (user == null)
throw new UsernameNotFoundException("The user could not be found: " + email);
}
User userWithGroups = this.userService.getUser(user.getId(), true);
this.logger.debug("Discovered user belongs to {} APS groups: {}", userWithGroups.getGroups().size(), user.getExternalId());
// remove any OIDC groups that the user is already considered a member of
// this will leave only OIDC groups that need to be added
for (Group group : userWithGroups.getGroups()) {
if (group.getExternalId() == null && !this.syncInternalGroups) {
this.logger.trace("Ignoring internal APS group: {} => {}", group.getId(), group.getName());
continue;
}
this.logger.trace("Inspecting APS group: {} => {} ({})", group.getId(), group.getName(), group.getExternalId());
if (group.getExternalId() != null) {
String translatedGroup = this.apsGroupExternalIdToTranslatedOidcGroup(group.getExternalId());
if (this.retenantUntenantedGroups && group.getTenantId() == null) {
this.logger.warn("Moving tenant-less APS group to tenant: {} => {}", group.getName(), tenantId);
group.setTenantId(tenantId);
group.setLastUpdate(new Date());
this.groupService.save(group);
}
if (translatedGroups.remove(translatedGroup)) {
this.logger.trace("User already belongs to APS group mapped to by (translated) OIDC group: {}: {} => {}", user.getExternalId(), translatedGroup, group.getName());
continue;
}
} else {
String translatedGroup = this.apsGroupNameToTranslatedOidcGroup(group.getName());
if (translatedGroups.remove(translatedGroup)) {
this.logger.trace("User already belongs to APS group mapped to by (translated) OIDC group: {}: {} => {}", user.getExternalId(), translatedGroup, group.getName());
if (this.externalizeMatchingInternalGroups) {
this.logger.warn("Classifying internal APS group as external: {} => {}", group.getName(), this.externalIdmSource);
// register the group as external
group.setExternalId(this.translatedOidcGroupToApsGroupExternalId(translatedGroup));
group.setLastUpdate(new Date());
this.groupService.save(group);
// internal role already existed and the user is already a member
}
continue;
} else if (!this.syncInternalGroups) {
this.logger.trace("Internal APS group membership sync disabled; not considering removal of user from APS group: {} => {}", user.getExternalId(), group.getName());
continue;
}
}
// at this point, we have a group that the user does not have a corresponding OIDC group for
if (this.syncRemovals) {
this.logger.trace("Removing user from APS group: {} => {}", user.getExternalId(), group.getName());
this.groupService.deleteUserFromGroup(group, userWithGroups);
this.logger.info("Removed user from APS group: {} => {}", user.getExternalId(), group.getName());
} else {
this.logger.debug("User/group removal sync disabled; not removing user from APS group: {} => {}", user.getExternalId(), group.getName());
}
}
// the user needs to be added to the remaining authorities
for (String translatedGroup : translatedGroups) {
this.logger.trace("Inspecting unaccounted for (translated) OIDC group: {}", translatedGroup);
Group group;
try {
group = this.groupService.getGroupByExternalIdAndTenantId(this.translatedOidcGroupToApsGroupExternalId(translatedGroup), tenantId);
} catch (NonUniqueResultException nure) {
this.logger.warn("There are multiple groups matching the (translated) OIDC group for the external system: {} [{}]; skipping consideration of OIDC group", translatedGroup, this.externalIdmSource);
continue;
}
if (group == null && this.syncInternalGroups) {
List<Group> groups = this.groupService.getGroupByNameAndTenantId(this.translatedOidcGroupToApsGroupName(translatedGroup), tenantId);
if (groups.size() > 1) {
this.logger.warn("There are multiple APS groups matching the (translated) OIDC group: {} [{}]; skipping consideration of OIDC group", translatedGroup, this.externalIdmSource);
continue;
} else if (groups.size() == 1) {
group = groups.iterator().next();
if (this.externalizeMatchingInternalGroups) {
this.logger.debug("Found an internal APS group; registering as external: {}", group.getName());
group.setExternalId(this.translatedOidcGroupToApsGroupExternalId(translatedGroup));
group.setLastSyncTimeStamp(new Date());
group.setLastUpdate(new Date());
this.groupService.save(group);
}
}
}
if (group == null) {
if (!this.createMissing) {
this.logger.debug("APS Group does not exist for (translated) OIDC group; APS group creation is disabled; OIDC group will go unrecognized: {}", translatedGroup);
continue;
}
group = this.createApsGroup(translatedGroup, tenantId);
}
if (this.syncAdditions) {
this.logger.trace("Adding user to APS group: {} => {}", user.getExternalId(), group.getName());
this.groupService.addUserToGroup(group, userWithGroups);
this.logger.info("Added user to APS group: {} => {}", user.getExternalId(), group.getName());
} else {
this.logger.debug("User/group addition sync disabled; not adding user to APS group: {} => {}", user.getExternalId(), group.getName());
}
}
}
protected Group createApsGroup(String translatedGroup, long tenantId) {
this.logger.debug("APS Group does not exist for (translated) OIDC group; will attempt to create: {}", translatedGroup);
String name = this.translatedOidcGroupToApsGroupName(translatedGroup);
String externalId = this.translatedOidcGroupToApsGroupExternalId(translatedGroup);
boolean syncAsOrg = this.isTranslatedOidcGroupToBeOrganization(translatedGroup);
this.logger.trace("Creating new APS group as {}: {}", syncAsOrg ? "organization" : "capability", translatedGroup);
int type = syncAsOrg ? Group.TYPE_FUNCTIONAL_GROUP : Group.TYPE_SYSTEM_GROUP;
Group apsGroup = this.groupService.createGroupFromExternalStore(name, tenantId, type, null, externalId, new Date());
this.logger.info("Created new APS group: {} => {} [{}]", apsGroup.getId(), apsGroup.getName(), apsGroup.getExternalId());
return apsGroup;
}
private Set<String> filterGroups(Set<String> unfilteredGroups) {
if (this.includes.isEmpty() && this.excludes.isEmpty())
return unfilteredGroups;
Set<String> filteredGroups = new HashSet<>();
for (String group : unfilteredGroups) {
boolean doInclude = this.includes.isEmpty();
for (Pattern regex : this.includes) {
Matcher matcher = regex.matcher(group);
if (matcher.matches()) {
this.logger.trace("OIDC group matched inclusion filter: {}", group);
doInclude = true;
break;
}
}
if (doInclude) {
for (Pattern regex : this.excludes) {
Matcher matcher = regex.matcher(group);
if (matcher.matches()) {
this.logger.trace("OIDC group matched exclusion filter: {}", group);
doInclude = false;
break;
}
}
if (doInclude)
filteredGroups.add(group);
}
}
return filteredGroups;
}
private Set<String> translateGroups(Set<String> untranslatedGroups) {
Set<String> translatedGroups = new HashSet<>();
for (String untranslatedGroup : untranslatedGroups) {
String translatedGroup = null;
for (Pair<Pattern, String> regex : this.translations) {
Matcher matcher = regex.getFirst().matcher(untranslatedGroup);
if (matcher.matches()) {
translatedGroup = matcher.replaceFirst(regex.getSecond());
this.logger.trace("OIDC group formatted: {} => {}", untranslatedGroup, translatedGroup);
break;
}
}
translatedGroups.add(translatedGroup == null ? untranslatedGroup : translatedGroup);
}
return translatedGroups;
}
private String translatedOidcGroupToApsGroupExternalId(String group) {
return this.externalIdmSource + "_" + group;
}
private String apsGroupExternalIdToTranslatedOidcGroup(String externalId) {
int underscorePos = externalId.indexOf('_');
return underscorePos < 0 ? externalId : externalId.substring(underscorePos + 1);
}
private String translatedOidcGroupToApsGroupName(String group) {
return group;
}
private String apsGroupNameToTranslatedOidcGroup(String externalId) {
return externalId;
}
private boolean isTranslatedOidcGroupToBeOrganization(String translatedGroup) {
if (this.capabilities.isEmpty())
return true;
for (Pattern regex : this.capabilities) {
Matcher matcher = regex.matcher(translatedGroup);
if (matcher.matches())
return false;
}
return true;
}
}

View File

@@ -0,0 +1,11 @@
package com.inteligr8.activiti.auth.service;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.oauth2.jwt.Jwt;
public interface JwtAuthenticationProvider {
Converter<Jwt, AbstractAuthenticationToken> create();
}

View File

@@ -0,0 +1,61 @@
package com.inteligr8.activiti.auth.service;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.jwt.Jwt;
import com.activiti.security.identity.service.config.JwtAuthenticationToken;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
public class SyncingJwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final UserDetailsService userDetailsService;
private final UserSyncService userSyncService;
private final GroupSyncService groupSyncService;
@Autowired
private TokenRecaller tokenRecaller;
public SyncingJwtAuthenticationConverter(UserDetailsService userDetailsService, UserSyncService userSyncService, GroupSyncService groupSyncService) {
this.userDetailsService = userDetailsService;
this.userSyncService = userSyncService;
this.groupSyncService = groupSyncService;
}
@Override
public AbstractAuthenticationToken convert(Jwt source) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("convert({}, {})", source.getId(), source.getClaimAsString(StandardClaimNames.EMAIL));
try {
this.logger.trace("jwt: {}", new ObjectMapper().registerModule(new JavaTimeModule()).writeValueAsString(source));
} catch (JsonProcessingException jpe) {
this.logger.error("error", jpe);
}
}
if (this.tokenRecaller.recall(source.getTokenValue())) {
this.logger.trace("Skipping sync for '{}' as the same token was already recently sync'd", source.getClaimAsString(StandardClaimNames.EMAIL));
} else {
this.userSyncService.sync(source);
this.groupSyncService.sync(source);
this.tokenRecaller.add(source.getTokenValue());
}
UserDetails springUser = this.userDetailsService.loadUserByUsername(source.getClaimAsString(StandardClaimNames.EMAIL));
return new JwtAuthenticationToken(
springUser,
new ArrayList<>(springUser.getAuthorities()));
}
}

View File

@@ -0,0 +1,27 @@
package com.inteligr8.activiti.auth.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;
@Component
public class SyncingJwtAuthenticationProvider implements JwtAuthenticationProvider {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserSyncService userSyncService;
@Autowired
private GroupSyncService groupSyncService;
@Override
public Converter<Jwt, AbstractAuthenticationToken> create() {
return new SyncingJwtAuthenticationConverter(this.userDetailsService, this.userSyncService, this.groupSyncService);
}
}

View File

@@ -0,0 +1,76 @@
package com.inteligr8.activiti.auth.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.stereotype.Component;
import com.activiti.security.CustomOAuth2User;
import com.activiti.security.UserDetailsService;
import com.activiti.security.identity.service.config.IdentityServiceKeycloakProperties;
/**
* This class takes precedence over the service provided by APS when the
* Activiti Identity Service configuration is enabled. When it isn't
* enabled, it will still serve as the default OIDC user service for
* Spring Security.
*
* This is only executed with non-API authentication and authorization use
* cases. API authentication/authorization uses the
* `SyncingJwtAuthenitcationConverter`.
*/
@Component
@Primary
public class SyncingUserService extends OidcUserService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserSyncService userSyncService;
@Autowired
private GroupSyncService groupSyncService;
@Autowired
private IdentityServiceKeycloakProperties identityServiceKeycloakProperties;
@Autowired
private TokenRecaller tokenRecaller;
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
this.logger.trace("loadUser({}, {})", userRequest.getIdToken().getEmail(), userRequest.getAccessToken().getScopes());
OidcUser oidcUser = super.loadUser(userRequest);
this.logger.debug("Loaded OIDC user: {}", oidcUser.getEmail());
if (this.tokenRecaller.recall(userRequest.getAccessToken().getTokenValue())) {
this.logger.trace("Skipping sync for '{}' as the same token was already recently sync'd", userRequest.getIdToken().getEmail());
} else {
this.userSyncService.sync(oidcUser);
this.groupSyncService.sync(oidcUser);
this.tokenRecaller.add(userRequest.getAccessToken().getTokenValue());
}
UserDetails springUser = this.userDetailsService.loadUserByUsername(oidcUser.getEmail());
CustomOAuth2User customOAuth2User = new CustomOAuth2User(
springUser.getAuthorities(),
oidcUser.getIdToken(),
oidcUser.getUserInfo(),
this.identityServiceKeycloakProperties.getPrincipalAttribute()
);
customOAuth2User.setUserDetails(springUser);
return customOAuth2User;
}
}

View File

@@ -1,4 +1,18 @@
package com.inteligr8.activiti;
/*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.inteligr8.activiti.auth.service;
import java.util.ArrayList;
import java.util.Collection;
@@ -14,6 +28,11 @@ import com.activiti.domain.idm.Tenant;
import com.activiti.service.idm.TenantService;
import com.activiti.service.license.LicenseService;
/**
* This service simpler tenant meta-data access.
*
* @author brian@inteligr8.com
*/
@Component
public class TenantFinderService {
@@ -25,7 +44,7 @@ public class TenantFinderService {
@Autowired(required = false)
private TenantService tenantService;
@Value("${keycloak-ext.tenant:#{null}}")
@Value("${auth-ext.tenant:#{null}}")
private String tenant;
public Long findTenantId() {

View File

@@ -0,0 +1,59 @@
package com.inteligr8.activiti.auth.service;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections4.map.PassiveExpiringMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
@Component
public class TokenRecaller {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${auth-ext.sync.resyncInMillis:300000}")
private long resyncTimeInMillis;
private PassiveExpiringMap<String, Long> tokenCache;
@PostConstruct
private void init() {
this.tokenCache = new PassiveExpiringMap<>(this.resyncTimeInMillis, TimeUnit.MILLISECONDS);
}
@Scheduled(timeUnit = TimeUnit.MINUTES, initialDelay = 10L, fixedDelay = 5L)
private void reap() {
int tokens = this.tokenCache.size();
this.logger.trace("Reaping token cache of size: {}", tokens);
synchronized (this.tokenCache) {
// clear expired keys
this.tokenCache.entrySet();
}
this.logger.debug("Reaped {} expired tokens from cache", this.tokenCache.size() - tokens);
}
public void add(String token) {
synchronized (this.tokenCache) {
this.tokenCache.put(token, System.currentTimeMillis() + this.resyncTimeInMillis);
}
}
public boolean recall(String token) {
Long expirationTimeMillis = this.tokenCache.get(token);
if (expirationTimeMillis == null) {
return false;
} else if (expirationTimeMillis < System.currentTimeMillis()) {
return false;
} else {
return true;
}
}
}

View File

@@ -0,0 +1,128 @@
package com.inteligr8.activiti.auth.service;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.core.ClaimAccessor;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;
import com.activiti.domain.idm.Group;
import com.activiti.domain.idm.User;
import com.activiti.security.UserDetailsService;
import com.activiti.service.api.GroupService;
import com.activiti.service.api.UserService;
@Component
@Lazy
public class UserSyncService {
private final Logger logger = LoggerFactory.getLogger(UserSyncService.class);
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserService userService;
@Autowired
private GroupService groupService;
@Autowired
private TenantFinderService tenantFinderService;
@Value("${auth-ext.externalId:oauth}")
protected String externalIdmSource;
@Value("${auth-ext.sync.user.createMissing:true}")
protected boolean createMissingUser;
@Value("${auth-ext.sync.user.requireOidcGroup:#{null}}")
protected String requiredGroup;
@Value("${auth-ext.sync.user.clearNewUserGroups:true}")
protected boolean clearNewUserGroups;
public void sync(OidcUser oidcUser) {
UserDetails springUser = this.loadSpringUser(oidcUser.getEmail(), oidcUser.getGivenName(), oidcUser.getFamilyName(), oidcUser);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Loaded Spring Security user: {}: {}", springUser.getUsername(), springUser.getAuthorities());
} else {
this.logger.debug("Loaded Spring Security user: {}", springUser.getUsername());
}
}
public void sync(Jwt jwt) {
String email = jwt.getClaim(StandardClaimNames.EMAIL);
if (email == null)
throw new IllegalArgumentException("An '" + StandardClaimNames.EMAIL + "' claim is required");
String givenName = jwt.getClaim(StandardClaimNames.GIVEN_NAME);
String familyName = jwt.getClaim(StandardClaimNames.FAMILY_NAME);
UserDetails springUser = this.loadSpringUser(email, givenName, familyName, jwt);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Loaded Spring Security user: {}: {}", springUser.getUsername(), springUser.getAuthorities());
} else {
this.logger.debug("Loaded Spring Security user: {}", springUser.getUsername());
}
}
private UserDetails loadSpringUser(String email, String givenName, String familyName, ClaimAccessor claims) throws UsernameNotFoundException {
try {
UserDetails springUser = this.userDetailsService.loadUserByUsername(email);
this.logger.debug("Loaded APS user: {} => {}", email, springUser.getUsername());
return springUser;
} catch (UsernameNotFoundException unfe) {
this.logger.debug("User does not exist: {}", unfe.getMessage());
if (!this.createMissingUser)
throw unfe;
if (this.requiredGroup != null && (!claims.hasClaim("groups") || !claims.getClaimAsStringList("groups").contains(this.requiredGroup))) {
this.logger.info("User does not exist and does not have the required OIDC group to be created: {} ", email, this.requiredGroup);
throw unfe;
}
this.logger.debug("User does not exist; will attempt to create: {}", email);
User apsUser = this.createApsUser(email, givenName, familyName);
if (this.clearNewUserGroups) {
apsUser = this.userService.getUser(apsUser.getId(), true);
if (this.logger.isDebugEnabled())
this.logger.debug("User is new; clearing default groups: {}: {}", email, apsUser.getGroups().stream().map(group -> group.getName()).toList());
this.deleteApsUserGroups(apsUser);
}
return this.userDetailsService.loadByUserId(apsUser.getId());
}
}
private User createApsUser(String email, String givenName, String familyName) {
long tenantId = this.tenantFinderService.findTenantId();
User user = this.userService.createNewUserFromExternalStore(
email,
givenName,
familyName,
tenantId,
email,
this.externalIdmSource,
new Date());
this.logger.info("Created user: {} => {}", user.getId(), user.getEmail());
return user;
}
private void deleteApsUserGroups(User user) {
for (Group group : user.getGroups()) {
this.groupService.deleteUserFromGroup(group, user);
this.logger.trace("Removed user from group: {} => {}", user.getEmail(), group.getName());
}
}
}

View File

@@ -1,269 +0,0 @@
package com.inteligr8.activiti.keycloak;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessToken.Access;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.util.Pair;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import com.inteligr8.activiti.auth.Authenticator;
public abstract class AbstractKeycloakActivitiAuthenticator implements Authenticator, InitializingBean {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${keycloak-ext.createMissingUser:true}")
protected boolean createMissingUser;
@Value("${keycloak-ext.clearNewUserDefaultGroups:true}")
protected boolean clearNewUserDefaultGroups;
@Value("${keycloak-ext.createMissingGroup:true}")
protected boolean createMissingGroup;
@Value("${keycloak-ext.syncGroupAdd:true}")
protected boolean syncGroupAdd;
@Value("${keycloak-ext.syncGroupRemove:true}")
protected boolean syncGroupRemove;
@Value("${keycloak-ext.syncInternalGroups:false}")
protected boolean syncInternalGroups;
@Value("${keycloak-ext.resource.include.regex.patterns:#{null}}")
protected String resourceRegexIncludes;
@Value("${keycloak-ext.group.format.regex.patterns:#{null}}")
protected String regexPatterns;
@Value("${keycloak-ext.group.format.regex.replacements:#{null}}")
protected String regexReplacements;
@Value("${keycloak-ext.group.include.regex.patterns:#{null}}")
protected String regexIncludes;
@Value("${keycloak-ext.group.exclude.regex.patterns:#{null}}")
protected String regexExcludes;
protected final List<Pair<Pattern, String>> groupFormatters = new LinkedList<>();
protected final Set<Pattern> resourceIncludes = new HashSet<>();
protected final Set<Pattern> groupIncludes = new HashSet<>();
protected final Set<Pattern> groupExcludes = new HashSet<>();
@Override
public void afterPropertiesSet() {
if (this.regexPatterns != null) {
String[] regexPatternStrs = StringUtils.split(this.regexPatterns, ',');
String[] regexReplaceStrs = this.regexReplacements == null ? new String[0] : StringUtils.split(this.regexReplacements, ",");
for (int i = 0; i < regexPatternStrs.length; i++) {
Pattern regexPattern = Pattern.compile(regexPatternStrs[i]);
String regexReplace = (i < regexReplaceStrs.length) ? regexReplaceStrs[i] : "";
this.groupFormatters.add(Pair.of(regexPattern, regexReplace));
}
}
if (this.resourceRegexIncludes != null) {
String[] regexPatternStrs = StringUtils.split(this.resourceRegexIncludes, ',');
for (int i = 0; i < regexPatternStrs.length; i++)
this.resourceIncludes.add(Pattern.compile(regexPatternStrs[i]));
}
if (this.regexIncludes != null) {
String[] regexPatternStrs = StringUtils.split(this.regexIncludes, ',');
for (int i = 0; i < regexPatternStrs.length; i++)
this.groupIncludes.add(Pattern.compile(regexPatternStrs[i]));
}
if (this.regexExcludes != null) {
String[] regexPatternStrs = StringUtils.split(this.regexExcludes, ',');
for (int i = 0; i < regexPatternStrs.length; i++)
this.groupExcludes.add(Pattern.compile(regexPatternStrs[i]));
}
}
protected Map<String, String> getKeycloakRoles(Authentication auth) {
Map<String, String> authorities = new HashMap<>();
AccessToken atoken = this.getKeycloakAccessToken(auth);
if (atoken == null) {
this.logger.debug("Access token not available");
return null;
} else if (atoken.getRealmAccess() == null && atoken.getResourceAccess().isEmpty()) {
this.logger.debug("Access token has no role information");
return null;
} else {
if (atoken.getRealmAccess() != null) {
this.logger.debug("Access token realm roles: {}", atoken.getRealmAccess().getRoles());
Collection<String> roles = this.filterRoles(atoken.getRealmAccess().getRoles());
Map<String, String> mappedRoles = this.formatRoles(roles);
authorities.putAll(mappedRoles);
}
for (Entry<String, Access> resourceAccess : atoken.getResourceAccess().entrySet()) {
if (this.includeResource(resourceAccess.getKey())) {
this.logger.debug("Access token resources '{}' roles: {}", resourceAccess.getKey(), resourceAccess.getValue().getRoles());
Collection<String> roles = this.filterRoles(resourceAccess.getValue().getRoles());
Map<String, String> mappedRoles = this.formatRoles(roles);
authorities.putAll(mappedRoles);
}
}
this.logger.debug("Access token authorities: {}", authorities);
}
return authorities;
}
private Collection<String> filterRoles(Collection<String> unfilteredRoles) {
if (this.groupIncludes.isEmpty() && this.groupExcludes.isEmpty())
return unfilteredRoles;
Set<String> filteredRoles = new HashSet<>(unfilteredRoles.size());
for (String role : unfilteredRoles) {
boolean doInclude = this.groupIncludes.isEmpty();
for (Pattern regex : this.groupIncludes) {
Matcher matcher = regex.matcher(role);
if (matcher.matches()) {
this.logger.debug("Role matched inclusion filter: {}", role);
doInclude = true;
break;
}
}
if (doInclude) {
for (Pattern regex : this.groupExcludes) {
Matcher matcher = regex.matcher(role);
if (matcher.matches()) {
this.logger.debug("Role matched exclusion filter: {}", role);
doInclude = false;
break;
}
}
if (doInclude)
filteredRoles.add(role);
}
}
return filteredRoles;
}
private Map<String, String> formatRoles(Collection<String> unformattedRoles) {
Map<String, String> formattedRoles = new HashMap<>(unformattedRoles.size());
for (String unformattedRole : unformattedRoles) {
String formattedRole = null;
for (Pair<Pattern, String> regex : this.groupFormatters) {
Matcher matcher = regex.getFirst().matcher(unformattedRole);
if (matcher.matches()) {
this.logger.trace("Role matched formatter: {}", unformattedRole);
formattedRole = matcher.replaceFirst(regex.getSecond());
this.logger.debug("Role formatted: {}", formattedRole);
break;
}
}
formattedRoles.put(unformattedRole, formattedRole == null ? unformattedRole : formattedRole);
}
return formattedRoles;
}
private boolean includeResource(String resource) {
if (this.resourceIncludes.isEmpty())
return true;
for (Pattern resourceInclude : this.resourceIncludes) {
Matcher matcher = resourceInclude.matcher(resource);
if (matcher.matches())
return true;
}
return false;
}
protected AccessToken getKeycloakAccessToken(Authentication auth) {
KeycloakSecurityContext ksc = this.getKeycloakSecurityContext(auth);
return ksc == null ? null : ksc.getToken();
}
@SuppressWarnings("unchecked")
protected KeycloakSecurityContext getKeycloakSecurityContext(Authentication auth) {
if (auth.getCredentials() instanceof KeycloakSecurityContext) {
this.logger.debug("Found keycloak context in credentials");
return (KeycloakSecurityContext)auth.getCredentials();
} else if (auth.getPrincipal() instanceof KeycloakPrincipal) {
this.logger.debug("Found keycloak context in principal: {}", auth.getPrincipal());
return ((KeycloakPrincipal<? extends KeycloakSecurityContext>)auth.getPrincipal()).getKeycloakSecurityContext();
} else if (!(auth instanceof KeycloakAuthenticationToken)) {
this.logger.warn("Unexpected token: {}", auth.getClass());
return null;
}
KeycloakAuthenticationToken ktoken = (KeycloakAuthenticationToken)auth;
if (ktoken.getAccount() != null) {
this.logger.debug("Found keycloak context in account: {}", ktoken.getAccount().getPrincipal() == null ? null : ktoken.getAccount().getPrincipal().getName());
return ktoken.getAccount().getKeycloakSecurityContext();
} else {
this.logger.warn("Unable to find keycloak security context");
this.logger.debug("Principal: {}", auth.getPrincipal());
this.logger.debug("Account: {}", ktoken.getAccount());
if (auth.getPrincipal() != null)
this.logger.debug("Principal type: {}", auth.getPrincipal().getClass());
return null;
}
}
protected <K, V> boolean removeMapEntriesByValue(Map<K, V> map, V value) {
if (value == null)
throw new IllegalArgumentException();
int found = 0;
Iterator<Entry<K, V>> i = map.entrySet().iterator();
while (i.hasNext()) {
Entry<K, V> entry = i.next();
if (entry.getValue() != null && value.equals(entry.getValue())) {
i.remove();
found++;
}
}
return found > 0;
}
protected Set<String> toSet(Collection<? extends GrantedAuthority> grantedAuthorities) {
Set<String> authorities = new HashSet<>(Math.max(grantedAuthorities.size(), 16));
for (GrantedAuthority grantedAuthority : grantedAuthorities) {
String authority = StringUtils.trimToNull(grantedAuthority.getAuthority());
if (authority == null)
this.logger.warn("The granted authorities include an empty authority!?: '{}'", grantedAuthority.getAuthority());
authorities.add(authority);
}
return authorities;
}
}

View File

@@ -1,267 +0,0 @@
package com.inteligr8.activiti.keycloak;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.NonUniqueResultException;
import org.apache.commons.lang3.StringUtils;
import org.keycloak.representations.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import com.activiti.domain.idm.Group;
import com.activiti.domain.idm.User;
import com.activiti.service.api.GroupService;
import com.activiti.service.api.UserService;
import com.inteligr8.activiti.TenantFinderService;
/**
* This class/bean implements an Open ID Connect authenticator for Alfresco
* Process Services that supports the creation of missing users and groups and
* synchronizes user/group membership. This is configurable using several
* Spring property values starting with the `keycloak-ext.` prefix.
*
* This implements an internal Authenticator so other authenticators could be
* created in the future.
*
* FIXME This implements is not good for multi-tenancy.
*
* @author brian.long@yudrio.com
*/
@Component("keycloak-ext.activiti-app.authenticator")
@Lazy
public class KeycloakActivitiAppAuthenticator extends AbstractKeycloakActivitiAuthenticator {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final Pattern emailNamesPattern = Pattern.compile("([A-Za-z]+)[A-Za-z0-9]*\\.([A-Za-z]+)[A-Za-z0-9]*@.*");
@Autowired
private UserService userService;
@Autowired
private GroupService groupService;
@Autowired
private TenantFinderService tenantFinderService;
@Value("${keycloak-ext.external.id:ais}")
protected String externalIdmSource;
@Value("${keycloak-ext.syncGroupAs:organization}")
protected String syncGroupAs;
protected boolean syncGroupAsOrganization() {
return !this.syncGroupAsCapability();
}
protected boolean syncGroupAsCapability() {
return this.syncGroupAs != null && this.syncGroupAs.toLowerCase().startsWith("cap");
}
/**
* This method validates that the user exists, if not, it creates the
* missing user. Without this functionality, SSO straight up fails in APS.
*/
@Override
public void preAuthenticate(Authentication auth) throws AuthenticationException {
Long tenantId = this.tenantFinderService.findTenantId();
this.logger.trace("Tenant ID: {}", tenantId);
User user = this.findUser(auth, tenantId);
if (user == null) {
if (this.createMissingUser) {
this.logger.debug("User does not yet exist; creating the user: {}", auth.getName());
user = this.createUser(auth, tenantId);
this.logger.debug("Created user: {} => {}", user.getId(), user.getExternalId());
if (this.clearNewUserDefaultGroups) {
this.logger.debug("Clearing groups: {}", user.getId());
// fetch and remove default groups
user = this.userService.getUser(user.getId(), true);
for (Group group : user.getGroups())
this.groupService.deleteUserFromGroup(group, user);
}
} else {
this.logger.info("User does not exist; user creation is disabled: {}", auth.getName());
}
} else if (user.getExternalOriginalSrc() == null || user.getExternalOriginalSrc().length() == 0) {
this.logger.debug("User exists, but not created by an external source: {}", auth.getName());
this.logger.info("Linking user '{}' with external IDM '{}'", auth.getName(), this.externalIdmSource);
user.setExternalId(auth.getName());
user.setExternalOriginalSrc(this.externalIdmSource);
this.userService.save(user);
} else if (!this.externalIdmSource.equals(user.getExternalOriginalSrc())) {
this.logger.debug("User '{}' exists, but created by another source: {}", auth.getName(), user.getExternalOriginalSrc());
} else {
this.logger.trace("User already exists: {}", auth.getName());
}
}
/**
* This method validates that the groups exist, if not, it creates the
* missing ones. Without this functionality, SSO works, but the user's
* authorities are not synchronized.
*/
@Override
public void postAuthenticate(Authentication auth) throws AuthenticationException {
Long tenantId = this.tenantFinderService.findTenantId();
User user = this.findUser(auth, tenantId);
this.logger.debug("Inspecting user: {} => {}", user.getId(), user.getExternalId());
this.syncUserRoles(user, auth, tenantId);
}
private User findUser(Authentication auth, Long tenantId) {
String email = auth.getName();
User user = this.userService.findUserByEmailAndTenantId(email, tenantId);
if (user == null) {
this.logger.debug("User does not exist in tenant; trying tenant-less lookup: {}", email);
user = this.userService.findUserByEmail(email);
} else {
this.logger.trace("Found user: {}", user.getId());
}
return user;
}
private User createUser(Authentication auth, Long tenantId) {
AccessToken atoken = this.getKeycloakAccessToken(auth);
if (atoken == null) {
this.logger.debug("The keycloak access token could not be found; using email to determine names: {}", auth.getName());
Matcher emailNamesMatcher = this.emailNamesPattern.matcher(auth.getName());
if (!emailNamesMatcher.matches()) {
this.logger.warn("The email address could not be parsed for names: {}", auth.getName());
return this.userService.createNewUserFromExternalStore(auth.getName(), "Unknown", "Person", tenantId, auth.getName(), this.externalIdmSource, new Date());
} else {
String firstName = StringUtils.capitalize(emailNamesMatcher.group(1));
String lastName = StringUtils.capitalize(emailNamesMatcher.group(2));
return this.userService.createNewUserFromExternalStore(auth.getName(), firstName, lastName, tenantId, auth.getName(), this.externalIdmSource, new Date());
}
} else {
return this.userService.createNewUserFromExternalStore(auth.getName(), atoken.getGivenName(), atoken.getFamilyName(), tenantId, auth.getName(), this.externalIdmSource, new Date());
}
}
private void syncUserRoles(User user, Authentication auth, Long tenantId) {
Map<String, String> roles = this.getKeycloakRoles(auth);
if (roles == null) {
this.logger.debug("The user roles could not be determined; skipping sync: {}", user.getEmail());
return;
}
boolean syncAsOrg = this.syncGroupAsOrganization();
// check Activiti groups
User userWithGroups = this.userService.getUser(user.getId(), true);
for (Group group : userWithGroups.getGroups()) {
if (group.getExternalId() == null && !this.syncInternalGroups)
continue;
this.logger.trace("Inspecting group: {} => {} ({})", group.getId(), group.getName(), group.getExternalId());
if (group.getExternalId() != null && this.removeMapEntriesByValue(roles, this.apsGroupExternalIdToKeycloakRole(group.getExternalId()))) {
if (group.getTenantId() == null) {
// fix stray groups
group.setTenantId(tenantId);
group.setLastUpdate(new Date());
this.groupService.save(group);
}
// role already existed and the user is already a member
} else if (group.getExternalId() == null && roles.remove(this.apsGroupNameToKeycloakRole(group.getName())) != null) {
// register the group as external
group.setExternalId(this.keycloakRoleToApsGroupExternalId(this.apsGroupNameToKeycloakRole(group.getName())));
group.setLastUpdate(new Date());
this.groupService.save(group);
// internal role already existed and the user is already a member
} else {
// at this point, we have a group that the user does not have a corresponding role for
if (this.syncGroupRemove) {
this.logger.trace("Removing user '{}' from group '{}'", user.getExternalId(), group.getName());
this.groupService.deleteUserFromGroup(group, userWithGroups);
} else {
this.logger.debug("User/group membership sync disabled; not removing user from group: {} => {}", user.getExternalId(), group.getName());
}
}
}
// add remaining authorities into Activiti
for (Entry<String, String> role : roles.entrySet()) {
this.logger.trace("Syncing group membership: {}", role);
Group group;
try {
group = this.groupService.getGroupByExternalIdAndTenantId(this.keycloakRoleToApsGroupExternalId(role.getKey()), tenantId);
} catch (NonUniqueResultException nure) {
this.logger.warn("There are multiple groups with the external ID; not adding user to group: {}", role.getKey());
continue;
}
if (group == null && this.syncInternalGroups) {
List<Group> groups = this.groupService.getGroupByNameAndTenantId(this.keycloakRoleToApsGroupName(role.getValue()), tenantId);
if (groups.size() > 1) {
this.logger.warn("There are multiple groups with the same name; not adding user to group: {}", role.getValue());
continue;
} else if (groups.size() == 1) {
group = groups.iterator().next();
this.logger.debug("Found an internal group; registering as external: {}", group.getName());
group.setExternalId(this.keycloakRoleToApsGroupExternalId(role.getKey()));
group.setLastSyncTimeStamp(new Date());
group.setLastUpdate(new Date());
this.groupService.save(group);
}
}
if (group == null) {
if (this.createMissingGroup) {
this.logger.trace("Creating new group for role: {}", role);
String name = this.keycloakRoleToApsGroupName(role.getValue());
String externalId = this.keycloakRoleToApsGroupExternalId(role.getKey());
int type = syncAsOrg ? Group.TYPE_FUNCTIONAL_GROUP : Group.TYPE_SYSTEM_GROUP;
this.logger.trace("Creating new group: {} ({}) [type: {}]", name, externalId, type);
group = this.groupService.createGroupFromExternalStore(name, tenantId, type, null, externalId, new Date());
} else {
this.logger.debug("Group does not exist; group creation is disabled: {}", role);
}
}
if (group != null && this.syncGroupAdd) {
this.logger.trace("Adding user '{}' to group '{}'", user.getExternalId(), group.getName());
this.groupService.addUserToGroup(group, userWithGroups);
} else {
this.logger.debug("User/group membership sync disabled; not adding user to group: {} => {}", user.getExternalId(), group.getName());
}
}
}
private String keycloakRoleToApsGroupExternalId(String role) {
return this.externalIdmSource + "_" + role;
}
private String apsGroupExternalIdToKeycloakRole(String externalId) {
int underscorePos = externalId.indexOf('_');
return underscorePos < 0 ? externalId : externalId.substring(underscorePos + 1);
}
private String keycloakRoleToApsGroupName(String role) {
return role;
}
private String apsGroupNameToKeycloakRole(String externalId) {
return externalId;
}
}

View File

@@ -1,162 +0,0 @@
package com.inteligr8.activiti.keycloak;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
/**
* This is an unused implementation for non-APS installation. It is not tested
* and probably pointless.
*
* @author brian.long@yudrio.com
*/
@Component("keycloak-ext.activiti-engine.authenticator")
@Lazy
public class KeycloakActivitiEngineAuthenticator extends AbstractKeycloakActivitiAuthenticator {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private IdentityService identityService;
@Value("${keycloak-ext.group.prefix:KEYCLOAK_}")
private String groupPrefix;
/**
* This method validates that the user exists, if not, it creates the
* missing user. Without this functionality, SSO straight up fails.
*/
@Override
public void preAuthenticate(Authentication auth) throws AuthenticationException {
User user = this.findUser(auth);
if (user == null) {
if (this.createMissingUser) {
this.logger.debug("User does not yet exist; creating the user: {}", auth.getName());
user = this.createUser(auth);
this.logger.debug("Created user: {} => {}", user.getId(), user.getEmail());
if (this.clearNewUserDefaultGroups) {
this.logger.debug("Clearing groups: {}", user.getId());
List<Group> groups = this.identityService.createGroupQuery()
.groupMember(user.getId())
.list();
for (Group group : groups)
this.identityService.deleteMembership(user.getId(), group.getId());
}
} else {
this.logger.info("User does not exist; user creation is disabled: {}", auth.getName());
}
}
}
/**
* This method validates that the groups exist, if not, it creates the
* missing ones. Without this functionality, SSO works, but the user's
* authorities are not synchronized.
*/
@Override
public void postAuthenticate(Authentication auth) throws AuthenticationException {
User user = this.findUser(auth);
this.logger.debug("Inspecting user: {} => {}", user.getId(), user.getEmail());
this.syncUserRoles(user, auth);
}
private User findUser(Authentication auth) {
String email = auth.getName();
User user = this.identityService.createUserQuery()
.userEmail(email)
.singleResult();
return user;
}
private User createUser(Authentication auth) {
User user = this.identityService.newUser(auth.getName());
user.setEmail(auth.getName());
this.identityService.saveUser(user);
return user;
}
private void syncUserRoles(User user, Authentication auth) {
Map<String, String> roles = this.getKeycloakRoles(auth);
if (roles == null) {
this.logger.debug("The user roles could not be determined; skipping sync: {}", user.getEmail());
return;
}
// check Activiti groups
List<Group> groups = this.identityService.createGroupQuery()
.groupMember(user.getEmail())
.list();
this.logger.debug("User is currently a member of {} groups", groups.size());
for (Group group : groups) {
if (!group.getId().startsWith(this.groupPrefix) && this.syncInternalGroups)
continue;
this.logger.trace("Inspecting group: {} => {} ({})", group.getId(), group.getName(), group.getType());
if (roles.remove(this.activitiGroupIdToKeycloakRole(group.getId())) != null) {
this.logger.trace("Group and membership already exist: {} => {}", user.getEmail(), group.getName());
// already a member of the group
} else {
if (this.syncGroupRemove) {
this.logger.trace("Group membership not in OIDC token; removing from group: {} => {}", user.getEmail(), group.getName());
this.identityService.deleteMembership(user.getId(), group.getId());
} else {
this.logger.debug("User/group membership sync disabled; not removing user from group: {} => {}", user.getId(), group.getId());
}
}
}
this.logger.debug("Unaddressed OIDC roles: {}", roles);
// check remainder/unaddressed roles
for (Entry<String, String> role : roles.entrySet()) {
this.logger.trace("Inspecting role: {}", role);
Group group = this.identityService.createGroupQuery()
.groupId(this.keycloakRoleToActivitiGroupId(role.getKey()))
.singleResult();
if (group == null) {
if (this.createMissingGroup) {
this.logger.trace("Group does not exist; creating one");
group = this.identityService.newGroup(this.keycloakRoleToActivitiGroupId(role.getKey()));
group.setName(role.getValue());
this.identityService.saveGroup(group);
} else {
this.logger.info("Group does not exist; group creation is disabled: {}", role.getKey());
}
}
if (group != null && this.syncGroupAdd) {
this.logger.trace("Group membership not in Activiti; adding to group: {} => {}", user.getEmail(), group.getName());
this.identityService.createMembership(user.getId(), group.getId());
} else {
this.logger.debug("User/group membership sync disabled; not adding user to group: {} => {}", user.getId(), group.getId());
}
}
}
private String keycloakRoleToActivitiGroupId(String role) {
return this.groupPrefix + role;
}
private String activitiGroupIdToKeycloakRole(String groupId) {
return groupId.startsWith(this.groupPrefix) ? groupId.substring(this.groupPrefix.length()) : groupId;
}
}

View File

@@ -1,67 +0,0 @@
package com.inteligr8.activiti.keycloak;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import com.inteligr8.activiti.ActivitiSecurityConfigAdapter;
import com.inteligr8.activiti.auth.Authenticator;
import com.inteligr8.activiti.auth.InterceptingAuthenticationProvider;
/**
* This class/bean injects a custom keycloak authentication provider into the
* security configuration.
*
* @author brian@inteligr8.com
* @see org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider
*/
@Component
public class KeycloakSecurityConfigurationAdapter implements ActivitiSecurityConfigAdapter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${keycloak-ext.keycloak.enabled:false}")
private boolean enabled;
// this assures execution before the OOTB impl (-10 < 0)
@Value("${keycloak-ext.keycloak.priority:-5}")
private int priority;
@Autowired
@Qualifier("keycloak-ext.activiti-app.authenticator")
private Authenticator authenticator;
protected Authenticator getAuthenticator() {
return this.authenticator;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) {
this.logger.trace("configureGlobal()");
this.logger.info("Using Keycloak authentication extension, featuring creation of missing users and authority synchronization");
KeycloakAuthenticationProvider provider = new KeycloakAuthenticationProvider();
provider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(new InterceptingAuthenticationProvider(provider, this.getAuthenticator()));
}
}

View File

@@ -0,0 +1,302 @@
{
"realm": "my-app",
"displayName": "My Application",
"enabled": true,
"sslRequired": "none",
"scopeMappings": [
{
"clientScope": "offline_access",
"roles": [
"offline_access"
]
}
],
"clientScopeMappings": {
"account": [
{
"client": "account-console",
"roles": [
"manage-account",
"view-groups"
]
}
]
},
"roles": {
"realm": [
{
"name": "aps-admin",
"description": "APS Administrator",
"composite": false,
"clientRole": false
},
{
"name": "aps-modeler",
"description": "APS Modeler",
"composite": false,
"clientRole": false
},
{
"name": "aps-publisher",
"description": "APS Publisher",
"composite": false,
"clientRole": false
},
{
"name": "biz-employee",
"description": "Business Reviewer",
"composite": false,
"clientRole": false
},
{
"name": "biz-manager",
"description": "Business Reviewer",
"composite": false,
"clientRole": false
}
]
},
"clients": [
{
"clientId": "aps-app-public",
"name": "APS App",
"description": "Alfresco Process Services Activiti App",
"rootUrl": "http://localhost:8080/activiti-app",
"adminUrl": "http://localhost:8080/activiti-app",
"baseUrl": "",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": [
"*"
],
"webOrigins": [
"*"
],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": true,
"serviceAccountsEnabled": false,
"publicClient": true,
"frontchannelLogout": true,
"protocol": "openid-connect",
"attributes": {
"realm_client": "false",
"oidc.ciba.grant.enabled": "false",
"backchannel.logout.session.required": "true",
"standard.token.exchange.enabled": "false",
"oauth2.device.authorization.grant.enabled": "false",
"backchannel.logout.revoke.offline.tokens": "false"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": true,
"nodeReRegistrationTimeout": -1,
"defaultClientScopes": [
"web-origins",
"acr",
"profile",
"roles",
"basic",
"email",
"microprofile-jwt"
],
"optionalClientScopes": [
"address",
"phone",
"organization",
"offline_access"
]
},
{
"clientId": "aps-app-confidential",
"name": "APS App",
"description": "Alfresco Process Services Activiti App",
"rootUrl": "http://localhost:8080/activiti-app",
"adminUrl": "http://localhost:8080/activiti-app",
"baseUrl": "",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"secret": "a-secret",
"redirectUris": [
"*"
],
"webOrigins": [
"*"
],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": true,
"serviceAccountsEnabled": false,
"publicClient": false,
"frontchannelLogout": true,
"protocol": "openid-connect",
"attributes": {
"realm_client": "false",
"oidc.ciba.grant.enabled": "false",
"backchannel.logout.session.required": "true",
"standard.token.exchange.enabled": "false",
"oauth2.device.authorization.grant.enabled": "false",
"backchannel.logout.revoke.offline.tokens": "false"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": true,
"nodeReRegistrationTimeout": -1,
"defaultClientScopes": [
"web-origins",
"acr",
"profile",
"roles",
"basic",
"email",
"microprofile-jwt"
],
"optionalClientScopes": [
"address",
"phone",
"organization",
"offline_access"
]
},
{
"clientId": "cli",
"name": "Command Line Tools",
"description": "",
"rootUrl": "",
"adminUrl": "",
"baseUrl": "",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"secret": "eJa5W7bv4ohFbr7QRtaCk0eccRFoYM5x",
"redirectUris": [
"/*"
],
"webOrigins": [
"/*"
],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": false,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": true,
"publicClient": false,
"frontchannelLogout": true,
"protocol": "openid-connect",
"attributes": {
"realm_client": "false",
"oidc.ciba.grant.enabled": "false",
"client.secret.creation.time": "1747506410",
"backchannel.logout.session.required": "true",
"standard.token.exchange.enabled": "true",
"oauth2.device.authorization.grant.enabled": "false",
"backchannel.logout.revoke.offline.tokens": "false"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": true,
"nodeReRegistrationTimeout": -1,
"defaultClientScopes": [
"web-origins",
"acr",
"profile",
"roles",
"basic",
"email",
"microprofile-jwt"
],
"optionalClientScopes": [
"address",
"phone",
"organization",
"offline_access"
],
"access": {
"view": true,
"configure": true,
"manage": true
}
}
],
"users": [
{
"username": "test",
"enabled": true,
"firstName": "Test",
"lastName": "User",
"email": "test@tester.com",
"credentials": [
{
"type": "password",
"temporary": false,
"value": "test"
}
]
},
{
"username": "test.admin",
"enabled": true,
"firstName": "Test",
"lastName": "Administrator",
"email": "test.admin@tester.com",
"credentials": [
{
"type": "password",
"temporary": false,
"value": "test"
}
],
"realmRoles": [
"aps-admin"
]
},
{
"username": "test.modeler",
"enabled": true,
"firstName": "Test",
"lastName": "Modeler",
"email": "test.modeler@tester.com",
"credentials": [
{
"type": "password",
"temporary": false,
"value": "test"
}
],
"realmRoles": [
"aps-modeler",
"aps-publisher"
]
},
{
"username": "test.manager",
"enabled": true,
"firstName": "Test",
"lastName": "Manager",
"email": "test.manager@tester.com",
"credentials": [
{
"type": "password",
"temporary": false,
"value": "test"
}
],
"realmRoles": [
"biz-manager"
]
}
],
"attributes": {
"frontendUrl": "http://host.docker.internal:8081"
}
}

View File

@@ -0,0 +1,21 @@
rootLogger.level=warn
rootLogger.appenderRef.stdout.ref=ConsoleAppender
###### Console appender definition #######
# Direct log messages to stdout
appender.console.type=Console
appender.console.name=ConsoleAppender
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=%d{hh:mm:ss,SSS} [%t] %-5p %c %X - %replace{%m}{[\r\n]+}{}%n
logger.aspose-license.name=com.activiti.conf.TransformationConfiguration
logger.aspose-license.level=off
logger.aps-security.name=com.activiti.security
logger.aps-security.level=debug
logger.spring-security.name=org.springframework.security
logger.spring-security.level=debug
logger.auth-ext.name=com.inteligr8.activiti.auth
logger.auth-ext.level=trace

View File

@@ -0,0 +1,8 @@
{
"realm": "master",
"enabled": true,
"sslRequired": "required",
"attributes": {
"frontendUrl": "http://host.docker.internal:8081"
}
}

View File

@@ -0,0 +1,35 @@
@keycloakRealm = my-app
@keycloakBaseUrl = http://localhost:8081
@oauthUrl = {{keycloakBaseUrl}}/realms/{{keycloakRealm}}
@keycloakTokenUrl = {{oauthUrl}}/protocol/openid-connect/token
@oauthClientId = cli
@oauthClientSecret = eJa5W7bv4ohFbr7QRtaCk0eccRFoYM5x
@apsBaseUrl = http://localhost:8080/activiti-app
### Token
# @name token
curl -LX POST {{keycloakTokenUrl}} \
-H 'Content-type: application/x-www-form-urlencoded' \
-d "grant_type=client_credentials" \
-d "client_id={{oauthClientId}}" \
-d "client_secret={{oauthClientSecret}}"
@accessToken = {{token.response.body.access_token}}
@auth = Bearer {{accessToken}}
### APS Version
# @name version
GET {{apsBaseUrl}}/api/enterprise/app-version
Authorization: Bearer {{accessToken}}
### APS Tenants
# @name tenants
GET {{apsBaseUrl}}/api/enterprise/admin/tenants
Authorization: Bearer {{accessToken}}
@tenantId = {{tenants.response.body.0.id}}
### APS Templates
# @name templates
GET {{apsBaseUrl}}/app/rest/document-templates?tenantId={{tenantId}}&start=0&size=10&sort=sort_by_name_asc
Authorization: Bearer {{accessToken}}