215 lines
8.8 KiB
Java
215 lines
8.8 KiB
Java
package org.gcube.service.idm.controller;
|
|
|
|
import java.rmi.ServerException;
|
|
import java.util.ArrayList;
|
|
import java.util.Arrays;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
import org.gcube.service.idm.keycloack.KkClientFactory;
|
|
import org.keycloak.admin.client.CreatedResponseUtil;
|
|
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.UserResource;
|
|
import org.keycloak.admin.client.resource.UsersResource;
|
|
import org.keycloak.representations.idm.ClientRepresentation;
|
|
import org.keycloak.representations.idm.CredentialRepresentation;
|
|
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
|
|
import org.keycloak.representations.idm.RoleRepresentation;
|
|
import org.keycloak.representations.idm.UserRepresentation;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
import jakarta.ws.rs.NotFoundException;
|
|
import jakarta.ws.rs.WebApplicationException;
|
|
|
|
public class AdminKeycloakController {
|
|
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AdminKeycloakController.class);
|
|
|
|
// TODO: Using Keycloak Admin Client to create user with roles (Realm and Client
|
|
// level)
|
|
// https://gist.github.com/thomasdarimont/c4e739c5a319cf78a4cff3b87173a84b
|
|
public static UserRepresentation createUser(String username, String email, String password, String firstName,
|
|
String lastName, Map<String, List<String>> attributes, List<String> roles)
|
|
throws WebApplicationException, ServerException {
|
|
UserRepresentation newUser = new UserRepresentation();
|
|
newUser.setEnabled(true);
|
|
newUser.setUsername(username);
|
|
newUser.setFirstName(firstName);
|
|
newUser.setLastName(lastName);
|
|
newUser.setEmail(email);
|
|
if (attributes != null) {
|
|
// user.setAttributes(Collections.singletonMap("origin",
|
|
// Arrays.asList("demo")));
|
|
newUser.setAttributes(attributes);
|
|
}
|
|
RealmResource realmResource = KkClientFactory.getSingleton().getKKRealm();
|
|
UsersResource usersRessource = realmResource.users();
|
|
|
|
// Response response = usersRessource.create(user);
|
|
// System.out.printf("Repsonse: %s %s%n", response.getStatus(),
|
|
// response.getStatusInfo());
|
|
// System.out.println(response.getLocation());
|
|
// String userId = CreatedResponseUtil.getCreatedId(response);
|
|
|
|
String newUserId = null;
|
|
|
|
// throws exception if creationResponse is failed
|
|
try {
|
|
newUserId = CreatedResponseUtil.getCreatedId(usersRessource.create(newUser));
|
|
|
|
} catch (WebApplicationException e) {
|
|
logger.error("error creating user {} - {}", newUser, e.getMessage());
|
|
|
|
e.printStackTrace();
|
|
throw new WebApplicationException(e.getMessage());
|
|
}
|
|
|
|
logger.info("created user {}", newUser);
|
|
|
|
CredentialRepresentation passwordCred = new CredentialRepresentation();
|
|
passwordCred.setTemporary(false);
|
|
passwordCred.setType(CredentialRepresentation.PASSWORD);
|
|
passwordCred.setValue(password);
|
|
|
|
UserResource userResource = usersRessource.get(newUserId);
|
|
userResource.resetPassword(passwordCred);
|
|
|
|
// // Get realm role "tester" (requires view-realm role)
|
|
RoleRepresentation testerRealmRole = realmResource.roles()//
|
|
.get("tester").toRepresentation();
|
|
//
|
|
// // Assign realm role tester to user
|
|
userResource.roles().realmLevel() //
|
|
.add(Arrays.asList(testerRealmRole));
|
|
//
|
|
ClientResource client = KkClientFactory.getSingleton().getKKClient();
|
|
|
|
if (roles != null) {
|
|
List<RoleRepresentation> listRolesRepr = new ArrayList<>();
|
|
|
|
roles.forEach(role -> listRolesRepr.add(client.roles().get(role).toRepresentation()));
|
|
//
|
|
// // // Assign client level role to user
|
|
// userResource.roles() //
|
|
// .clientLevel(client.get.getId()).add(roles);
|
|
}
|
|
return userResource.toRepresentation();
|
|
}
|
|
|
|
// https://gist.github.com/thomasdarimont/c4e739c5a319cf78a4cff3b87173a84b
|
|
public static ClientRepresentation createClient(
|
|
String id,
|
|
String clientId,
|
|
String name,
|
|
String description,
|
|
String rootUrl,
|
|
String adminUrl,
|
|
String baseUrl,
|
|
Boolean surrogateAuthRequired,
|
|
Boolean enabled,
|
|
Boolean alwaysDisplayInConsole,
|
|
String clientAuthenticatorType,
|
|
String secret,
|
|
String registrationAccessToken,
|
|
// @Deprecated String[] defaultRoles,
|
|
List<String> redirectUris,
|
|
List<String> webOrigins,
|
|
Integer notBefore,
|
|
Boolean bearerOnly,
|
|
Boolean consentRequired,
|
|
Boolean standardFlowEnabled,
|
|
Boolean implicitFlowEnabled,
|
|
Boolean directAccessGrantsEnabled,
|
|
Boolean serviceAccountsEnabled,
|
|
// Boolean oauth2DeviceAuthorizationGrantEnabled, no getter/setter
|
|
Boolean authorizationServicesEnabled,
|
|
// @Deprecated Boolean directGrantsOnly,
|
|
Boolean publicClient,
|
|
Boolean frontchannelLogout,
|
|
String protocol,
|
|
Map<String, String> attributes,
|
|
Map<String, String> authenticationFlowBindingOverrides,
|
|
Boolean fullScopeAllowed,
|
|
Integer nodeReRegistrationTimeout,
|
|
Map<String, Integer> registeredNodes,
|
|
List<ProtocolMapperRepresentation> protocolMappers,
|
|
// @Deprecated String clientTemplate,
|
|
// @Deprecated private Boolean useTemplateConfig,
|
|
// @Deprecated private Boolean useTemplateScope,
|
|
// @Deprecated private Boolean useTemplateMappers,
|
|
List<String> defaultClientScopes,
|
|
List<String> optionalClientScopes,
|
|
// private ResourceServerRepresentation authorizationSettings,
|
|
// private Map<String, Boolean> access,
|
|
String origin
|
|
|
|
) {
|
|
ClientRepresentation newClient = new ClientRepresentation();
|
|
|
|
newClient.setId(id);
|
|
newClient.setClientId(clientId);
|
|
newClient.setName(name);
|
|
newClient.setDescription(description);
|
|
newClient.setRootUrl(rootUrl);
|
|
newClient.setAdminUrl(adminUrl);
|
|
newClient.setBaseUrl(baseUrl);
|
|
newClient.setSurrogateAuthRequired(surrogateAuthRequired);
|
|
newClient.setEnabled(enabled);
|
|
newClient.setAlwaysDisplayInConsole(alwaysDisplayInConsole);
|
|
newClient.setClientAuthenticatorType(clientAuthenticatorType);
|
|
newClient.setSecret(secret);
|
|
newClient.setRegistrationAccessToken(registrationAccessToken);
|
|
|
|
newClient.setRedirectUris(redirectUris);
|
|
newClient.setWebOrigins(webOrigins);
|
|
newClient.setNotBefore(notBefore);
|
|
newClient.setConsentRequired(consentRequired);
|
|
newClient.setStandardFlowEnabled(standardFlowEnabled);
|
|
newClient.setImplicitFlowEnabled(implicitFlowEnabled);
|
|
newClient.setDirectAccessGrantsEnabled(directAccessGrantsEnabled);
|
|
newClient.setServiceAccountsEnabled(serviceAccountsEnabled);
|
|
|
|
newClient.setAuthorizationServicesEnabled(authorizationServicesEnabled);
|
|
|
|
newClient.setPublicClient(publicClient);
|
|
newClient.setFrontchannelLogout(frontchannelLogout);
|
|
newClient.setProtocol(protocol);
|
|
newClient.setAttributes(attributes);
|
|
newClient.setAuthenticationFlowBindingOverrides(authenticationFlowBindingOverrides);
|
|
newClient.setFullScopeAllowed(fullScopeAllowed);
|
|
newClient.setNodeReRegistrationTimeout(nodeReRegistrationTimeout);
|
|
newClient.setRegisteredNodes(registeredNodes);
|
|
newClient.setProtocolMappers(protocolMappers);
|
|
|
|
newClient.setDefaultClientScopes(defaultClientScopes);
|
|
newClient.setOptionalClientScopes(optionalClientScopes);
|
|
newClient.setOrigin(origin);
|
|
|
|
return createClient(newClient);
|
|
}
|
|
|
|
public static ClientRepresentation createClient(ClientRepresentation newClient) {
|
|
RealmResource realmResource = KkClientFactory.getSingleton().getKKRealm();
|
|
ClientsResource clientsResource = realmResource.clients();
|
|
|
|
String newClientId = null;
|
|
|
|
// throws exception if creationResponse is failed
|
|
try {
|
|
newClientId = CreatedResponseUtil.getCreatedId(clientsResource.create(newClient));
|
|
|
|
} catch (WebApplicationException e) {
|
|
logger.error("error creating client {} - {}", newClient, e.getMessage());
|
|
|
|
e.printStackTrace();
|
|
throw new WebApplicationException(e.getMessage());
|
|
}
|
|
|
|
logger.info("created user {}", newClient);
|
|
ClientResource client = clientsResource.get(newClientId);
|
|
return client.toRepresentation();
|
|
}
|
|
|
|
}
|