hello-world-service/src/main/java/org/gcube/service/helloworld/services/KeycloakTestService.java

167 lines
6.1 KiB
Java

package org.gcube.service.helloworld.services;
import java.util.ArrayList;
import java.util.List;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.service.helloworld.HelloWorldManager;
import org.gcube.service.helloworld.serializers.CustomSerializator;
import org.gcube.service.helloworld.utils.InfrastrctureServiceClient;
import org.gcube.smartgears.annotations.ManagedBy;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.ClientsResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.RoleResource;
import org.keycloak.admin.client.resource.RolesResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.core.Response;
/**
* service example that shows how to query IS and how to access Keycloak
* @author Alfredo Oliviero (ISTI - CNR)
*/
@ManagedBy(HelloWorldManager.class)
@Path("")
public class KeycloakTestService {
private final static Logger logger = LoggerFactory.getLogger(KeycloakTestService.class);
private final static String RUNTIME_RESOURCE_NAME = "IAM";
private final static String CATEGORY = "Service";
private final static String REALM_D4S = "d4science";
private final static boolean IS_ROOT_SERVICE = true;
public static String getClientIdContext(String context) {
return context.replace("/", "%2F");
}
@GET
@Path("/keycloak")
@Produces({ "application/json;charset=UTF-8", "application/vnd.api+json" })
public Response testKeycloak(
@QueryParam("role-name") @DefaultValue("Member") String roleName) {
String client_contenxt = "/gcube";
List<String> usernames = new ArrayList<String>();
try {
ServiceEndpoint.AccessPoint accessPoint = InfrastrctureServiceClient.getAccessPointFromIS(
RUNTIME_RESOURCE_NAME,
CATEGORY,
REALM_D4S,
IS_ROOT_SERVICE);
if (accessPoint == null) {
String error_log = "Unable to retrieve service endpoint " + REALM_D4S;
logger.error(error_log);
throw new NotFoundException(error_log);
}
String keycloakURL = accessPoint.address();
String realm = accessPoint.name();
String clientId = accessPoint.username();
String clientSecret = StringEncrypter.getEncrypter().decrypt(accessPoint.password());
Keycloak kclient = KeycloakBuilder.builder()
.serverUrl(keycloakURL)
.realm(realm)
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId(clientId) //
.clientSecret(clientSecret).build();
List<UserRepresentation> users = searchByRole(kclient, realm, client_contenxt, roleName);
if (users != null) {
for (UserRepresentation user : users) {
usernames.add(user.getUsername());
}
}
// responseBean.setResult(usernames);
// responseBean.setSuccess(true);
ObjectMapper objectMapper = CustomSerializator.getSerializer();
String jsonData = objectMapper.writeValueAsString(usernames);
return Response.ok(jsonData).build();
} catch (JsonProcessingException e) {
e.printStackTrace();
return Response.serverError().build();
} catch (Exception e) {
e.printStackTrace();
return Response.serverError().build();
}
// return Response.status(status).entity(responseBean).build();
}
private static List<UserRepresentation> searchByRole(Keycloak kclient, String krealm, String clientIdContext,
String roleName) {
clientIdContext = getClientIdContext(clientIdContext);
logger.info("Searching by role: {}", roleName);
RealmResource realm_resource = kclient.realm(krealm);
logger.info("{} realm_resource: {}", krealm, realm_resource);
ClientsResource clients_resource = realm_resource.clients();
logger.info("clients_resource {}", clients_resource);
for (ClientRepresentation c : clients_resource.findAll()) {
logger.info("listing all clients, found {} - {}", c.getClientId(), c.getId());
}
List<ClientRepresentation> clients_repr = clients_resource.findByClientId(clientIdContext);
logger.info("{} clients_repr: {}", clientIdContext, clients_repr);
String client_id = "";
for (ClientRepresentation c_repr : clients_repr) {
logger.info("searching {}, found client {} - {}", clientIdContext, c_repr.getClientId(), c_repr.getId());
client_id = c_repr.getId();
}
ClientResource client_resource = clients_resource.get(client_id);
logger.info("client_resource {}", client_resource);
RolesResource roles_resource = client_resource.roles();
for (RoleRepresentation r : roles_resource.list()) {
logger.info("found role {}", r);
}
logger.info("roles_resource {}", roles_resource);
RoleResource role_resource = roles_resource.get(roleName);
logger.info("{} role_resource: {}", roleName, roles_resource);
List<UserRepresentation> users_repr = role_resource.getUserMembers(0, 100000);
for (UserRepresentation u : users_repr) {
logger.info("found user {}", u);
}
return users_repr;
}
}