Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Add Keycloak IdP APIs (#1894)

Wouter Born67b6adecb0dc
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
index ea9e2cdcd..f32509e09 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
@@ -232,7 +232,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
if (clientRepresentations.size() > 1) {
throw new IllegalStateException("More than one matching client found realm=" + realm + ", client=" + client);
}
- clientRepresentation = clientRepresentations.get(0);
+ clientRepresentation = clientRepresentations.getFirst();
clientResource = clientsResource.get(clientRepresentation.getId());
}
} catch (Exception e) {
@@ -791,7 +791,6 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
@Override
public void updateRealm(Realm realm) {
LOG.fine("Update realm: " + realm);
- realmCache.remove(realm.getName());
getRealms(realmsResource -> {
if (TextUtil.isNullOrEmpty(realm.getId())) {
@@ -836,6 +835,8 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
configureRealm(realmRepresentation);
realmResource.update(realmRepresentation);
+ realmCache.remove(realm.getName());
+
Set<RealmRole> realmRoles = (realm.getRealmRoles() != null ? realm.getRealmRoles() : new HashSet<RealmRole>())
.stream()
.filter(rr -> !isBuiltInRealmRole(rr.getName()))
@@ -1021,13 +1022,104 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
return null;
}
- ClientRepresentation newClient = clientsResource.findByClientId(client.getClientId()).get(0);
+ ClientRepresentation newClient = clientsResource.findByClientId(client.getClientId()).getFirst();
ClientResource clientResource = clientsResource.get(newClient.getId());
addDefaultRoles(clientResource.roles());
return newClient;
}));
}
+ /**
+ * Imports the identity provider configuration using the given import data. This simplifies configuring an OIDC or SAML
+ * identity provider from which some of the configuration parameters can be imported from the identity provider itself.
+ *
+ * @param realm the realm used for importing the identity provider configuration.
+ * @param importData contains the details required for importing the identity provider configuration.
+ * E.g. the following values can be used:
+ * <ul><li>{@code fromUrl}: The URL used for importing the configuration parameters</li>
+ * <li>{@code providerId}: The identity provider ({@code oidc} or {@code saml}) to import the configuration for.</li></ul>
+ *
+ * @return the imported configuration parameters which can be added to the {@link Map} provided to
+ * {@link #createUpdateIdentityProvider(String, String, String, Map)} when creating or updating an identity provider.
+ */
+ public Map<String, String> getIdentityProviderImportConfig(String realm, Map<String, Object> importData) {
+ if (importData == null || importData.isEmpty()) {
+ throw new IllegalArgumentException("Import data is null or empty");
+ }
+
+ return getRealms(realmsResource -> realmsResource.realm(realm).identityProviders().importFrom(importData));
+ }
+
+ public void createUpdateIdentityProvider(String realm, String alias, String providerId, Map<String, String> config) {
+ IdentityProviderRepresentation representation = new IdentityProviderRepresentation();
+ representation.setAlias(alias);
+ representation.setProviderId(providerId);
+ representation.setConfig(config);
+
+ getRealms(realmsResource -> {
+ IdentityProvidersResource identityProvidersResource = realmsResource.realm(realm).identityProviders();
+
+ if (identityProvidersResource.findAll().stream().anyMatch(ipr -> alias.equals(ipr.getAlias()))) {
+ identityProvidersResource.get(alias).update(representation);
+ } else {
+ try (Response response = identityProvidersResource.create(representation)) {
+ if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
+ throw new IllegalStateException("Failed to create identity provider response=" + response.getStatusInfo().getStatusCode() + ": " + representation);
+ }
+ }
+ }
+
+ return identityProvidersResource.get(alias).toRepresentation();
+ });
+ }
+
+ public void createUpdateIdentityProviderMapper(String realm, String idpAlias, String mapperName, String idpMapper, Map<String, String> mapperConfig) {
+ getRealms(realmsResource -> {
+ IdentityProviderResource idpResource = realmsResource.realm(realm).identityProviders().get(idpAlias);
+
+ IdentityProviderMapperRepresentation mapper = new IdentityProviderMapperRepresentation();
+ mapper.setName(mapperName);
+ mapper.setConfig(mapperConfig);
+ mapper.setIdentityProviderAlias(idpAlias);
+ mapper.setIdentityProviderMapper(idpMapper);
+
+ Optional<IdentityProviderMapperRepresentation> existingMapper = idpResource.getMappers().stream().filter(m -> mapperName.equals(m.getName())).findFirst();
+ if (existingMapper.isPresent()) {
+ idpResource.update(existingMapper.get().getId(), mapper);
+ } else {
+ try (Response response = idpResource.addMapper(mapper)) {
+ if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
+ throw new IllegalStateException("Failed to create identity provider mapper '" + mapperName + "' response=" + response.getStatusInfo().getStatusCode() + ": " + response.getStatusInfo().getReasonPhrase());
+ }
+ }
+ }
+
+ return null;
+ });
+ }
+
+ public void addAuthenticationExecutionConfig(String realm, String flowAlias, String executionProviderId, String authenticatorAlias, Map<String, String> authenticatorConfig) {
+ getRealms(realmsResource -> {
+ AuthenticationManagementResource authenticationManagementResource = realmsResource.realm(realm).flows();
+ List<AuthenticationExecutionInfoRepresentation> executions = authenticationManagementResource.getExecutions(flowAlias);
+ for (AuthenticationExecutionInfoRepresentation execution : executions) {
+ if (executionProviderId.equals(execution.getProviderId())) {
+ AuthenticatorConfigRepresentation config = new AuthenticatorConfigRepresentation();
+ config.setAlias(authenticatorAlias);
+ config.setConfig(authenticatorConfig);
+
+ try (Response response = authenticationManagementResource.newExecutionConfig(execution.getId(), config)) {
+ if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
+ throw new IllegalStateException("Failed to create execution config '" + authenticatorAlias + "' response=" + response.getStatusInfo().getStatusCode() + ": " + response.getStatusInfo().getReasonPhrase());
+ }
+ }
+ return null;
+ }
+ }
+ return null;
+ });
+ }
+
public void deleteClient(String realm, String clientId) {
if (TextUtil.isNullOrEmpty(realm)
@@ -1225,7 +1317,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
ComponentRepresentation newComponentRepresentation = realmResource.components()
.query(componentRepresentation.getParentId(),
componentRepresentation.getProviderType(),
- componentRepresentation.getName()).get(0);
+ componentRepresentation.getName()).getFirst();
syncUsers(newComponentRepresentation.getId(), realm, "triggerFullSync");
return newComponentRepresentation.getId();
}
@@ -1244,7 +1336,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
ComponentRepresentation newComponentRepresentation = realmResource.components()
.query(componentRepresentation.getParentId(),
componentRepresentation.getProviderType(),
- componentRepresentation.getName()).get(0);
+ componentRepresentation.getName()).getFirst();
realmResource.userStorage().syncMapperData(newComponentRepresentation.getParentId(), newComponentRepresentation.getId(), "fedToKeycloak");
return newComponentRepresentation.getId();
}
diff --git a/model/src/main/java/org/openremote/model/security/User.java b/model/src/main/java/org/openremote/model/security/User.java
index 8afeb63c6..71f47cb8f 100644
--- a/model/src/main/java/org/openremote/model/security/User.java
+++ b/model/src/main/java/org/openremote/model/security/User.java
@@ -186,6 +186,16 @@ public class User {
return this;
}
+ public User setAttribute(String key, List<String> values) {
+ if (attributes == null) {
+ attributes = new ArrayList<>();
+ } else {
+ attributes.removeIf(attr -> attr.getName().equals(key));
+ }
+ values.forEach(value -> attributes.add(new UserAttribute(key, value)));
+ return this;
+ }
+
public boolean hasAttribute(String key) {
return attributes != null && attributes.stream().anyMatch(attr -> attr.getName().equals(key));
}
diff --git a/test/src/test/groovy/org/openremote/test/security/IdentityProviderTest.groovy b/test/src/test/groovy/org/openremote/test/security/IdentityProviderTest.groovy
new file mode 100644
index 000000000..b8cd6db3b
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/security/IdentityProviderTest.groovy
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.test.security
+
+import org.keycloak.admin.client.resource.IdentityProviderResource
+import org.keycloak.admin.client.resource.IdentityProvidersResource
+import org.keycloak.representations.idm.IdentityProviderMapperRepresentation
+import org.openremote.manager.security.ManagerIdentityService
+import org.openremote.manager.security.ManagerKeycloakIdentityProvider
+import org.openremote.model.security.ClientRole
+import org.openremote.model.security.Realm
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Shared
+import spock.lang.Specification
+
+class IdentityProviderTest extends Specification implements ManagerContainerTrait {
+
+ @Shared
+ static ManagerKeycloakIdentityProvider identityProvider
+
+ def setupSpec() {
+ def container = startContainer(defaultConfig(), defaultServices())
+ identityProvider = container.getService(ManagerIdentityService.class).identityProvider as ManagerKeycloakIdentityProvider
+ }
+
+ def "Realm operations"() {
+ def realmName = "testrealm"
+ def realmDisplayName = "Test Realm"
+ def realmEnabled = true
+
+ when: "a realm does not yet exist in the identity provider"
+ !identityProvider.realmExists(realmName)
+
+ and: "the realm is created"
+ def realm = new Realm(null, realmName, realmDisplayName, realmEnabled)
+ identityProvider.createRealm(realm)
+ realm = identityProvider.getRealm(realmName)
+
+ then: "the realm exists in the identity provider"
+ identityProvider.realmExists(realmName)
+
+ and: "the realm has the correct properties"
+ realm.name == realmName
+ realm.displayName == realmDisplayName
+ realm.enabled == realmEnabled
+
+ when: "the realm is updated"
+ realmDisplayName = "Updated Test Realm"
+ realm.displayName = realmDisplayName
+ identityProvider.updateRealm(realm)
+
+ then: "the realm still exists in the identity provider"
+ identityProvider.realmExists(realmName)
+
+ when: "the realm is retrieved"
+ realm = identityProvider.getRealm(realmName)
+
+ then: "the realm has the correct properties"
+ realm.name == realmName
+ realm.displayName == realmDisplayName
+ realm.enabled == realmEnabled
+
+ when: "the realm is deleted"
+ identityProvider.deleteRealm(realmName)
+
+ then: "the realm no longer exists in the identity provider"
+ !identityProvider.realmExists(realmName)
+
+ and: "the realm cannot be retrieved"
+ identityProvider.getRealm(realmName) == null
+ }
+
+ def "Configure Keycloak chaining"() {
+ def realmName = "idprealm"
+ def realmDisplayName = "IdP Realm"
+ def realmEnabled = true
+ def idpAlias = "keycloak-oidc"
+
+ when: "a realm does not yet exist in the identity provider"
+ !identityProvider.realmExists(realmName)
+
+ and: "the realm is created"
+ def realm = new Realm(null, realmName, realmDisplayName, realmEnabled)
+ identityProvider.createRealm(realm)
+
+ then: "the realm exists in the identity provider"
+ identityProvider.realmExists(realmName)
+
+ when: "an identity provider is created in the realm"
+ Map<String, String> idpConfig = new HashMap<>();
+ idpConfig.put("clientId", "test-client");
+ idpConfig.put("clientSecret", "test-client-secret");
+ idpConfig.put("clientAuthMethod", "client_secret_basic");
+ idpConfig.put("syncMode", "FORCE");
+ idpConfig.put("filteredByClaim", "true");
+ idpConfig.put("claimFilterName", "claimName");
+ idpConfig.put("claimFilterValue", "claimValue");
+
+ identityProvider.createUpdateIdentityProvider(realmName, idpAlias, "oidc", idpConfig);
+
+ then: "the identity provider is created in the realm"
+ identityProvider.getRealms { realmsResource ->
+ IdentityProvidersResource identityProvidersResource = realmsResource.realm(realmName).identityProviders();
+ assert identityProvidersResource.findAll().stream().anyMatch(ipr -> idpAlias == ipr.getAlias())
+ return null
+ } == null
+
+ and: "the identity provider configuration matches"
+ identityProvider.getRealms { realmsResource ->
+ IdentityProvidersResource identityProvidersResource = realmsResource.realm(realmName).identityProviders();
+ Map<String, String> storedConfig = identityProvidersResource.findAll().stream().filter(ipr -> idpAlias == ipr.getAlias()).findFirst().get().getConfig()
+
+ assert idpConfig.size() == storedConfig.size()
+ idpConfig.each { key, value ->
+ if (key != "clientSecret") {
+ // clientSecret is not returned by Keycloak for security reasons
+ assert storedConfig.get(key) == value
+ }
+ }
+
+ return null
+ } == null
+
+ when: "identity provider role mappers are created for all roles"
+ ClientRole.ALL_ROLES.forEach(role -> {
+ String mapperName = role.replaceAll(":", " ")
+
+ Map<String, String> mapperConfig = new HashMap<>();
+ mapperConfig.put("syncMode", "FORCE")
+ mapperConfig.put("claim", "cloudRoles")
+ mapperConfig.put("claim.value", role)
+ mapperConfig.put("role", "openremote." + role)
+
+ identityProvider.createUpdateIdentityProviderMapper(realmName, idpAlias, mapperName, "oidc-role-idp-mapper", mapperConfig)
+ });
+
+ then: "the identity provider role mappers are created"
+ identityProvider.getRealms { realmsResource ->
+ IdentityProviderResource idpResource = realmsResource.realm(realmName).identityProviders().get(idpAlias)
+ List<IdentityProviderMapperRepresentation> mappers = idpResource.getMappers()
+
+ assert mappers.size() == ClientRole.ALL_ROLES.size()
+
+ mappers.each { mapper ->
+ Map<String, String> storedConfig = mapper.getConfig()
+ String role = storedConfig.get("claim.value")
+
+ assert ClientRole.ALL_ROLES.contains(role)
+ assert storedConfig.get("syncMode") == "FORCE"
+ assert storedConfig.get("claim") == "cloudRoles"
+ assert storedConfig.get("role") == "openremote." + role
+ }
+
+ return null
+ } == null
+
+ when: "the browser authentication flow is configured to redirect to the identity provider"
+ identityProvider.addAuthenticationExecutionConfig(realmName, "browser", "identity-provider-redirector", idpAlias, Map.of("defaultProvider", idpAlias));
+
+ then: "the authentication flow is updated"
+ identityProvider.getRealms { realmsResource ->
+ def flows = realmsResource.realm(realmName).flows().getFlows()
+ def browserFlow = flows.stream().filter { afr -> afr.getAlias() == "browser" }.findFirst().get()
+ def iprExecutions = browserFlow.getAuthenticationExecutions().stream().filter(execution -> execution.getAuthenticator() == "identity-provider-redirector").toList()
+ assert iprExecutions.size() == 1
+ assert iprExecutions.get(0).getAuthenticatorConfig() == idpAlias
+ return null
+ } == null
+ }
+
+}