refactored for v24+

This commit is contained in:
2025-05-04 20:11:15 -04:00
parent dcd7e987f1
commit 5dfdf8452d
26 changed files with 1378 additions and 1162 deletions

114
README.md
View File

@@ -1,14 +1,17 @@
# 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.
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.
## 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,57 +21,82 @@ 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
}
```
## Support Matrix
| Keycloak Activiti App Extension | Activiti App |
| ------------------------------- | --------------- |
| v1.0 - v1.2 | v1.11.x |
| v1.3 | v1.11.x - v2.x |
| v1.4+ | v24.x+ |
| Auth Activiti App Extension | Activiti App |
| --------------------------- | --------------- |
| v1.0 - v1.2 | v1.11.x |
| v1.3 | v1.11.x - v2.x |
| 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`.
### OAuth Authentication/Authorization
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 |
| ---------------------------------------------- | --------- |
| `auth-ext.oauth.scopes` | `openid`, `profile`, `email`, `microprofile-jwt` |
### OAuth Synchronization
The following properties provide the core functionality of this extension. That is role synchronization.
| Property | Default | Description |
| ---------------------------------------------- | --------- | ----------- |
| `keycloak-ext.keycloak.enabled` | `false` | Enable Keycloak integration, overriding and extending the OOTB OAuth 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. |
| `auth-ext.sync.externalId` | `oauth` | This will serve as the external ID for users and as the prefix for the external ID of groups created 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.user.createMissing` | `true` | If the user is authenticated, the user may be created in APS. |
| `auth-ext.sync.user.requireGroup` | | 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.translate.patterns` | | A comma delimited set of regular expression patterns for the translation (reformatting) of authorities. |
| `auth-ext.sync.group.translate.replacements` | | A comma delimited set of regular expression replacement strings for the translation (reformatting) of authorities. |
| `auth-ext.sync.group.include.patterns` | | A comma delimited set of regular expression patterns on what authorities to include. This is processed before `translate` processing. A blank value includes everything. If anything is specified, then only matches could possibly be included; but could still be excluded explicitly. |
| `auth-ext.sync.group.exclude.patterns` | | A comma delimited set of regular expression patterns on what authorities to exclude. This is processed before `translate` processing. A blank value excludes nothing. If anything is specified and `include` is empty, then only matches will be excluded. If both are specified, `exclude` overrules `include` matches. |
| `auth-ext.sync.group.capabilities.patterns` | `Superusers` | A comma delimited set of regular expression patterns on what authorities to associate with APS Capabilities instead of APS Organizations (default). |
### For Activiti App Only
| Property | Default | Description |
| ---------------------------------------------- | ------- | ----------- |
| `keycloak-ext.group.capability.regex.patterns` | | When creating a new group, sync as an APS Organization, except when the specified pattern matches the role. In those cases, sync as an APS Capability. |
| `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. |
### Authentication Data Fixers
### Rare
#### Administrator Password Fixer
| Property | Default | Description |
| ----------------------------------------- | --------------- | ----------- |
| `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. |
| `keycloak-ext.group.admins.validate` | `false` | Whether or not to validate the existence and capabilities of an administrators group on application 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 | Description |
| ----------------------------------------- | ------------------------ | ----------- |
| `auth-ext.reset.admin.username` | `admin@app.activiti.com` |
| `auth-ext.reset.admin.password` | | If set, the user's password will be set to this value on startup; otherwise this fixer is skipped. |
### Deprecated
#### Administrator Members Fixer
| Property | Default | Description |
| ----------------------------------------- | ------------------------ | ----------- |
| `auth-ext.default.admins.users` | | A comma delimited list of user emails; fixer is skipped if empty. |
| `auth-ext.group.admins.name` | `Superusers` | The APS Group (Capability or Organization) to add the specified users to. |
| `auth-ext.group.admins.externalId` | | If specified, this APS Group will be considered before the specified `name` field. |
#### Administrator Group Fixer
| Property | Default | Description |
| ----------------------------------------- | ------------------------ | ----------- |
| `auth-ext.group.admins.validate` | `false` | If `true`, the specified APS Group will be granted all capabilities. |
| `auth-ext.group.admins.name` | `Superusers` | The APS Group (Capability or Organization) to add the specified users to. |
| `auth-ext.group.admins.externalId` | | If specified, this APS Group will be considered before the specified `name` field. |
| Property | Since | Description |
| ---------------------------------------------- | ----- | ----------- |
| `keycloak-ext.ais.*` | v24.x | AIS integration was removed. The `keycloak-ext.keycloak.*` properties must be used instead. |

226
pom.xml
View File

@@ -4,12 +4,12 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.inteligr8.activiti</groupId>
<artifactId>keycloak-activiti-app-ext</artifactId>
<version>1.4-SNAPSHOT</version>
<artifactId>auth-activiti-app-ext</artifactId>
<version>2.0-SNAPSHOT</version>
<name>Keycloak Authentication &amp; Authorization for APS</name>
<description>An Alfresco Process Service App extension providing improved Keycloak/AIS support.</description>
<url>https://bitbucket.org/inteligr8/keycloak-activiti-app-ext</url>
<name>Authentication &amp; Authorization for APS</name>
<description>An Alfresco Process Service App extension providing improved authentication and authorization support.</description>
<url>https://bitbucket.org/inteligr8/auth-activiti-app-ext</url>
<licenses>
<license>
@@ -19,9 +19,9 @@
</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>
<connection>scm:git:https://bitbucket.org/inteligr8/auth-activiti-app-ext.git</connection>
<developerConnection>scm:git:git@bitbucket.org:inteligr8/auth-activiti-app-ext.git</developerConnection>
<url>https://bitbucket.org/inteligr8/auth-activiti-app-ext</url>
</scm>
<organization>
<name>Inteligr8</name>
@@ -41,18 +41,24 @@
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.release>17</maven.compiler.release>
<aps.version>24.3.0</aps.version>
<keycloak.version>23.0.7</keycloak.version>
<spring-security-oauth2.version>6.3.2</spring-security-oauth2.version>
<aps.version>25.1.1</aps.version>
<!-- for RAD -->
<tomcat-rad.version>10-2.2</tomcat-rad.version>
<aps.tomcat.opts.base>-Dspring.main.allow-circular-references=true \
-Dhibernate.dialect=org.hibernate.dialect.PostgreSQLDialect \
-Dauth-ext.oauth.enabled=true \
-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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
<version>${spring-security-oauth2.version}</version>
<scope>provided</scope>
</dependency>
<!-- Needed for Activiti App Identity Service inheritance/override -->
<!-- includes activiti-app-logic for API -->
<dependency>
@@ -62,6 +68,7 @@
<classifier>classes</classifier>
<scope>provided</scope>
<exclusions>
<!-- not necessary to download for building -->
<exclusion>
<groupId>com.activiti</groupId>
<artifactId>aspose-transformation</artifactId>
@@ -70,41 +77,18 @@
<groupId>org.alfresco.officeservices</groupId>
<artifactId>aoservices</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>${keycloak.version}</version>
<exclusions>
<!-- provided by APS -->
<!-- very old and overrides real spring version -->
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<groupId>com.ryantenney.metrics</groupId>
<artifactId>metrics-spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</exclusion>
<exclusion>
<groupId>jakarta.activation</groupId>
<artifactId>*</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>*</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>*</artifactId>
</exclusion>
<exclusion>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
</exclusion>
<exclusion>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</exclusion>
</exclusions>
</dependency>
@@ -113,34 +97,132 @@
<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></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>
<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>
@@ -204,10 +286,6 @@
</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>

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,76 +0,0 @@
/*
* 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.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.security.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 unset the 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;
}
/**
* A priority for the execution order of adapters. The first enabled one will be used.
*
* @return A standard priority value; the lower the value, the higher the priority; 0 is the default
*/
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

@@ -26,12 +26,10 @@ import org.springframework.context.annotation.FullyQualifiedAnnotationBeanNameGe
@Configuration
@ComponentScan(
basePackages = {
"com.inteligr8.activiti.idm",
"com.inteligr8.activiti.keycloak",
"com.inteligr8.activiti.security"
"com.inteligr8.activiti.auth"
},
nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class
)
public class KeycloakExtSpringComponentScanner {
public class AuthExtSpringComponentScanner {
}

View File

@@ -12,7 +12,7 @@
* 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.idm;
package com.inteligr8.activiti.auth;
import java.util.ArrayList;
import java.util.Arrays;
@@ -32,8 +32,7 @@ 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.DataFixer;
import com.inteligr8.activiti.keycloak.TenantFinderService;
import com.inteligr8.activiti.auth.service.TenantFinderService;
/**
* This class/bean attempts to fix the administrative group in APS. This may
@@ -43,7 +42,7 @@ import com.inteligr8.activiti.keycloak.TenantFinderService;
* @author brian@inteligr8.com
*/
@Component
public class ActivitiAppAdminGroupFixer implements DataFixer {
public class ActivitiAppAdministratorGroupFixer implements DataFixer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@@ -62,61 +61,66 @@ public class ActivitiAppAdminGroupFixer implements DataFixer {
@Autowired
private TenantFinderService tenantFinderService;
@Value("${keycloak-ext.group.admins.name:admins}")
@Value("${auth-ext.group.admins.name:Superusers}")
private String adminGroupName;
@Value("${keycloak-ext.group.admins.externalId:#{null}}")
private String adminGroupExternalId;
@Value("${auth-ext.sync.externalId:oauth}")
protected String externalIdmSource;
@Value("${keycloak-ext.group.admins.validate:false}")
@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.validateAdmins(this.externalIdmSource + "_" + this.adminGroupName);
}
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: {} => {}; 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");
this.logger.trace("Functional groups: {}", this.toGroupNames(this.groupService.getFunctionalGroups(null)));
this.logger.trace("System groups: {}", this.toGroupNames(this.groupService.getSystemGroups(null)));
this.logger.trace("Tenant: null; functional groups: {}; system groups: {}",
this.toGroupNames(this.groupService.getFunctionalGroups(null)),
this.toGroupNames(this.groupService.getSystemGroups(null)));
}
private void validateAdmins() {
if (this.groupService == null)
return;
private void validateAdmins(String adminGroupExternalId) {
Long tenantId = this.tenantFinderService.findTenantId();
Group group = this.groupService.getGroupByExternalIdAndTenantId(this.adminGroupExternalId, tenantId);
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.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("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());
@@ -125,7 +129,7 @@ public class ActivitiAppAdminGroupFixer implements DataFixer {
for (GroupCapability cap : groupWithCaps.getCapabilities())
adminCaps.remove(cap.getName());
if (!adminCaps.isEmpty()) {
this.logger.info("Granting group '{}' capabilities: {}", group.getName(), adminCaps);
this.logger.info("Granting group capabilities: {} => {}", group.getName(), adminCaps);
this.groupService.addCapabilitiesToGroup(group.getId(), new ArrayList<>(adminCaps));
}
}

View File

@@ -12,7 +12,7 @@
* 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.idm;
package com.inteligr8.activiti.auth;
import java.util.Arrays;
import java.util.List;
@@ -29,8 +29,7 @@ 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.DataFixer;
import com.inteligr8.activiti.keycloak.TenantFinderService;
import com.inteligr8.activiti.auth.service.TenantFinderService;
/**
* This class/bean attempts to add administrators to the administrative group
@@ -40,7 +39,7 @@ import com.inteligr8.activiti.keycloak.TenantFinderService;
* @author brian@inteligr8.com
*/
@Component
public class ActivitiAppAdminMembersFixer implements DataFixer {
public class ActivitiAppAdministratorMembersFixer implements DataFixer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@@ -53,53 +52,66 @@ public class ActivitiAppAdminMembersFixer implements DataFixer {
@Autowired
private TenantFinderService tenantFinderService;
@Value("${keycloak-ext.default.admins.users:#{null}}")
@Value("${auth-ext.default.admins.users:#{null}}")
private String adminUserStrs;
@Value("${keycloak-ext.group.admins.name:admins}")
@Value("${auth-ext.group.admins.name:Superusers}")
private String adminGroupName;
@Value("${keycloak-ext.group.admins.externalId:#{null}}")
@Value("${auth-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();
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() {
if (this.userService == null || this.groupService == null)
return;
List<String> adminUsers = Arrays.asList(this.adminUserStrs.split(","));
if (adminUsers.isEmpty())
return;
private void associateAdmins(List<String> adminUsers) {
Long tenantId = this.tenantFinderService.findTenantId();
List<Group> groups = null;
try {
Group group1 = this.groupService.getGroupByExternalIdAndTenantId(this.adminGroupExternalId, tenantId);
if (group1 != null)
groups = Arrays.asList(group1);
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)
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.info("The user with email '{}' does not exist, so they cannot be added as an administrator", email);
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)
this.groupService.addUserToGroup(group, user);
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

@@ -12,7 +12,7 @@
* 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.idm;
package com.inteligr8.activiti.auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -22,8 +22,7 @@ import org.springframework.stereotype.Component;
import com.activiti.domain.idm.User;
import com.activiti.service.api.UserService;
import com.inteligr8.activiti.DataFixer;
import com.inteligr8.activiti.keycloak.TenantFinderService;
import com.inteligr8.activiti.auth.service.TenantFinderService;
/**
* This class/bean attempts to reset the configured user's password.
@@ -31,7 +30,7 @@ import com.inteligr8.activiti.keycloak.TenantFinderService;
* @author brian@inteligr8.com
*/
@Component
public class ActivitiAppAdminPasswordFixer implements DataFixer {
public class ActivitiAppAdministratorPasswordFixer implements DataFixer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@@ -41,23 +40,29 @@ public class ActivitiAppAdminPasswordFixer implements DataFixer {
@Autowired
private TenantFinderService tenantFinderService;
@Value("${keycloak-ext.reset.admin.username:admin@app.activiti.com}")
@Value("${auth-ext.reset.admin.username:admin@app.activiti.com}")
private String adminUsername;
@Value("${keycloak-ext.reset.admin.password:#{null}}")
@Value("${auth-ext.reset.admin.password:#{null}}")
private String adminPassword;
@Override
public void fix() {
this.logger.trace("fix()");
if (this.adminPassword != null) {
this.logger.info("Resetting the password for admin user '{}'", this.adminUsername);
Long tenantId = this.tenantFinderService.findTenantId();
User adminUser = this.userService.findUserByEmailAndTenantId(this.adminUsername, tenantId);
this.userService.changePassword(adminUser.getId(), this.adminPassword);
}
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,28 +0,0 @@
/*
* 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.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,32 @@
package com.inteligr8.activiti.auth;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import com.activiti.api.boot.BootstrapConfigurer;
@Component("bootstrap.proxy")
@Primary
public class Bootstrapper implements BootstrapConfigurer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void applicationContextInitialized(ApplicationContext applicationContext) {
Map<String, BootstrapConfigurer> bootstraps = applicationContext.getBeansOfType(BootstrapConfigurer.class);
bootstraps.remove("bootstrap.proxy");
this.logger.debug("Executing {} bootstrap configurers", bootstraps.size());
for (Entry<String, BootstrapConfigurer> bootstrap : bootstraps.entrySet()) {
this.logger.trace("Executing bootstrap configurer: {}: {}", bootstrap.getKey(), bootstrap.getValue().getClass());
bootstrap.getValue().applicationContextInitialized(applicationContext);
}
}
}

View File

@@ -12,7 +12,11 @@
* 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;
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
@@ -20,12 +24,17 @@ package com.inteligr8.activiti;
*
* @author brian@inteligr8.com
*/
public interface DataFixer {
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,63 +0,0 @@
/*
* 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.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,65 @@
package com.inteligr8.activiti.auth.oauth;
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.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import com.activiti.security.identity.service.config.IdentityServiceEnabledCondition;
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;
@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 clientRegistration1() 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();
}
}

View File

@@ -0,0 +1,363 @@
/*
* 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.oidc.user.OidcUser;
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.sync.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) {
if (!oidcUser.hasClaim("groups")) {
this.logger.warn("There is no 'groups' claim to synchronize: {}", oidcUser.getEmail());
this.logger.debug("The claims available: {}", oidcUser.getClaims().keySet());
return;
}
Set<String> oidcGroups = new HashSet<>(oidcUser.getClaimAsStringList("groups"));
this.logger.trace("Incoming OIDC groups: {}: {}", oidcUser.getEmail(), oidcGroups);
oidcGroups = this.filterGroups(oidcGroups);
oidcGroups = this.translateGroups(oidcGroups);
this.logger.debug("Filtered/translated OIDC groups: {}: {}", oidcUser.getEmail(), oidcGroups);
long tenantId = this.tenantFinderService.findTenantId();
// check Activiti groups
User user = this.userService.findUserByEmailAndTenantId(oidcUser.getEmail(), tenantId);
if (user == null) {
user = this.userService.findUserByEmail(oidcUser.getEmail());
if (user == null)
throw new UsernameNotFoundException("The user could not be found: " + oidcUser.getEmail());
}
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 oidcGroup = this.apsGroupExternalIdToOidcGroup(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 (oidcGroups.remove(oidcGroup)) {
this.logger.trace("User already belongs to APS group mapped to by OIDC group: {}: {} => {}", user.getExternalId(), oidcGroup, group.getName());
continue;
}
} else {
String oidcGroup = this.apsGroupNameToOidcGroup(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.oidcGroupToApsGroupExternalId(oidcGroup));
group.setLastUpdate(new Date());
this.groupService.save(group);
// internal role already existed and the user is already a member
}
if (oidcGroups.remove(oidcGroup)) {
this.logger.trace("User already belongs to APS group mapped to by OIDC group: {}: {} => {}", user.getExternalId(), oidcGroup, group.getName());
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 oidcGroup : oidcGroups) {
this.logger.trace("Inspecting unaccounted for OIDC group: {}", oidcGroup);
Group group;
try {
group = this.groupService.getGroupByExternalIdAndTenantId(this.oidcGroupToApsGroupExternalId(oidcGroup), tenantId);
} catch (NonUniqueResultException nure) {
this.logger.warn("There are multiple groups matching the OIDC group for the external system: {} [{}]; skipping consideration of OIDC group", oidcGroup, this.externalIdmSource);
continue;
}
if (group == null && this.syncInternalGroups) {
List<Group> groups = this.groupService.getGroupByNameAndTenantId(this.oidcGroupToApsGroupName(oidcGroup), tenantId);
if (groups.size() > 1) {
this.logger.warn("There are multiple APS groups matching the OIDC group: {} [{}]; skipping consideration of OIDC group", oidcGroup, 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.oidcGroupToApsGroupExternalId(oidcGroup));
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 OIDC group; APS group creation is disabled; OIDC group will go unrecognized: {}", oidcGroup);
continue;
}
group = this.createApsGroup(oidcGroup, 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 oidcGroup, long tenantId) {
this.logger.debug("APS Group does not exist for OIDC group; will attempt to create: {}", oidcGroup);
String name = this.oidcGroupToApsGroupName(oidcGroup);
String externalId = this.oidcGroupToApsGroupExternalId(oidcGroup);
boolean syncAsOrg = this.isOidcGroupToBeOrganization(oidcGroup);
this.logger.trace("Creating new APS group as {}: {}", syncAsOrg ? "organization" : "capability", oidcGroup);
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 oidcGroupToApsGroupExternalId(String group) {
return this.externalIdmSource + "_" + group;
}
private String apsGroupExternalIdToOidcGroup(String externalId) {
int underscorePos = externalId.indexOf('_');
return underscorePos < 0 ? externalId : externalId.substring(underscorePos + 1);
}
private String oidcGroupToApsGroupName(String group) {
return group;
}
private String apsGroupNameToOidcGroup(String externalId) {
return externalId;
}
private boolean isOidcGroupToBeOrganization(String role) {
if (this.capabilities.isEmpty())
return true;
for (Pattern regex : this.capabilities) {
Matcher matcher = regex.matcher(role);
if (matcher.matches())
return false;
}
return true;
}
}

View File

@@ -0,0 +1,65 @@
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.
*/
@Component
@Primary
public class OIDCUserService extends OidcUserService {
private final Logger logger = LoggerFactory.getLogger(OIDCUserService.class);
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserSyncService userSyncService;
@Autowired
private GroupSyncService groupSyncService;
@Autowired
private IdentityServiceKeycloakProperties identityServiceKeycloakProperties;
@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());
this.userSyncService.sync(oidcUser);
this.groupSyncService.sync(oidcUser);
// reload for sync'd group changes
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

@@ -12,7 +12,7 @@
* 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.keycloak;
package com.inteligr8.activiti.auth.service;
import java.util.ArrayList;
import java.util.Collection;
@@ -44,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,109 @@
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.oidc.user.OidcUser;
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.sync.externalId:oauth}")
protected String externalIdmSource;
@Value("${auth-ext.sync.user.createMissing:true}")
protected boolean createMissingUser;
@Value("${auth-ext.sync.user.requireGroup:#{null}}")
protected String requiredGroup;
@Value("${auth-ext.sync.user.clearNewUserGroups:true}")
protected boolean clearNewUserGroups;
public void sync(OidcUser oidcUser) {
UserDetails springUser = this.loadSpringUser(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());
}
}
private UserDetails loadSpringUser(OidcUser oidcUser) throws UsernameNotFoundException {
try {
UserDetails springUser = this.userDetailsService.loadUserByUsername(oidcUser.getEmail());
this.logger.debug("Loaded APS user: {} => {}", oidcUser.getEmail(), 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 && (!oidcUser.hasClaim("groups") || !oidcUser.getClaimAsStringList("groups").contains(this.requiredGroup))) {
this.logger.info("User does not exist and does not have the required OIDC group to be created: {} ", oidcUser.getEmail(), this.requiredGroup);
throw unfe;
}
this.logger.debug("User does not exist; will attempt to create: {}", oidcUser.getEmail());
User apsUser = this.createApsUser(oidcUser);
if (this.clearNewUserGroups) {
apsUser = this.userService.getUser(apsUser.getId(), true);
if (this.logger.isDebugEnabled())
this.logger.debug("User is new; clearing default groups: {}: {}", oidcUser.getEmail(), apsUser.getGroups().stream().map(group -> group.getName()).toList());
this.deleteApsUserGroups(apsUser);
}
return this.userDetailsService.loadByUserId(apsUser.getId());
}
}
private User createApsUser(OidcUser oidcUser) {
long tenantId = this.tenantFinderService.findTenantId();
User user = this.userService.createNewUserFromExternalStore(
oidcUser.getEmail(),
oidcUser.getGivenName(),
oidcUser.getFamilyName(),
tenantId,
oidcUser.getEmail(),
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,286 +0,0 @@
/*
* 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.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 javax.annotation.OverridingMethodsMustInvokeSuper;
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
@OverridingMethodsMustInvokeSuper
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,304 +0,0 @@
/*
* 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.keycloak;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.OverridingMethodsMustInvokeSuper;
import jakarta.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;
/**
* 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 implementation 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.group.capability.regex.patterns:#{null}}")
protected String regexCapIncludes;
protected final Set<Pattern> capIncludes = new HashSet<>();
@Override
@OverridingMethodsMustInvokeSuper
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (this.regexCapIncludes != null) {
String[] regexPatternStrs = StringUtils.split(this.regexCapIncludes, ',');
for (int i = 0; i < regexPatternStrs.length; i++)
this.capIncludes.add(Pattern.compile(regexPatternStrs[i]));
}
}
/**
* 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;
}
// 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);
boolean syncAsOrg = this.isRoleToBeOrganization(role.getKey());
this.logger.trace("Creating new group as {}: {}", syncAsOrg ? "organization" : "capability", 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) {
if (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;
}
private boolean isRoleToBeOrganization(String role) {
if (this.capIncludes.isEmpty())
return true;
for (Pattern regex : this.capIncludes) {
Matcher matcher = regex.matcher(role);
if (matcher.matches())
return false;
}
return true;
}
}

View File

@@ -1,81 +0,0 @@
/*
* 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.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.auth.Authenticator;
import com.inteligr8.activiti.auth.InterceptingAuthenticationProvider;
import com.inteligr8.activiti.security.ActivitiSecurityConfigAdapter;
/**
* 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

@@ -1,55 +0,0 @@
/*
* 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.security;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* This provides a means to supporting multiple `SecurityConfigAdapter` options
* in one code base, while allowing only the first enabled one to be used.
*
* @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,74 +0,0 @@
/*
* 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.security;
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;
import com.inteligr8.activiti.DataFixer;
/**
* 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

@@ -0,0 +1,241 @@
{
"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"
],
"optionalClientScopes": [
"address",
"phone",
"organization",
"offline_access",
"microprofile-jwt"
]
},
{
"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"
],
"optionalClientScopes": [
"address",
"phone",
"organization",
"offline_access",
"microprofile-jwt"
]
}
],
"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"
}
}