You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by la...@apache.org on 2024/04/23 01:27:46 UTC
(airavata-custos) branch dev-refactoring updated: Keycloak clients refactoring
This is an automated email from the ASF dual-hosted git repository.
lahirujayathilake pushed a commit to branch dev-refactoring
in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
The following commit(s) were added to refs/heads/dev-refactoring by this push:
new e16426606 Keycloak clients refactoring
e16426606 is described below
commit e164266069583e697aa906ae8cb4fbafde303b03
Author: lahiruj <la...@gmail.com>
AuthorDate: Mon Apr 22 21:27:37 2024 -0400
Keycloak clients refactoring
---
.../services/clients/keycloak/KeycloakClient.java | 918 ++++++---------------
.../clients/keycloak/auth/KeycloakAuthClient.java | 286 ++-----
2 files changed, 340 insertions(+), 864 deletions(-)
diff --git a/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/KeycloakClient.java b/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/KeycloakClient.java
index 56496463f..488554428 100644
--- a/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/KeycloakClient.java
+++ b/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/KeycloakClient.java
@@ -19,16 +19,31 @@
package org.apache.custos.federated.services.clients.keycloak;
-import org.apache.custos.cluster.management.client.ClusterManagementClient;
import org.apache.custos.core.services.api.commons.util.Constants;
-import org.apache.custos.federated.services.clients.keycloak.auth.KeycloakAuthClient;
import org.apache.http.HttpStatus;
import org.keycloak.admin.client.Keycloak;
-import org.keycloak.admin.client.resource.*;
-import org.keycloak.representations.idm.*;
+import org.keycloak.admin.client.resource.GroupResource;
+import org.keycloak.admin.client.resource.ProtocolMappersResource;
+import org.keycloak.admin.client.resource.RealmResource;
+import org.keycloak.admin.client.resource.RoleMappingResource;
+import org.keycloak.admin.client.resource.RoleResource;
+import org.keycloak.admin.client.resource.UserResource;
+import org.keycloak.representations.idm.ClientRepresentation;
+import org.keycloak.representations.idm.CredentialRepresentation;
+import org.keycloak.representations.idm.EventRepresentation;
+import org.keycloak.representations.idm.FederatedIdentityRepresentation;
+import org.keycloak.representations.idm.GroupRepresentation;
+import org.keycloak.representations.idm.IdentityProviderRepresentation;
+import org.keycloak.representations.idm.MappingsRepresentation;
+import org.keycloak.representations.idm.ProtocolMapperRepresentation;
+import org.keycloak.representations.idm.RealmEventsConfigRepresentation;
+import org.keycloak.representations.idm.RealmRepresentation;
+import org.keycloak.representations.idm.RoleRepresentation;
+import org.keycloak.representations.idm.RolesRepresentation;
+import org.keycloak.representations.idm.UserRepresentation;
+import org.keycloak.representations.idm.UserSessionRepresentation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@@ -36,7 +51,12 @@ import javax.validation.constraints.NotNull;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import java.net.URI;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
import java.util.stream.Collectors;
/**
@@ -44,16 +64,10 @@ import java.util.stream.Collectors;
*/
@Component
public class KeycloakClient {
- private final static Logger LOGGER = LoggerFactory.getLogger(KeycloakClient.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(KeycloakClient.class);
- private final static int POOL_SIZE = 10;
-
- private final static int ACCESS_TOKEN_LIFE_SPAN = 1800;
-
- private final static int SESSION_IDLE_TIMEOUT = 3600;
-
- @Autowired
- private KeycloakAuthClient keycloakAuthClient;
+ private static final int ACCESS_TOKEN_LIFE_SPAN = 1800;
+ private static final int SESSION_IDLE_TIMEOUT = 3600;
@Value("${iam.server.client.id:admin-cli}")
private String clientId;
@@ -85,12 +99,8 @@ public class KeycloakClient {
@Value("${iam.federated.cilogon.jwksUri:https://cilogon.org/oauth2/certs}")
private String jwksUri;
-
public void createRealm(String realmId, String displayName) {
- Keycloak client = null;
- try {
- // get client
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
// create realm
RealmRepresentation newRealmDetails = new RealmRepresentation();
newRealmDetails.setEnabled(true);
@@ -106,57 +116,40 @@ public class KeycloakClient {
RealmRepresentation realmWithRoles = createDefaultRoles(newRealmDetails);
client.realms().create(realmWithRoles);
-
} catch (Exception ex) {
String msg = "Error creating Realm in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public void updateRealm(String realmId, String displayName) {
- Keycloak client = null;
- try {
- // get client
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
// create realm
-
RealmResource realmResource = client.realm(realmId);
if (realmResource != null) {
-
RealmRepresentation newRealmDetails = realmResource.toRepresentation();
newRealmDetails.setId(realmId);
newRealmDetails.setDisplayName(displayName);
newRealmDetails.setRealm(realmId);
realmResource.update(newRealmDetails);
} else {
- String msg = "Realm not found, reason: ";
- LOGGER.error(msg);
- throw new RuntimeException(msg, null);
+ LOGGER.error("Realm not found");
+ throw new RuntimeException("Realm not found");
}
} catch (Exception ex) {
String msg = "Error creating Realm in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean createRealmAdminAccount(String realmId, String adminUsername, String adminFirstname,
String adminLastname, String adminEmail, String adminPassword) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
UserRepresentation user = new UserRepresentation();
user.setUsername(adminUsername);
user.setFirstName(adminFirstname);
@@ -176,7 +169,7 @@ public class KeycloakClient {
// Add user to the "admin" role
RoleResource adminRoleResource = client.realm(realmId).roles().get("admin");
- retrievedUser.roles().realmLevel().add(Arrays.asList(adminRoleResource.toRepresentation()));
+ retrievedUser.roles().realmLevel().add(Collections.singletonList(adminRoleResource.toRepresentation()));
CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
@@ -201,28 +194,21 @@ public class KeycloakClient {
String msg = "Error creating Realm Admin Account in keycloak server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean updateRealmAdminAccount(String realmId, String adminUsername, String adminFirstname,
String adminLastname, String adminEmail, String adminPassword) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
UserRepresentation representation = getUserByUsername(client, realmId, adminUsername);
if (representation != null) {
- UserRepresentation user = representation;
- user.setUsername(adminUsername);
- user.setFirstName(adminFirstname);
- user.setLastName(adminLastname);
- user.setEmail(adminEmail);
- user.setEmailVerified(true);
- user.setEnabled(true);
+ representation.setUsername(adminUsername);
+ representation.setFirstName(adminFirstname);
+ representation.setLastName(adminLastname);
+ representation.setEmail(adminEmail);
+ representation.setEmailVerified(true);
+ representation.setEnabled(true);
client.realm(realmId).users().get(representation.getId()).update(representation);
return true;
} else {
@@ -232,24 +218,17 @@ public class KeycloakClient {
String msg = "Error updating Realm Admin Account in keycloak server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean grantAdminPrivilege(String realmId, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
UserRepresentation representation = getUserByUsername(client, realmId, username);
if (representation != null) {
-
UserResource retrievedUser = client.realm(realmId).users().get(representation.getId());
RoleResource adminRoleResource = client.realm(realmId).roles().get("admin");
- retrievedUser.roles().realmLevel().add(Arrays.asList(adminRoleResource.toRepresentation()));
+ retrievedUser.roles().realmLevel().add(Collections.singletonList(adminRoleResource.toRepresentation()));
String realmManagementClientId = getRealmManagementClientId(client, realmId);
@@ -258,61 +237,45 @@ public class KeycloakClient {
return true;
} else {
- String msg = "Cannot find existing user with username " + username;
- LOGGER.error(msg);
- throw new RuntimeException(msg);
+ LOGGER.error("Cannot find existing user with username: " + username);
+ throw new RuntimeException("Cannot find existing user with username: " + username);
}
+
} catch (Exception ex) {
String msg = "Error granting admin privilege, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean removeAdminPrivilege(String realmId, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
UserRepresentation representation = getUserByUsername(client, realmId, username);
if (representation != null) {
UserResource retrievedUser = client.realm(realmId).users().get(representation.getId());
RoleResource adminRoleResource = client.realm(realmId).roles().get("admin");
- retrievedUser.roles().realmLevel().remove(Arrays.asList(adminRoleResource.toRepresentation()));
+ retrievedUser.roles().realmLevel().remove(Collections.singletonList(adminRoleResource.toRepresentation()));
String realmManagementClientId = getRealmManagementClientId(client, realmId);
- List<RoleRepresentation> representations = retrievedUser.roles().
- clientLevel(realmManagementClientId).listEffective();
retrievedUser.roles().clientLevel(realmManagementClientId).
remove(retrievedUser.roles().clientLevel(realmManagementClientId).listEffective());
return true;
} else {
- String msg = "Cannot find existing user with username " + username;
- LOGGER.error(msg);
- throw new RuntimeException(msg);
+ LOGGER.error("Cannot find existing user with username: " + username);
+ throw new RuntimeException("Cannot find existing user with username: " + username);
}
} catch (Exception ex) {
String msg = "Error removing admin privilege, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
- public KeycloakClientSecret configureClient(String realmId, String clientName,
- @NotNull String tenantURL, List<String> redirectUris) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ public KeycloakClientSecret configureClient(String realmId, String clientName, @NotNull String tenantURL, List<String> redirectUris) {
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
ClientRepresentation pgaClient = new ClientRepresentation();
pgaClient.setName(clientName);
pgaClient.setClientId(clientName);
@@ -325,24 +288,16 @@ public class KeycloakClient {
pgaClient.setFullScopeAllowed(true);
pgaClient.setClientAuthenticatorType("client-secret");
-
pgaClient.setBaseUrl(tenantURL);
-
// Remove trailing slash from gatewayURL
if (tenantURL.endsWith("/")) {
tenantURL = tenantURL.substring(0, tenantURL.length() - 1);
}
- // Add redirect URL after login
- // redirectUris.add(tenantURL + "/callback-url"); // PGA
- // redirectUris.add(tenantURL + "/auth/callback*"); // Django
- // Add redirect URL after logout
- List<String> newList = new ArrayList<>();
- newList.addAll(redirectUris);
+ List<String> newList = new ArrayList<>(redirectUris);
newList.add(tenantURL);
-
pgaClient.setRedirectUris(newList);
List<String> webOrigins = new ArrayList<>();
@@ -350,123 +305,93 @@ public class KeycloakClient {
pgaClient.setWebOrigins(webOrigins);
pgaClient.setPublicClient(false);
- Response httpResponse = client.realms().realm(realmId).clients().create(pgaClient);
- LOGGER.debug("Realm client configuration exited with code : " + httpResponse.getStatus() + " : " + httpResponse.getStatusInfo());
-
- // Add the manage-users role to the web client
- UserRepresentation serviceAccountUserRepresentation =
- getUserByUsername(client, realmId, "service-account-" + pgaClient.getClientId());
- UserResource serviceAccountUser = client.realms().realm(realmId).users().get(serviceAccountUserRepresentation.getId());
- String realmManagementClientId = getRealmManagementClientId(client, realmId);
- List<RoleRepresentation> manageUsersRole =
- serviceAccountUser.roles().clientLevel(realmManagementClientId).listAvailable()
- .stream()
- .filter(r -> r.getName().equals("manage-users"))
- .collect(Collectors.toList());
- serviceAccountUser.roles().clientLevel(realmManagementClientId).add(manageUsersRole);
-
- if (httpResponse.getStatus() == HttpStatus.SC_CREATED) {
- String ClientUUID = client.realms().realm(realmId).clients().findByClientId(pgaClient.getClientId()).get(0).getId();
- CredentialRepresentation clientSecret = client.realms().realm(realmId).clients().get(ClientUUID).getSecret();
- KeycloakClientSecret keycloakClientSecret = new KeycloakClientSecret(pgaClient.getClientId(), clientSecret.getValue());
- return keycloakClientSecret;
- } else {
- LOGGER.error("Request for realm client creation failed with HTTP code : " + httpResponse.getStatus());
- LOGGER.error("Reason for realm client creation failure : " + httpResponse.getStatusInfo());
- throw new RuntimeException("Reason for realm client creation failure :" + httpResponse.getStatusInfo(), null);
+ try (Response httpResponse = client.realms().realm(realmId).clients().create(pgaClient)) {
+ LOGGER.debug("Realm client configuration exited with code : " + httpResponse.getStatus() + " : " + httpResponse.getStatusInfo());
+
+ // Add the manage-users role to the web client
+ UserRepresentation serviceAccountUserRepresentation =
+ getUserByUsername(client, realmId, "service-account-" + pgaClient.getClientId());
+ UserResource serviceAccountUser = client.realms().realm(realmId).users().get(serviceAccountUserRepresentation.getId());
+ String realmManagementClientId = getRealmManagementClientId(client, realmId);
+ List<RoleRepresentation> manageUsersRole =
+ serviceAccountUser.roles().clientLevel(realmManagementClientId).listAvailable()
+ .stream()
+ .filter(r -> r.getName().equals("manage-users"))
+ .collect(Collectors.toList());
+ serviceAccountUser.roles().clientLevel(realmManagementClientId).add(manageUsersRole);
+
+ if (httpResponse.getStatus() == HttpStatus.SC_CREATED) {
+ String ClientUUID = client.realms().realm(realmId).clients().findByClientId(pgaClient.getClientId()).get(0).getId();
+ CredentialRepresentation clientSecret = client.realms().realm(realmId).clients().get(ClientUUID).getSecret();
+ return new KeycloakClientSecret(pgaClient.getClientId(), clientSecret.getValue());
+
+ } else {
+ LOGGER.error("Request for realm client creation failed with HTTP code : " + httpResponse.getStatus());
+ LOGGER.error("Reason for realm client creation failure : " + httpResponse.getStatusInfo());
+ throw new RuntimeException("Reason for realm client creation failure :" + httpResponse.getStatusInfo(), null);
+ }
}
} catch (Exception ex) {
String msg = "Error getting values from property file, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
-
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
- public KeycloakClientSecret updateClient(String realmId, String clientName,
- @NotNull String tenantURL, List<String> redirectUris) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ public KeycloakClientSecret updateClient(String realmId, String clientName, @NotNull String tenantURL, List<String> redirectUris) {
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
List<ClientRepresentation> clientRepresentations = client.realm(realmId).clients().findByClientId(clientName);
if (clientRepresentations == null || clientRepresentations.isEmpty()) {
- String msg = "Cannot find a client with name " + clientName;
- LOGGER.error(msg);
- throw new RuntimeException(msg);
+ LOGGER.error("Cannot find a client with name " + clientName);
+ throw new RuntimeException("Cannot find a client with name " + clientName);
}
ClientRepresentation pgaClient = clientRepresentations.get(0);
-
pgaClient.setBaseUrl(tenantURL);
-
// Remove trailing slash from gatewayURL
if (tenantURL.endsWith("/")) {
tenantURL = tenantURL.substring(0, tenantURL.length() - 1);
}
- // Add redirect URL after login
- // redirectUris.add(tenantURL + "/callback-url"); // PGA
- // redirectUris.add(tenantURL + "/auth/callback*"); // Django
- // Add redirect URL after logout
- List<String> newList = new ArrayList<>();
- newList.addAll(redirectUris);
+ List<String> newList = new ArrayList<>(redirectUris);
newList.add(tenantURL);
-
pgaClient.setRedirectUris(newList);
pgaClient.setPublicClient(false);
client.realms().realm(realmId).clients().get(pgaClient.getId()).update(pgaClient);
String ClientUUID = client.realms().realm(realmId).clients().findByClientId(pgaClient.getClientId()).get(0).getId();
CredentialRepresentation clientSecret = client.realms().realm(realmId).clients().get(ClientUUID).getSecret();
- KeycloakClientSecret keycloakClientSecret = new KeycloakClientSecret(pgaClient.getClientId(), clientSecret.getValue());
- return keycloakClientSecret;
+ return new KeycloakClientSecret(pgaClient.getClientId(), clientSecret.getValue());
} catch (Exception ex) {
String msg = "Error getting values from property file, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
-
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean isUsernameAvailable(String realmId, String username, String accessToken) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
return userRepresentation == null;
+
} catch (Exception ex) {
String msg = "Error getting values from property file, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean createUser(String realmId, String username, String newPassword, String firstName,
- String lastName, String emailAddress,
- boolean tempPassowrd, String accessToken) throws UnauthorizedException {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
+ String lastName, String emailAddress, boolean tempPassowrd, String accessToken) throws UnauthorizedException {
+
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation user = new UserRepresentation();
user.setUsername(username);
user.setFirstName(firstName);
@@ -488,137 +413,97 @@ public class KeycloakClient {
credential.setTemporary(tempPassowrd);
retrievedUser.resetPassword(credential);
return true;
+
} else {
String msg = "Reason for user account creation failure : " + httpResponse.getStatusInfo();
LOGGER.error("Request for user Account Creation failed with HTTP code : " + httpResponse.getStatus());
LOGGER.error(msg);
throw new UnauthorizedException(msg, null);
}
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean enableUserAccount(String realmId, String accessToken, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
-
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
UserResource userResource = client.realm(realmId).users().get(userRepresentation.getId());
UserRepresentation profile = userResource.toRepresentation();
profile.setEnabled(true);
- // We require that a user verify their email before enabling the account
- // profile.setEmailVerified(true);
userResource.update(profile);
return true;
+
} catch (Exception ex) {
String msg = "Error occurred enableUserAccount, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean disableUserAccount(String realmId, String accessToken, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
-
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
if (userRepresentation != null) {
-
UserResource userResource = client.realm(realmId).users().get(userRepresentation.getId());
UserRepresentation profile = userResource.toRepresentation();
profile.setEnabled(false);
- // We require that a user verify their email before enabling the account
- // profile.setEmailVerified(true);
userResource.update(profile);
}
return true;
+
} catch (Exception ex) {
String msg = "Error in disableUserAccount at keycloak, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean isUserAccountEnabled(String realmId, String accessToken, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
return userRepresentation != null && userRepresentation.isEnabled();
+
} catch (Exception ex) {
String msg = "Error getting values from property file, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean isUserExist(String realmId, String accessToken, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
return userRepresentation != null;
+
} catch (Exception ex) {
String msg = "Error getting values from property file, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public UserRepresentation getUser(String realmId, String accessToken, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
return getUserByUsername(client, realmId, username);
+
} catch (Exception ex) {
String msg = "Error retrieving user, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public UserRepresentation getUser(String realmId, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
return getUserByUsername(client, realmId, username);
+
} catch (Exception ex) {
String msg = "Error retrieving user, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
@@ -626,27 +511,19 @@ public class KeycloakClient {
public List<UserRepresentation> getUsers(String accessToken, String realmId, int offset, int limit,
String username, String firstName, String lastName,
String email, String search) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL,superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
return searchUsers(client, realmId, username, firstName, lastName, email, search, offset, limit);
} catch (Exception ex) {
String msg = "Error occurred while searching for user, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean resetUserPassword(String accessToken, String realmId, String username, String newPassword) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
if (userRepresentation != null) {
UserResource retrievedUser = client.realm(realmId).users().get(userRepresentation.getId());
@@ -669,40 +546,24 @@ public class KeycloakClient {
String msg = "Error resetting user password in keycloak server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public List<UserRepresentation> findUser(String accessToken, String realmId, String email, String userName) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
- return client.realm(realmId).users().search(userName,
- null,
- null,
- email,
- 0, 1);
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
+ return client.realm(realmId).users().search(userName, null, null, email, 0, 1);
} catch (Exception ex) {
String msg = "Error finding user in keycloak server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public void updateUserRepresentation(String accessToken, String realmId, String username,
String firstname, String lastName, String email) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
if (userRepresentation != null) {
userRepresentation.setFirstName(firstname);
@@ -718,18 +579,12 @@ public class KeycloakClient {
String msg = "Error updating user profile in keycloak server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean deleteUser(String accessToken, String realmId, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
if (userRepresentation != null) {
client.realm(realmId).users().delete(userRepresentation.getId());
@@ -741,10 +596,6 @@ public class KeycloakClient {
String msg = "Error deleting user in keycloak server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
@@ -752,9 +603,7 @@ public class KeycloakClient {
public boolean addRolesToUsers(String accessToken, String realmId, List<String> users,
List<String> roles, String clientId, boolean clientLevel) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
for (String username : users) {
UserRepresentation representation = getUserByUsername(client, realmId, username.toLowerCase());
@@ -786,10 +635,6 @@ public class KeycloakClient {
String msg = "Error while adding roles to user " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
@@ -797,9 +642,7 @@ public class KeycloakClient {
public boolean removeRoleFromUser(String accessToken, String realmId, String username,
List<String> roles, String clientId, boolean clientLevel) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
UserRepresentation representation = getUserByUsername(client, realmId, username.toLowerCase());
if (representation != null) {
@@ -843,20 +686,12 @@ public class KeycloakClient {
String msg = "Error removing roles from user , reason " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean deleteRealm(String realmId) {
- Keycloak client = null;
- try {
- // get client
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
if (realmResource != null) {
@@ -869,10 +704,6 @@ public class KeycloakClient {
String msg = "Error deleting Realm in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
return true;
@@ -880,22 +711,15 @@ public class KeycloakClient {
public boolean configureOIDCFederatedIDP(String realmId, String displayName, String scopes, KeycloakClientSecret secret, Map<String, String> configs) {
- Keycloak client = null;
- try {
-
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
List<IdentityProviderRepresentation> representations = realmResource.identityProviders().findAll();
-
for (IdentityProviderRepresentation representation : representations) {
-
realmResource.identityProviders().get(representation.getInternalId()).remove();
-
}
-
IdentityProviderRepresentation idp = new IdentityProviderRepresentation();
idp.setAlias("oidc");
@@ -918,15 +742,10 @@ public class KeycloakClient {
realmResource.identityProviders().create(idp);
-
} catch (Exception ex) {
String msg = "Error occurred while configuring IDP in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
return true;
}
@@ -941,14 +760,10 @@ public class KeycloakClient {
* @return
*/
public boolean addUserAttributes(String realmId, String accessToken, Map<String, List<String>> attributeMap, List<String> users) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
-
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
RealmResource realmResource = client.realm(realmId);
for (String user : users) {
-
UserRepresentation userRepresentation = getUserByUsername(client, realmId, user.toLowerCase());
if (userRepresentation != null) {
@@ -961,6 +776,7 @@ public class KeycloakClient {
exAtrMap.put(key, attributeMap.get(key));
});
userRepresentation.setAttributes(exAtrMap);
+
} else {
userRepresentation.setAttributes(attributeMap);
}
@@ -969,39 +785,30 @@ public class KeycloakClient {
}
}
-
} catch (Exception ex) {
String msg = "Error occurred while adding user attributes in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
return true;
-
}
/**
- * This deletes user attributes of users
+ * Deletes the specified attributes for the given users in Keycloak Server.
*
- * @param realmId
- * @param attributeMap
- * @param users
- * @return
+ * @param realmId The ID of the realm in Keycloak.
+ * @param accessToken The access token for authentication.
+ * @param attributeMap A map containing attribute names as keys and lists of attribute values to delete as values.
+ * @param users A list of usernames for the users whose attributes need to be deleted.
+ * @return true if the attributes were successfully deleted, false otherwise.
+ * @throws RuntimeException if an error occurs while deleting user attributes.
*/
public boolean deleteUserAttributes(String realmId, String accessToken, Map<String, List<String>> attributeMap, List<String> users) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
-
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
RealmResource realmResource = client.realm(realmId);
for (String user : users) {
-
UserRepresentation userRepresentation = getUserByUsername(client, realmId, user.toLowerCase());
UserResource resource = realmResource.users().get(userRepresentation.getId());
@@ -1026,63 +833,48 @@ public class KeycloakClient {
String msg = "Error occurred while deleting user attributes in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
return true;
-
}
/**
- * Create protocol mapper representation in given client
+ * Adds a protocol mapper to a client in the specified realm
*
- * @param protocolMapperRepresentations
- * @param realmId
- * @param clientId
- * @return
+ * @param protocolMapperRepresentation the representation of the protocol mapper to be added
+ * @param realmId the ID of the realm
+ * @param clientId the ID of the client
+ * @return true if the protocol mapper was successfully added, false otherwise
*/
- public boolean addProtocolMapper(ProtocolMapperRepresentation protocolMapperRepresentations,
+ public boolean addProtocolMapper(ProtocolMapperRepresentation protocolMapperRepresentation,
String realmId, String clientId) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
ClientRepresentation representation = realmResource.clients().findByClientId(clientId).get(0);
-
ProtocolMappersResource resource = realmResource.clients().get(representation.getId()).getProtocolMappers();
- resource.createMapper(protocolMapperRepresentations);
+ resource.createMapper(protocolMapperRepresentation);
} catch (Exception ex) {
String msg = "Error occurred while adding protocol mappers in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
return true;
}
/**
- * Get all users of given tenant
+ * Retrieves a list of UserRepresentation objects for all users in the specified realm.
*
- * @param realmId
- * @return
+ * @param realmId The ID of the realm from which to retrieve the users.
+ * @return A List of UserRepresentation objects containing the user details.
+ * @throws RuntimeException if an error occurred while fetching the user details.
*/
public List<UserRepresentation> getAllUsers(String realmId) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
List<UserRepresentation> representations = client.realm(realmId).users().list();
List<UserRepresentation> representationList = new ArrayList<>();
if (representations != null && !representations.isEmpty()) {
@@ -1096,28 +888,22 @@ public class KeycloakClient {
String msg = "Error occurred while adding protocol mappers in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
}
/**
- * Configure Roles in keycloak Realm or Client
+ * Adds a list of roles to a realm or client in Keycloak Server.
*
- * @param roleRepresentations
- * @param realmId
- * @param clientScope if true add roles to client else to realm
- * @return
+ * @param roleRepresentations The list of role representations to be added.
+ * @param realmId The ID of the realm.
+ * @param clientId The ID of the client (if clientScope is true).
+ * @param clientScope Flag indicating whether the roles should be added to a client or realm.
+ * @return A boolean indicating whether the roles were successfully added.
+ * @throws RuntimeException if an error occurs while adding roles in Keycloak Server.
*/
public boolean addRoles(List<RoleRepresentation> roleRepresentations, String realmId, String clientId, boolean clientScope) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
if (clientScope) {
@@ -1128,38 +914,31 @@ public class KeycloakClient {
}
} else {
-
for (RoleRepresentation representation : roleRepresentations) {
realmResource.roles().create(representation);
}
-
}
} catch (Exception ex) {
String msg = "Error occurred while adding roles in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
return true;
}
/**
- * Delete Roles in keycloak Realm or Client
+ * Deletes a role in Keycloak server.
*
- * @param realmId
+ * @param id the ID of the role to be deleted
+ * @param realmId the ID of the realm in which the role exists
+ * @param clientId the ID of the client for which the role is associated
* @param clientScope if true add roles to client else to realm
- * @return
+ * @return true if the role is successfully deleted, false otherwise
+ * @throws RuntimeException if an error occurs while deleting the role
*/
public boolean deleteRole(String id, String realmId, String clientId, boolean clientScope) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
if (clientScope) {
@@ -1168,18 +947,12 @@ public class KeycloakClient {
} else {
realmResource.roles().deleteRole(id);
-
}
} catch (Exception ex) {
- String msg = "Error occurred while delete role" + id +
- " in Keycloak Server, reason: " + ex.getMessage();
+ String msg = "Error occurred while delete role" + id + " in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
return true;
}
@@ -1189,62 +962,50 @@ public class KeycloakClient {
* Provides all Roles belongs to client, if clientId not present, provides all
* Roles related to Realm
*
- * @param realmId
- * @param clientId
+ * @param realmId The ID of the realm to retrieve the roles from.
+ * @param clientId Optional parameter to filter roles for a specific client. Null to retrieve all roles in the realm.
+ * @return A list of RoleRepresentation objects representing the retrieved roles.
+ * @throws RuntimeException If an error occurs while accessing the Keycloak Server.
*/
public List<RoleRepresentation> getAllRoles(String realmId, String clientId) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
if (clientId != null) {
-
ClientRepresentation representation = realmResource.clients().findByClientId(clientId).get(0);
-
return realmResource.clients().get(representation.getId()).roles().list();
} else {
return realmResource.roles().list();
-
}
} catch (Exception ex) {
String msg = "Error occurred while adding roles in Keycloak Server, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
/**
- * Configure event persistance for Keycloak Realms.
+ * Configures event persistence for a given realm and event type.
*
- * @param realmId
- * @param eventType
- * @param time
- * @param enabelEvents
- * @param isAdminEvent
- * @return
+ * @param realmId the ID of the realm
+ * @param eventType the type of event to configure
+ * @param time the expiration time for the events (in milliseconds)
+ * @param enableEvents whether to enable event persistence
+ * @param isAdminEvent whether the event is an admin event
+ * @return true if event persistence was successfully configured, false otherwise
+ * @throws RuntimeException if an error occurred while configuring event persistence
*/
- public boolean configureEventPersistence(String realmId, String eventType, long time, boolean enabelEvents, boolean isAdminEvent) {
-
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
+ public boolean configureEventPersistence(String realmId, String eventType, long time, boolean enableEvents, boolean isAdminEvent) {
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmEventsConfigRepresentation representation = client.realm(realmId).getRealmEventsConfig();
if (isAdminEvent) {
representation.setAdminEventsEnabled(true);
} else {
- representation.setEventsEnabled(enabelEvents);
+ representation.setEventsEnabled(enableEvents);
representation.setEventsExpiration(time);
List<String> eventTypes = representation.getEnabledEventTypes();
if (eventTypes != null && !eventTypes.isEmpty() && !eventTypes.contains(eventType)) {
@@ -1256,45 +1017,33 @@ public class KeycloakClient {
}
representation.setEnabledEventTypes(eventTypes);
-
client.realm(realmId).updateRealmEventsConfig(representation);
-
}
-
return true;
+
} catch (Exception ex) {
String msg = "Error occurred while configuring event persistence events, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
/**
- * Get Last login event of given user
+ * Retrieve the last login event for a given user.
*
- * @param realmId
- * @param clientId
- * @return
+ * @param realmId the ID of the realm in which the user is authenticated
+ * @param clientId the ID of the client involved in the login
+ * @param username the username of the user
+ * @return the most recent EventRepresentation object representing the last login event for the user,
+ * or null if no login event is found or an error occurred
*/
public EventRepresentation getLastLoginEvent(String realmId, String clientId, String username) {
-
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
List<EventRepresentation> eventRepresentations = client.realm(realmId).getEvents();
for (EventRepresentation representation : eventRepresentations) {
Map<String, String> map = representation.getDetails();
-
-
if (map != null && !map.isEmpty()) {
for (String key : map.keySet()) {
if (key.equals("username") && map.get(key).equals(username)) {
@@ -1303,37 +1052,29 @@ public class KeycloakClient {
}
}
}
-
return null;
} catch (Exception ex) {
String msg = "Error occurred while pulling events, reason: " + ex.getMessage();
LOGGER.warn(msg, ex);
return null;
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
/**
- * provides last active session of given user
+ * Retrieves the latest user session for the given realm, client, access token, and username.
+ * Returns null if no user session is found.
*
- * @param realmId
- * @param clientId
- * @param accessToken
- * @param username
- * @return
+ * @param realmId the ID of the realm
+ * @param clientId the ID of the client
+ * @param accessToken the access token for authorization
+ * @param username the username of the user
+ * @return the latest UserSessionRepresentation if found, otherwise null
+ * @throws RuntimeException if an error occurs while retrieving the user session
*/
public UserSessionRepresentation getLatestSession(String realmId, String clientId, String accessToken, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
List<UserRepresentation> userResourceList = client.realm(realmId).users().search(
username.toLowerCase(), null, null, null, null, null);
@@ -1344,30 +1085,19 @@ public class KeycloakClient {
if (!userSessionRepresentations.isEmpty()) {
return userSessionRepresentations.get(userSessionRepresentations.size() - 1);
}
-
}
-
return null;
+
} catch (Exception ex) {
String msg = "Error occurred while pulling active user sessions, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
public boolean deleteExternalIDPLinks(String realmId) {
-
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
List<UserRepresentation> userResourceList = client.realm(realmId).users().list();
userResourceList.forEach(user -> {
@@ -1381,26 +1111,16 @@ public class KeycloakClient {
}
});
return true;
+
} catch (Exception ex) {
- String msg = "Error occurred while deleting external IDP links of realm "
- + realmId + ", reason " + ex.getMessage();
+ String msg = "Error occurred while deleting external IDP links of realm " + realmId + ", reason " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
public boolean deleteExternalIDPLinks(String realmId, List<String> users) {
-
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
List<UserRepresentation> userResourceList = client.realm(realmId).users().list();
userResourceList.forEach(user -> {
@@ -1416,28 +1136,19 @@ public class KeycloakClient {
}
});
return true;
+
} catch (Exception ex) {
String msg = "Error occurred while deleting external IDP links of realm "
+ realmId + ", reason " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
public List<FederatedIdentityRepresentation> getExternalIDPLinks(String realmId, String requestedUser) {
-
- Keycloak client = null;
List<FederatedIdentityRepresentation> arrayList = new ArrayList<>();
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
RealmResource realmResource = client.realm(realmId);
List<UserRepresentation> userResourceList = client.realm(realmId).users().list();
userResourceList.forEach(user -> {
@@ -1446,38 +1157,26 @@ public class KeycloakClient {
List<FederatedIdentityRepresentation> federatedIdentityRepresentations =
userResource.getFederatedIdentity();
if (federatedIdentityRepresentations != null && !federatedIdentityRepresentations.isEmpty()) {
- federatedIdentityRepresentations.forEach(fed -> {
- arrayList.add(fed);
- });
+ arrayList.addAll(federatedIdentityRepresentations);
}
}
});
return arrayList;
+
} catch (Exception ex) {
- String msg = "Error occurred while deleting external IDP links of realm "
- + realmId + ", reason " + ex.getMessage();
+ String msg = "Error occurred while deleting external IDP links of realm " + realmId + ", reason " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
public void addExternalIDPLinks(String realmId, List<FederatedIdentityRepresentation> representations) {
-
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
- Keycloak finalClient = client;
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
if (representations != null && !representations.isEmpty()) {
representations.forEach(fed -> {
- List<UserRepresentation> userRepresentationList = finalClient.realm(realmId).users().search(fed.getUserName());
+ List<UserRepresentation> userRepresentationList = client.realm(realmId).users().search(fed.getUserName());
userRepresentationList.forEach(user -> {
- UserResource userResource = finalClient.realm(realmId).users().get(user.getId());
+ UserResource userResource = client.realm(realmId).users().get(user.getId());
userResource.addFederatedIdentity(fed.getIdentityProvider(), fed);
});
@@ -1485,42 +1184,31 @@ public class KeycloakClient {
}
} catch (Exception ex) {
- String msg = "Error occurred while adding external IDP links " +
- realmId + ", reason " + ex.getMessage();
+ String msg = "Error occurred while adding external IDP links " + realmId + ", reason " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
/**
- * creates groups and child groups in Keycloak
+ * Creates groups in Keycloak for a given realm.
*
- * @param realmId
- * @param clientId
- * @param accessToken
- * @param groupRepresentations
- * @return
+ * @param realmId The ID of the realm.
+ * @param clientId The ID of the client.
+ * @param clientSec The client secret.
+ * @param groupRepresentations The list of GroupRepresentation objects representing the groups to be created.
+ * @return A list of GroupRepresentation objects representing the created groups in Keycloak.
*/
public List<GroupRepresentation> createGroups(String realmId, String clientId, String clientSec, List<GroupRepresentation> groupRepresentations) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
List<GroupRepresentation> representationList = new ArrayList<>();
for (GroupRepresentation representation : groupRepresentations) {
-
-
Response response = client.realm(realmId).groups().add(representation);
-
if (response.getStatus() == HttpStatus.SC_CREATED) {
String id = getCreatedId(response);
@@ -1560,14 +1248,15 @@ public class KeycloakClient {
representation.setId(id);
this.createGroup(client, realmId, clientId, representation);
response.close();
- GroupRepresentation savedRep =
- client.realm(realmId).groups().group(representation.getId()).toRepresentation();
+ GroupRepresentation savedRep = client.realm(realmId).groups().group(representation.getId()).toRepresentation();
representationList.add(savedRep);
return representationList;
+
} else if (response.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
String msg = "Error occurred while creating group, reason: HTTP " + response.getStatus() + " Unauthorized";
LOGGER.error(msg);
throw new RuntimeException(msg);
+
} else {
String msg = "Error occurred while creating group, reason: HTTP " + response.getStatus();
LOGGER.error(msg);
@@ -1578,34 +1267,25 @@ public class KeycloakClient {
String msg = "Error occurred while creating group, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
return null;
}
/**
- * Update given group
+ * Updates the given group representation in the specified realm.
*
- * @param realmId
- * @param accessToken
- * @param groupRepresentation
- * @return
+ * @param realmId The ID of the realm.
+ * @param clientId The ID of the client.
+ * @param clientSec The secret key of the client.
+ * @param groupRepresentation The group representation to update.
+ * @return The updated group representation.
*/
public GroupRepresentation updateGroup(String realmId, String clientId, String clientSec, GroupRepresentation groupRepresentation) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
- client.realm(realmId).groups().
- group(groupRepresentation.getId()).update(groupRepresentation);
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
+ client.realm(realmId).groups().group(groupRepresentation.getId()).update(groupRepresentation);
- List<RoleRepresentation> exRoles =
- client.realm(realmId).groups().group(groupRepresentation.getId()).roles().realmLevel().listAll();
+ List<RoleRepresentation> exRoles = client.realm(realmId).groups().group(groupRepresentation.getId()).roles().realmLevel().listAll();
if (exRoles != null && !exRoles.isEmpty()) {
client.realm(realmId).groups().group(groupRepresentation.getId()).roles().realmLevel().remove(exRoles);
@@ -1625,12 +1305,10 @@ public class KeycloakClient {
}
- ClientRepresentation clientRepresentation =
- client.realm(realmId).clients().findByClientId(clientId).get(0);
+ ClientRepresentation clientRepresentation = client.realm(realmId).clients().findByClientId(clientId).get(0);
- List<RoleRepresentation> exClientRoles =
- client.realm(realmId).groups().group(groupRepresentation.getId())
- .roles().clientLevel(clientRepresentation.getId()).listAll();
+ List<RoleRepresentation> exClientRoles = client.realm(realmId).groups().group(groupRepresentation.getId())
+ .roles().clientLevel(clientRepresentation.getId()).listAll();
if (exClientRoles != null && !exClientRoles.isEmpty()) {
client.realm(realmId).groups().group(groupRepresentation.getId())
@@ -1641,7 +1319,6 @@ public class KeycloakClient {
List<RoleRepresentation> clientRepresentations = new ArrayList<>();
for (String role : groupRepresentation.getClientRoles().get(clientId)) {
-
RoleResource resource = client.realm(realmId).clients().get(clientRepresentation.getId()).roles().get(role);
if (resource != null) {
@@ -1657,67 +1334,48 @@ public class KeycloakClient {
return client.realm(realmId).groups().group(groupRepresentation.getId()).toRepresentation();
-
} catch (Exception ex) {
String msg = "Error occurred while updating group, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
/**
- * Delete given group
+ * Deletes a group from Keycloak.
*
- * @param realmId
- * @param accessToken
- * @param groupId
- * @return
+ * @param realmId the ID of the realm containing the group
+ * @param clientId the ID of the client used for authentication
+ * @param clientSec the secret key of the client used for authentication
+ * @param groupId the ID of the group to be deleted
+ * @return true if the group is deleted successfully, false otherwise
*/
public boolean deleteGroup(String realmId, String clientId, String clientSec, String groupId) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
- String id = client.realm(realmId).groups().
- group(groupId).toRepresentation().getId();
-
- client.realm(realmId).groups().
- group(id).remove();
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
+ String id = client.realm(realmId).groups().group(groupId).toRepresentation().getId();
+ client.realm(realmId).groups().group(id).remove();
return true;
+
} catch (Exception ex) {
String msg = "Error occurred while deleting group, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
-
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
/**
- * find group by group Id or group name
+ * Finds a group in the Keycloak server.
*
- * @param realmId
- * @param accessToken
- * @return
+ * @param realmId the ID of the realm where the group is located
+ * @param accessToken the access token used for authentication
+ * @param id the ID of the group to find
+ * @param name the name of the group to find
+ * @return the GroupRepresentation object representing the found group, or null if not found or an error occurred
*/
public GroupRepresentation findGroup(String realmId, String accessToken, String id, String name) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
-
- if (id != null && !id.trim().equals("")) {
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
+ if (id != null && !id.trim().isEmpty()) {
GroupResource resource = client.realm(realmId).groups().group(id);
if (resource != null) {
return resource.toRepresentation();
@@ -1738,30 +1396,23 @@ public class KeycloakClient {
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
}
- } finally {
- if (client != null) {
- client.close();
- }
}
return null;
}
/**
- * pull all groups related to given realm
+ * Retrieves all groups for a given realm.
*
- * @param realmId
- * @param accessToken
- * @return
+ * @param realmId The ID of the realm.
+ * @param accessToken The access token for authentication.
+ * @return A list of GroupRepresentation objects representing the groups in the realm.
+ * Returns null if an HTTP 404 error occurs.
*/
public List<GroupRepresentation> getAllGroups(String realmId, String accessToken) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
-
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
List<GroupRepresentation> groupRepresentations = new ArrayList<>();
-
for (GroupRepresentation representation : client.realm(realmId).groups().groups()) {
groupRepresentations.
add(client.realm(realmId).groups().group(representation.getId()).toRepresentation());
@@ -1769,7 +1420,6 @@ public class KeycloakClient {
return groupRepresentations;
-
} catch (Exception ex) {
if (ex.getMessage().contains("HTTP 404")) {
return null;
@@ -1778,23 +1428,13 @@ public class KeycloakClient {
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
}
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean addUserToGroup(String realmId, String username, String groupId, String accessToken) {
-
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
-
client.realm(realmId).users().get(userRepresentation.getId()).joinGroup(groupId);
return true;
@@ -1802,22 +1442,13 @@ public class KeycloakClient {
String msg = "Error occurred while adding user to group, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean removeUserFromGroup(String realmId, String username, String groupId, String accessToken) {
-
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, realmId, accessToken);
-
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
UserRepresentation userRepresentation = getUserByUsername(client, realmId, username);
-
client.realm(realmId).users().get(userRepresentation.getId()).leaveGroup(groupId);
return true;
@@ -1825,20 +1456,12 @@ public class KeycloakClient {
String msg = "Error occurred while remove user from group, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
}
public boolean configureAgentClient(String realmId, String clientId, long accessTokenLifeTime) {
- Keycloak client = null;
- try {
-
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
ClientRepresentation representation = client.realm(realmId).clients().findByClientId(clientId).get(0);
if (representation != null) {
@@ -1851,60 +1474,35 @@ public class KeycloakClient {
client.realm(realmId).clients().get(representation.getId()).update(representation);
return true;
-
}
-
return false;
+
} catch (Exception ex) {
String msg = "Error occurred while remove user from group, reason: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
-
}
public boolean isValidEndUser(String realmId, String username, String accessToken) {
- Keycloak client = null;
- try {
-
- client = getClient(iamServerURL, realmId, accessToken);
-
+ try (Keycloak client = getClient(iamServerURL, realmId, accessToken)) {
return isValidEndUser(client, realmId, username);
} catch (Exception ex) {
String msg = "Error occurred end user validity: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
-
-
}
public boolean isValidEndUser(String realmId, String username) {
- Keycloak client = null;
- try {
- client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword);
-
+ try (Keycloak client = getClient(iamServerURL, superAdminRealmID, superAdminUserName, superAdminPassword)) {
return isValidEndUser(client, realmId, username);
} catch (Exception ex) {
String msg = "Error occurred end user validity: " + ex.getMessage();
LOGGER.error(msg, ex);
throw new RuntimeException(msg, ex);
- } finally {
- if (client != null) {
- client.close();
- }
}
-
-
}
@@ -1945,18 +1543,7 @@ public class KeycloakClient {
adminRole.setName("admin");
adminRole.setDescription("Admin role for PGA users");
defaultRoles.add(adminRole);
-// RoleRepresentation gatewayUserRole = new RoleRepresentation();
-// gatewayUserRole.setName("gateway-user");
-// gatewayUserRole.setDescription("default role for PGA users");
-// defaultRoles.add(gatewayUserRole);
-// RoleRepresentation pendingUserRole = new RoleRepresentation();
-// pendingUserRole.setName("user-pending");
-// pendingUserRole.setDescription("role for newly registered PGA users");
-// defaultRoles.add(pendingUserRole);
-// RoleRepresentation gatewayProviderRole = new RoleRepresentation();
-// gatewayProviderRole.setName("gateway-provider");
-// gatewayProviderRole.setDescription("role for gateway providers in the super-admin PGA");
-// defaultRoles.add(gatewayProviderRole);
+
RolesRepresentation rolesRepresentation = new RolesRepresentation();
rolesRepresentation.setRealm(defaultRoles);
realmDetails.setRoles(rolesRepresentation);
@@ -2128,5 +1715,4 @@ public class KeycloakClient {
return path.substring(path.lastIndexOf('/') + 1);
}
-
}
diff --git a/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/auth/KeycloakAuthClient.java b/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/auth/KeycloakAuthClient.java
index 7f157748c..7c1ca4dea 100644
--- a/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/auth/KeycloakAuthClient.java
+++ b/custos-services/custos-federated-services-clients/src/main/java/org/apache/custos/federated/services/clients/keycloak/auth/KeycloakAuthClient.java
@@ -55,7 +55,6 @@ import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
@@ -68,21 +67,18 @@ import java.util.Map;
@Component
public class KeycloakAuthClient {
- @Value("${iam.server.url:https://keycloak.custos.scigap.org:31000/auth/}")
- private String idpServerURL;
-
-
private static final Logger LOGGER = LoggerFactory.getLogger(KeycloakAuthClient.class);
+ @Value("${iam.server.url:https://keycloak.custos.scigap.org:31000/auth/}")
+ private String idpServerURL;
@EventListener(ApplicationReadyEvent.class)
- public void initializeSecurity() throws CertificateException, NoSuchAlgorithmException,
- KeyStoreException, KeyManagementException, IOException {
+ public void initializeSecurity() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
try {
LOGGER.debug("initializing security requirements");
KeycloakUtils.initializeTrustStoreManager();
} catch (Exception ex) {
- LOGGER.error("Keycloak Authclient initialization failed " + ex.getMessage());
+ LOGGER.error("Keycloak Authclient initialization failed ", ex);
throw ex;
}
}
@@ -92,37 +88,26 @@ public class KeycloakAuthClient {
try {
Map<String, Object> clientCredentials = new HashMap<>();
clientCredentials.put("secret", clientSecret);
- SSLContextBuilder builder = new SSLContextBuilder();
+ SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
-
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
- Configuration configuration = new Configuration(idpServerURL,
- realmId, clientId, clientCredentials, httpclient);
+ Configuration configuration = new Configuration(idpServerURL, realmId, clientId, clientCredentials, httpclient);
AuthzClient keycloakClient = AuthzClient.create(configuration);
-
AccessTokenResponse accessToken = keycloakClient.obtainAccessToken(username, password);
-
- if (accessToken != null) {
- return accessToken.getToken();
- }
-
- return null;
+ return accessToken != null ? accessToken.getToken() : null;
} catch (Exception e) {
- String msg = "Error occurred while authenticating " + e;
- LOGGER.error(msg);
- throw new RuntimeException(msg, e);
+ LOGGER.error("Error occurred while authenticating", e);
+ throw new RuntimeException("Error occurred while authenticating", e);
}
-
}
-
public boolean isUserAuthenticated(String username, String realmId, String accessToken) {
try {
User userInfo = getUserInfo(realmId, accessToken);
@@ -135,116 +120,99 @@ public class KeycloakAuthClient {
LOGGER.error(msg, e);
throw new RuntimeException(msg, e);
}
-
}
-
public User getUser(String accessToken, String realmId) {
try {
return getUserInfo(realmId, accessToken);
} catch (Exception e) {
- String msg = "Error occurred while retrieving user info " + e;
- LOGGER.error(msg);
- throw new RuntimeException(msg, e);
+ LOGGER.error("Error occurred while retrieving user info", e);
+ throw new RuntimeException("Error occurred while retrieving user info", e);
}
-
}
- public String getUserManagementServiceAccountAccessToken(String clientId, String clientSecret,
- String realmId) {
+ public String getUserManagementServiceAccountAccessToken(String clientId, String clientSecret, String realmId) {
try {
String tokenURL = getTokenEndpoint(realmId);
LOGGER.info("token url:" + tokenURL);
JSONObject clientCredentials = getClientCredentials(tokenURL, clientId, clientSecret);
return clientCredentials.getString("access_token");
} catch (Exception e) {
- String msg = "Error occurred while retrieving service account access token " + e;
- LOGGER.error(msg);
- throw new RuntimeException(msg, e);
+ LOGGER.error("Error occurred while retrieving service account access token", e);
+ throw new RuntimeException("Error occurred while retrieving service account access token", e);
}
}
- public JSONObject getAccessToken(String clientId, String clientSecret, String realmId,
- String code, String redirectUri) throws JSONException {
+ public JSONObject getAccessToken(String clientId, String clientSecret, String realmId, String code,
+ String redirectUri) throws JSONException {
try {
String tokenURL = getTokenEndpoint(realmId);
return getTokenFromOAuthCode(tokenURL, clientId, clientSecret, code, redirectUri);
} catch (Exception e) {
- String msg = "Error occurred while retrieving access token " + e;
- LOGGER.error(msg);
- throw new RuntimeException(msg, e);
+ LOGGER.error("Error occurred while retrieving the access token", e);
+ throw new RuntimeException("Error occurred while retrieving the access token", e);
}
}
public JSONObject getAccessTokenFromPasswordGrantType(String clientId, String clientSecret, String realmId,
- String username, String password) throws JSONException {
+ String username, String password) {
try {
String tokenURL = getTokenEndpoint(realmId);
return getTokenFromPasswordType(tokenURL, clientId, clientSecret, username, password);
} catch (Exception e) {
- String msg = "Error occurred while retrieving access token " + e;
- LOGGER.error(msg);
- throw new RuntimeException(msg, e);
+ LOGGER.error("Error occurred while retrieving the access token", e);
+ throw new RuntimeException("Error occurred while retrieving the access token", e);
}
-
}
- public JSONObject getAccessTokenFromRefreshTokenGrantType(String clientId, String clientSecret, String realmId,
- String refreshToken) throws JSONException {
+ public JSONObject getAccessTokenFromRefreshTokenGrantType(String clientId, String clientSecret, String realmId, String refreshToken) {
try {
String tokenURL = getTokenEndpoint(realmId);
return getTokenFromRefreshToken(tokenURL, clientId, clientSecret, refreshToken);
} catch (Exception e) {
- String msg = "Error occurred while retrieving access token " + e;
- LOGGER.error(msg);
+ String msg = "Error occurred while retrieving the access token";
+ LOGGER.error(msg, e);
throw new RuntimeException(msg, e);
}
-
}
- public JSONObject getAccessTokenFromClientCredentialsGrantType(String clientId, String clientSecret, String realmId
- ) throws JSONException {
+ public JSONObject getAccessTokenFromClientCredentialsGrantType(String clientId, String clientSecret, String realmId) {
try {
String tokenURL = getTokenEndpoint(realmId);
return getClientCredentials(tokenURL, clientId, clientSecret);
} catch (Exception e) {
- String msg = "Error occurred while retrieving access token " + e;
- LOGGER.error(msg);
- throw new RuntimeException(msg, e);
+ LOGGER.error("Error occurred while retrieving the access token", e);
+ throw new RuntimeException("Error occurred while retrieving the access token", e);
}
-
}
- public JSONObject getJWTVerificationCerts(String clientId, String clientSecret, String realmId
- ) throws JSONException {
+ public JSONObject getJWTVerificationCerts(String clientId, String clientSecret, String realmId) {
try {
String tokenURL = getJwksUri(realmId);
return getJWKSResponse(tokenURL, clientId, clientSecret);
} catch (Exception e) {
- String msg = "Error occurred while retrieving access token " + e;
- LOGGER.error(msg);
- throw new RuntimeException(msg, e);
+ LOGGER.error("Error occurred while retrieving the access token", e);
+ throw new RuntimeException("Error occurred while retrieving the access token", e);
}
}
- public boolean revokeRefreshToken(String clientId, String clientSecret, String realmId, String refreshToken) throws JSONException {
+ public boolean revokeRefreshToken(String clientId, String clientSecret, String realmId, String refreshToken) {
try {
String tokenURL = getEndSessionEndpoint(realmId);
endSession(tokenURL, clientId, clientSecret, refreshToken);
return true;
+
} catch (Exception e) {
- String msg = "Error occurred while revoking refresh token " + e;
- LOGGER.error(msg, e);
- throw new RuntimeException(msg, e);
+ LOGGER.error("Error occurred while revoking the refresh token", e);
+ throw new RuntimeException("Error occurred while revoking the refresh token", e);
}
-
}
private String getTokenEndpoint(String gatewayId) throws Exception {
@@ -273,20 +241,7 @@ public class KeycloakAuthClient {
public JSONObject getOIDCConfiguration(String tenantId, String clientId) throws Exception {
String openIdConnectUrl = getOpenIDConfigurationUrl(tenantId);
- JSONObject openIdConnectConfig = new JSONObject(getFromUrl(openIdConnectUrl, null));
-
- // openIdConnectConfig.put("introspection_endpoint", introEndpoint);
- // openIdConnectConfig.put("issuer", issuer);
-// openIdConnectConfig.put("custos_token_endpoint", tokenEndpoint);
- // openIdConnectConfig.put("end_session_endpoint", sessionEndpoint);
- // openIdConnectConfig.put("token_introspection_endpoint", introEndpoint);
-// openIdConnectConfig.put("custos_userinfo_endpoint", userInfoEndpoint);
- // openIdConnectConfig.put("jwks_uri", jwksUri);
-// openIdConnectConfig.put("registration_endpoint", registrationEndpoint);
- // openIdConnectConfig.remove("check_session_iframe");
-
-
- return openIdConnectConfig;
+ return new JSONObject(getFromUrl(openIdConnectUrl, null));
}
private User getUserInfo(String realmId, String token) throws Exception {
@@ -302,7 +257,6 @@ public class KeycloakAuthClient {
userInfo.getString("preferred_username"));
}
-
private String getOpenIDConfigurationUrl(String realm) {
LOGGER.debug("Connecting to " + idpServerURL);
return idpServerURL + "realms/" + realm + "/.well-known/openid-configuration";
@@ -318,23 +272,18 @@ public class KeycloakAuthClient {
String bearerAuth = "Bearer " + token;
conn.setRequestProperty("Authorization", bearerAuth);
}
- BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- try {
+ try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
- } finally {
- rd.close();
}
+
return result.toString();
}
private JSONObject getClientCredentials(String tokenURL, String clientId, String clientSecret) {
-
- CloseableHttpClient httpClient = HttpClients.createSystem();
-
HttpPost httpPost = new HttpPost(tokenURL);
String encoded = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
@@ -342,31 +291,19 @@ public class KeycloakAuthClient {
formParams.add(new BasicNameValuePair("grant_type", "client_credentials"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
httpPost.setEntity(entity);
- try {
- CloseableHttpResponse response = httpClient.execute(httpPost);
- try {
- String responseBody = EntityUtils.toString(response.getEntity());
- JSONObject tokenInfo = new JSONObject(responseBody);
- return tokenInfo;
- } finally {
- response.close();
- }
+
+ try (CloseableHttpClient httpClient = HttpClients.createSystem();
+ CloseableHttpResponse response = httpClient.execute(httpPost)) {
+ String responseBody = EntityUtils.toString(response.getEntity());
+ return new JSONObject(responseBody);
+
} catch (IOException | JSONException e) {
+ LOGGER.error("Error while extracting the Client credentials", e);
throw new RuntimeException(e);
- } finally {
- try {
- httpClient.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
}
}
- private JSONObject getTokenFromOAuthCode(String tokenURL, String clientId, String clientSecret, String code,
- String redirect_uri) {
-
- CloseableHttpClient httpClient = HttpClients.createSystem();
-
+ private JSONObject getTokenFromOAuthCode(String tokenURL, String clientId, String clientSecret, String code, String redirect_uri) {
HttpPost httpPost = new HttpPost(tokenURL);
String encoded = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
@@ -378,30 +315,19 @@ public class KeycloakAuthClient {
formParams.add(new BasicNameValuePair("client_secret", clientSecret));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
httpPost.setEntity(entity);
- try {
- CloseableHttpResponse response = httpClient.execute(httpPost);
- try {
- String responseBody = EntityUtils.toString(response.getEntity());
- JSONObject tokenInfo = new JSONObject(responseBody);
- return tokenInfo;
- } finally {
- response.close();
- }
+
+ try (CloseableHttpClient httpClient = HttpClients.createSystem();
+ CloseableHttpResponse response = httpClient.execute(httpPost)) {
+ String responseBody = EntityUtils.toString(response.getEntity());
+ return new JSONObject(responseBody);
+
} catch (IOException | JSONException e) {
- throw new RuntimeException(e);
- } finally {
- try {
- httpClient.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
+ LOGGER.error("Error while extracting the token from the OAuth Code", e);
+ throw new RuntimeException("Error while extracting the token from the OAuth Code", e);
}
}
private void endSession(String endSessionEndpoint, String clientId, String clientSecret, String refreshToken) {
-
- CloseableHttpClient httpClient = HttpClients.createSystem();
-
HttpPost httpPost = new HttpPost(endSessionEndpoint);
String encoded = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
@@ -411,53 +337,37 @@ public class KeycloakAuthClient {
formParams.add(new BasicNameValuePair("client_secret", clientSecret));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
httpPost.setEntity(entity);
- try {
- CloseableHttpResponse response = httpClient.execute(httpPost);
- response.close();
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- try {
- httpClient.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
+
+ try (CloseableHttpClient httpClient = HttpClients.createSystem();
+ CloseableHttpResponse response = httpClient.execute(httpPost)) {
+ if (response.getStatusLine().getStatusCode() != 200) {
+ throw new IllegalStateException("Failed to end session properly: " + EntityUtils.toString(response.getEntity()));
}
+ } catch (Exception e) {
+ LOGGER.error("Error while ending the session", e);
+ throw new RuntimeException("Error while ending the session", e);
}
}
private JSONObject getJWKSResponse(String jwksUri, String clientId, String clientSecret) {
-
- CloseableHttpClient httpClient = HttpClients.createSystem();
-
HttpGet httpPost = new HttpGet(jwksUri);
String encoded = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
- try {
- CloseableHttpResponse response = httpClient.execute(httpPost);
- try {
- String responseBody = EntityUtils.toString(response.getEntity());
- JSONObject tokenInfo = new JSONObject(responseBody);
- return tokenInfo;
- } finally {
- response.close();
- }
+
+ try (CloseableHttpClient httpClient = HttpClients.createSystem();
+ CloseableHttpResponse response = httpClient.execute(httpPost)) {
+
+ String responseBody = EntityUtils.toString(response.getEntity());
+ return new JSONObject(responseBody);
+
} catch (IOException | JSONException e) {
- throw new RuntimeException(e);
- } finally {
- try {
- httpClient.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
+ LOGGER.error("Error while retrieving the JWKS response", e);
+ throw new RuntimeException("Error while retrieving the JWKS response", e);
}
}
- private JSONObject getTokenFromPasswordType(String tokenURL, String clientId, String clientSecret, String username,
- String password) {
-
- CloseableHttpClient httpClient = HttpClients.createSystem();
-
+ private JSONObject getTokenFromPasswordType(String tokenURL, String clientId, String clientSecret, String username, String password) {
HttpPost httpPost = new HttpPost(tokenURL);
String encoded = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
@@ -470,31 +380,21 @@ public class KeycloakAuthClient {
formParams.add(new BasicNameValuePair("scope", "openid"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
httpPost.setEntity(entity);
- try {
- CloseableHttpResponse response = httpClient.execute(httpPost);
- try {
- String responseBody = EntityUtils.toString(response.getEntity());
- JSONObject tokenInfo = new JSONObject(responseBody);
- return tokenInfo;
- } finally {
- response.close();
- }
+
+ try (CloseableHttpClient httpClient = HttpClients.createSystem();
+ CloseableHttpResponse response = httpClient.execute(httpPost)) {
+
+ String responseBody = EntityUtils.toString(response.getEntity());
+ return new JSONObject(responseBody);
+
} catch (IOException | JSONException e) {
- throw new RuntimeException(e);
- } finally {
- try {
- httpClient.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
+ LOGGER.error("Error while extracting the token from the username/password", e);
+ throw new RuntimeException("Error while extracting the token from the username/password", e);
}
}
private JSONObject getTokenFromRefreshToken(String tokenURL, String clientId, String clientSecret, String refreshToken) {
-
- CloseableHttpClient httpClient = HttpClients.createSystem();
-
HttpPost httpPost = new HttpPost(tokenURL);
String encoded = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
@@ -506,25 +406,15 @@ public class KeycloakAuthClient {
formParams.add(new BasicNameValuePair("scope", "openid"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
httpPost.setEntity(entity);
- try {
- CloseableHttpResponse response = httpClient.execute(httpPost);
- try {
- String responseBody = EntityUtils.toString(response.getEntity());
- JSONObject tokenInfo = new JSONObject(responseBody);
- return tokenInfo;
- } finally {
- response.close();
- }
+ try (CloseableHttpClient httpClient = HttpClients.createSystem();
+ CloseableHttpResponse response = httpClient.execute(httpPost)) {
+
+ String responseBody = EntityUtils.toString(response.getEntity());
+ return new JSONObject(responseBody);
+
} catch (IOException | JSONException e) {
- throw new RuntimeException(e);
- } finally {
- try {
- httpClient.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
+ LOGGER.error("Error while extracting the token from the refresh token", e);
+ throw new RuntimeException("Error while extracting the token from the refresh token", e);
}
}
-
-
}