diff --git a/README.md b/README.md
index 0e22c3f..94cf2af 100644
--- a/README.md
+++ b/README.md
@@ -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
@@ -18,57 +21,82 @@ The installation is simple. Just include the JAR in the classpath of your Activ
```
-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. |
diff --git a/pom.xml b/pom.xml
index 56a9c48..e21806a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -4,12 +4,12 @@
4.0.0
com.inteligr8.activiti
- keycloak-activiti-app-ext
- 1.4-SNAPSHOT
+ auth-activiti-app-ext
+ 2.0-SNAPSHOT
- Keycloak Authentication & Authorization for APS
- An Alfresco Process Service App extension providing improved Keycloak/AIS support.
- https://bitbucket.org/inteligr8/keycloak-activiti-app-ext
+ Authentication & Authorization for APS
+ An Alfresco Process Service App extension providing improved authentication and authorization support.
+ https://bitbucket.org/inteligr8/auth-activiti-app-ext
@@ -19,9 +19,9 @@
- scm:git:https://bitbucket.org/inteligr8/keycloak-activiti-app-ext.git
- scm:git:git@bitbucket.org:inteligr8/keycloak-activiti-app-ext.git
- https://bitbucket.org/inteligr8/keycloak-activiti-app-ext
+ scm:git:https://bitbucket.org/inteligr8/auth-activiti-app-ext.git
+ scm:git:git@bitbucket.org:inteligr8/auth-activiti-app-ext.git
+ https://bitbucket.org/inteligr8/auth-activiti-app-ext
Inteligr8
@@ -41,18 +41,24 @@
17
17
- 24.3.0
- 23.0.7
- 6.3.2
+ 25.1.1
+
+
+ 10-2.2
+ -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
+ 120000
+ my-app
+ aps-app-public
+
-
- org.springframework.security
- spring-security-oauth2-client
- ${spring-security-oauth2.version}
- provided
-
@@ -62,6 +68,7 @@
classes
provided
+
com.activiti
aspose-transformation
@@ -70,41 +77,18 @@
org.alfresco.officeservices
aoservices
-
-
-
- org.keycloak
- keycloak-spring-security-adapter
- ${keycloak.version}
-
-
+
- org.slf4j
- slf4j-api
+ com.ryantenney.metrics
+ metrics-spring
- org.jboss.logging
- jboss-logging
+ org.springframework.security.oauth
+ spring-security-oauth2
- jakarta.activation
- *
-
-
- org.apache.httpcomponents
- *
-
-
- com.fasterxml.jackson.core
- *
-
-
- org.bouncycastle
- bcprov-jdk18on
-
-
- org.bouncycastle
- bcpkix-jdk18on
+ org.springframework.security.oauth.boot
+ spring-security-oauth2-autoconfigure
@@ -113,34 +97,132 @@
- maven-shade-plugin
- 3.6.0
-
-
- shade-jar
- shade
-
- true
-
-
-
- shaded.keycloak.
-
- com.activiti.conf.**
- com.activiti.extension.conf.**
- com.inteligr8.activiti.**
- META-INF/**/*
-
-
-
-
-
-
+ io.repaint.maven
+ tiles-maven-plugin
+ 2.40
+ true
+
+
+
+
+ com.inteligr8.ootbee:beedk-aps-ext-rad-tile:1.1-SNAPSHOT
+
+
+
+ activiti-oauth-confidential
+
+
+ secret
+
+
+
+ aps-app-confidential
+ a-secret
+
+
+
+ activiti-oauth-legacy
+
+
+ rad
+ !spring
+
+
+
+ ${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
+
+
+
+ activiti-oauth-spring
+
+
+ rad
+ spring
+
+
+
+ ${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}
+
+
+
+ rad-keycloak
+
+
+ rad
+
+
+
+
+
+ 26.2
+ 8081
+
+
+
+
+ io.fabric8
+ docker-maven-plugin
+ 0.46.0
+
+
+ run-keycloak
+ test-compile
+ start
+
+
+
+ keycloak/keycloak:${keycloak.server.version}
+ keycloak
+
+ start-dev --import-realm
+
+ admin
+ admin
+
+
+ ${keycloak.server.port}:8080
+
+
+ custom
+ ${project.artifactId}
+
+
+ host.docker.internal:host-gateway
+
+
+
+ ${project.basedir}/src/test/resources/keycloak-import:/opt/keycloak/data/import:ro
+
+
+
+
+
+
+
+
+
+
+
+
ossrh-release
@@ -204,10 +286,6 @@
-
- alfresco-private
- https://artifacts.alfresco.com/nexus/content/groups/private
-
activiti-releases
https://artifacts.alfresco.com/nexus/content/repositories/activiti-enterprise-releases
diff --git a/rad.ps1 b/rad.ps1
new file mode 100644
index 0000000..61bcb2f
--- /dev/null
+++ b/rad.ps1
@@ -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!"
+
diff --git a/rad.sh b/rad.sh
new file mode 100644
index 0000000..7d34c13
--- /dev/null
+++ b/rad.sh
@@ -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!"
+
diff --git a/src/main/java/com/activiti/conf/ActivitiOotbSecurityConfigurationAdapter.java b/src/main/java/com/activiti/conf/ActivitiOotbSecurityConfigurationAdapter.java
deleted file mode 100644
index 054d266..0000000
--- a/src/main/java/com/activiti/conf/ActivitiOotbSecurityConfigurationAdapter.java
+++ /dev/null
@@ -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 .
- */
-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);
- }
-
-}
diff --git a/src/main/java/com/activiti/extension/conf/KeycloakExtSpringComponentScanner.java b/src/main/java/com/activiti/extension/conf/AuthExtSpringComponentScanner.java
similarity index 84%
rename from src/main/java/com/activiti/extension/conf/KeycloakExtSpringComponentScanner.java
rename to src/main/java/com/activiti/extension/conf/AuthExtSpringComponentScanner.java
index fc297ec..250d24f 100644
--- a/src/main/java/com/activiti/extension/conf/KeycloakExtSpringComponentScanner.java
+++ b/src/main/java/com/activiti/extension/conf/AuthExtSpringComponentScanner.java
@@ -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 {
}
diff --git a/src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminGroupFixer.java b/src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorGroupFixer.java
similarity index 62%
rename from src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminGroupFixer.java
rename to src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorGroupFixer.java
index 9d2b390..c60f3b8 100644
--- a/src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminGroupFixer.java
+++ b/src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorGroupFixer.java
@@ -12,7 +12,7 @@
* You should have received a copy of the GNU General Public License along
* with this program. If not, see .
*/
-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 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 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));
}
}
diff --git a/src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminMembersFixer.java b/src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorMembersFixer.java
similarity index 59%
rename from src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminMembersFixer.java
rename to src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorMembersFixer.java
index acb8661..9a67da2 100644
--- a/src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminMembersFixer.java
+++ b/src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorMembersFixer.java
@@ -12,7 +12,7 @@
* You should have received a copy of the GNU General Public License along
* with this program. If not, see .
*/
-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 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 adminUsers = Arrays.asList(this.adminUserStrs.split(","));
- if (adminUsers.isEmpty())
- return;
-
+ private void associateAdmins(List adminUsers) {
Long tenantId = this.tenantFinderService.findTenantId();
+
List 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());
+ }
+ }
}
}
}
diff --git a/src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminPasswordFixer.java b/src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorPasswordFixer.java
similarity index 62%
rename from src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminPasswordFixer.java
rename to src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorPasswordFixer.java
index 5ef2ec4..f1b09bf 100644
--- a/src/main/java/com/inteligr8/activiti/idm/ActivitiAppAdminPasswordFixer.java
+++ b/src/main/java/com/inteligr8/activiti/auth/ActivitiAppAdministratorPasswordFixer.java
@@ -12,7 +12,7 @@
* You should have received a copy of the GNU General Public License along
* with this program. If not, see .
*/
-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);
}
}
diff --git a/src/main/java/com/inteligr8/activiti/auth/Authenticator.java b/src/main/java/com/inteligr8/activiti/auth/Authenticator.java
deleted file mode 100644
index 4cb473c..0000000
--- a/src/main/java/com/inteligr8/activiti/auth/Authenticator.java
+++ /dev/null
@@ -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 .
- */
-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 {
- }
-
-}
diff --git a/src/main/java/com/inteligr8/activiti/auth/Bootstrapper.java b/src/main/java/com/inteligr8/activiti/auth/Bootstrapper.java
new file mode 100644
index 0000000..6cb9ade
--- /dev/null
+++ b/src/main/java/com/inteligr8/activiti/auth/Bootstrapper.java
@@ -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 bootstraps = applicationContext.getBeansOfType(BootstrapConfigurer.class);
+ bootstraps.remove("bootstrap.proxy");
+
+ this.logger.debug("Executing {} bootstrap configurers", bootstraps.size());
+ for (Entry bootstrap : bootstraps.entrySet()) {
+ this.logger.trace("Executing bootstrap configurer: {}: {}", bootstrap.getKey(), bootstrap.getValue().getClass());
+ bootstrap.getValue().applicationContextInitialized(applicationContext);
+ }
+ }
+
+}
diff --git a/src/main/java/com/inteligr8/activiti/DataFixer.java b/src/main/java/com/inteligr8/activiti/auth/DataFixer.java
similarity index 75%
rename from src/main/java/com/inteligr8/activiti/DataFixer.java
rename to src/main/java/com/inteligr8/activiti/auth/DataFixer.java
index f763521..f65027e 100644
--- a/src/main/java/com/inteligr8/activiti/DataFixer.java
+++ b/src/main/java/com/inteligr8/activiti/auth/DataFixer.java
@@ -12,7 +12,11 @@
* You should have received a copy of the GNU General Public License along
* with this program. If not, see .
*/
-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();
+ }
}
diff --git a/src/main/java/com/inteligr8/activiti/auth/InterceptingAuthenticationProvider.java b/src/main/java/com/inteligr8/activiti/auth/InterceptingAuthenticationProvider.java
deleted file mode 100644
index cec4a0c..0000000
--- a/src/main/java/com/inteligr8/activiti/auth/InterceptingAuthenticationProvider.java
+++ /dev/null
@@ -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 .
- */
-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;
- }
-
-}
diff --git a/src/main/java/com/inteligr8/activiti/auth/oauth/IdentityServiceConfigurationOverride.java b/src/main/java/com/inteligr8/activiti/auth/oauth/IdentityServiceConfigurationOverride.java
new file mode 100644
index 0000000..70a3839
--- /dev/null
+++ b/src/main/java/com/inteligr8/activiti/auth/oauth/IdentityServiceConfigurationOverride.java
@@ -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();
+ }
+
+}
diff --git a/src/main/java/com/inteligr8/activiti/auth/service/GroupSyncService.java b/src/main/java/com/inteligr8/activiti/auth/service/GroupSyncService.java
new file mode 100644
index 0000000..127541a
--- /dev/null
+++ b/src/main/java/com/inteligr8/activiti/auth/service/GroupSyncService.java
@@ -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 .
+ */
+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 includes = new HashSet<>();
+
+ @Value("${auth-ext.sync.group.exclude.patterns:#{null}}")
+ protected String excludePatterns;
+ protected final Set excludes = new HashSet<>();
+
+ @Value("${auth-ext.sync.group.capability.patterns:Superusers}")
+ protected String capabilityPatterns;
+ protected final Set capabilities = new HashSet<>();
+
+ protected final List> 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 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 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 filterGroups(Set unfilteredGroups) {
+ if (this.includes.isEmpty() && this.excludes.isEmpty())
+ return unfilteredGroups;
+
+ Set 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 translateGroups(Set untranslatedGroups) {
+ Set translatedGroups = new HashSet<>();
+
+ for (String untranslatedGroup : untranslatedGroups) {
+ String translatedGroup = null;
+
+ for (Pair 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;
+ }
+
+}
diff --git a/src/main/java/com/inteligr8/activiti/auth/service/OIDCUserService.java b/src/main/java/com/inteligr8/activiti/auth/service/OIDCUserService.java
new file mode 100644
index 0000000..81fd63d
--- /dev/null
+++ b/src/main/java/com/inteligr8/activiti/auth/service/OIDCUserService.java
@@ -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;
+ }
+
+}
diff --git a/src/main/java/com/inteligr8/activiti/keycloak/TenantFinderService.java b/src/main/java/com/inteligr8/activiti/auth/service/TenantFinderService.java
similarity index 97%
rename from src/main/java/com/inteligr8/activiti/keycloak/TenantFinderService.java
rename to src/main/java/com/inteligr8/activiti/auth/service/TenantFinderService.java
index 8210791..e345aa3 100644
--- a/src/main/java/com/inteligr8/activiti/keycloak/TenantFinderService.java
+++ b/src/main/java/com/inteligr8/activiti/auth/service/TenantFinderService.java
@@ -12,7 +12,7 @@
* You should have received a copy of the GNU General Public License along
* with this program. If not, see .
*/
-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() {
diff --git a/src/main/java/com/inteligr8/activiti/auth/service/UserSyncService.java b/src/main/java/com/inteligr8/activiti/auth/service/UserSyncService.java
new file mode 100644
index 0000000..f559b60
--- /dev/null
+++ b/src/main/java/com/inteligr8/activiti/auth/service/UserSyncService.java
@@ -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());
+ }
+ }
+
+}
diff --git a/src/main/java/com/inteligr8/activiti/keycloak/AbstractKeycloakActivitiAuthenticator.java b/src/main/java/com/inteligr8/activiti/keycloak/AbstractKeycloakActivitiAuthenticator.java
deleted file mode 100644
index 8b3b776..0000000
--- a/src/main/java/com/inteligr8/activiti/keycloak/AbstractKeycloakActivitiAuthenticator.java
+++ /dev/null
@@ -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 .
- */
-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> groupFormatters = new LinkedList<>();
- protected final Set resourceIncludes = new HashSet<>();
- protected final Set groupIncludes = new HashSet<>();
- protected final Set 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 getKeycloakRoles(Authentication auth) {
- Map 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 roles = this.filterRoles(atoken.getRealmAccess().getRoles());
- Map mappedRoles = this.formatRoles(roles);
- authorities.putAll(mappedRoles);
- }
-
- for (Entry resourceAccess : atoken.getResourceAccess().entrySet()) {
- if (this.includeResource(resourceAccess.getKey())) {
- this.logger.debug("Access token resources '{}' roles: {}", resourceAccess.getKey(), resourceAccess.getValue().getRoles());
- Collection roles = this.filterRoles(resourceAccess.getValue().getRoles());
- Map mappedRoles = this.formatRoles(roles);
- authorities.putAll(mappedRoles);
- }
- }
-
- this.logger.debug("Access token authorities: {}", authorities);
- }
-
- return authorities;
- }
-
- private Collection filterRoles(Collection unfilteredRoles) {
- if (this.groupIncludes.isEmpty() && this.groupExcludes.isEmpty())
- return unfilteredRoles;
-
- Set 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 formatRoles(Collection unformattedRoles) {
- Map formattedRoles = new HashMap<>(unformattedRoles.size());
-
- for (String unformattedRole : unformattedRoles) {
- String formattedRole = null;
-
- for (Pair 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 boolean removeMapEntriesByValue(Map map, V value) {
- if (value == null)
- throw new IllegalArgumentException();
-
- int found = 0;
-
- Iterator> i = map.entrySet().iterator();
- while (i.hasNext()) {
- Entry entry = i.next();
- if (entry.getValue() != null && value.equals(entry.getValue())) {
- i.remove();
- found++;
- }
- }
-
- return found > 0;
- }
-
- protected Set toSet(Collection extends GrantedAuthority> grantedAuthorities) {
- Set 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;
- }
-}
diff --git a/src/main/java/com/inteligr8/activiti/keycloak/KeycloakActivitiAppAuthenticator.java b/src/main/java/com/inteligr8/activiti/keycloak/KeycloakActivitiAppAuthenticator.java
deleted file mode 100644
index 5bb0b04..0000000
--- a/src/main/java/com/inteligr8/activiti/keycloak/KeycloakActivitiAppAuthenticator.java
+++ /dev/null
@@ -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 .
- */
-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 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 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 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 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;
- }
-
-}
diff --git a/src/main/java/com/inteligr8/activiti/keycloak/KeycloakSecurityConfigurationAdapter.java b/src/main/java/com/inteligr8/activiti/keycloak/KeycloakSecurityConfigurationAdapter.java
deleted file mode 100644
index 38d6309..0000000
--- a/src/main/java/com/inteligr8/activiti/keycloak/KeycloakSecurityConfigurationAdapter.java
+++ /dev/null
@@ -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 .
- */
-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()));
- }
-
-}
diff --git a/src/main/java/com/inteligr8/activiti/security/ActivitiSecurityConfigAdapter.java b/src/main/java/com/inteligr8/activiti/security/ActivitiSecurityConfigAdapter.java
deleted file mode 100644
index ce9df8e..0000000
--- a/src/main/java/com/inteligr8/activiti/security/ActivitiSecurityConfigAdapter.java
+++ /dev/null
@@ -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 .
- */
-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 {
-
- /**
- * 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());
- }
-
-}
diff --git a/src/main/java/com/inteligr8/activiti/security/Inteligr8SecurityConfigurationRegistry.java b/src/main/java/com/inteligr8/activiti/security/Inteligr8SecurityConfigurationRegistry.java
deleted file mode 100644
index 82a523f..0000000
--- a/src/main/java/com/inteligr8/activiti/security/Inteligr8SecurityConfigurationRegistry.java
+++ /dev/null
@@ -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 .
- */
-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 adapters;
-
- @Autowired(required = false)
- private List 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());
- }
- }
- }
-
-}
diff --git a/src/test/resources/keycloak-import/realm-my-app.json b/src/test/resources/keycloak-import/realm-my-app.json
new file mode 100644
index 0000000..823718b
--- /dev/null
+++ b/src/test/resources/keycloak-import/realm-my-app.json
@@ -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"
+ }
+}
\ No newline at end of file
diff --git a/src/test/resources/log4j2-test.properties b/src/test/resources/log4j2-test.properties
new file mode 100644
index 0000000..41521ae
--- /dev/null
+++ b/src/test/resources/log4j2-test.properties
@@ -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
diff --git a/src/test/resources/realm-master.json b/src/test/resources/realm-master.json
new file mode 100644
index 0000000..be4cbc1
--- /dev/null
+++ b/src/test/resources/realm-master.json
@@ -0,0 +1,8 @@
+{
+ "realm": "master",
+ "enabled": true,
+ "sslRequired": "required",
+ "attributes": {
+ "frontendUrl": "http://host.docker.internal:8081"
+ }
+}
\ No newline at end of file