Keycloak - Create Realms/Users/Groups Programmatically

KeyCloak - Create Realms/Users/Groups Programmatically?

I found some info around the KeyCloak Java Admin Client. This gist has lots of useful examples showing how to managed users, realms, etc.

Keycloak: how to programmatically add new subgroups with associated users?

You can create groups and subgroups under it , Here is the sample code to create subgroups using Admin Client. You can also associate users to those groups

 public void addSubgroups()  {
RealmResource realm =keycloak.realm("myrealm");
GroupRepresentation topGroup = new GroupRepresentation();
topGroup.setName("group");
topGroup = createGroup(realm, topGroup);

createSubGroup(realm,topGroup.getId(),"subgroup1");
createSubGroup(realm,topGroup.getId(),"subgroup2");
}

private void createSubGroup(RealmResource realm, String parentGroupId, String subGroupName) {
GroupRepresentation subgroup = new GroupRepresentation();
subgroup.setName(subGroupName);
try (Response response = realm.groups().group(parentGroupId).subGroup(subgroup)){
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
System.out.println("Created Subgroup : " + subGroupName );
} else {
logger.severe("Error Creating Subgroup : " + subGroupName + ", Error Message : " + getErrorMessage(response));
}
}
}

private GroupRepresentation createGroup(RealmResource realm, GroupRepresentation group) {
try (Response response = realm.groups().add(group)) {
String groupId = getCreatedId(response);
group.setId(groupId);
return group;
}
}

Assign Roles programmatically to Groups with Keycloak API

If you have created role already then you can associate the role with group with the following code.

 RoleRepresentation grouprole = realm.roles().get("grouprole").toRepresentation();

List<RoleRepresentation> roles = new LinkedList<>();
roles.add(grouprole);
realm.groups().group(myGroup.getId()).roles().realmLevel().add(roles);

here "grouprole" role is associated to "myGroup" group

How to create keycloak client role programmatically and assign to user

Here is a solution to your request (not very beautiful, but it works):

// Get keycloak client
Keycloak kc = Keycloak.getInstance("http://localhost:8080/auth",
"master", "admin", "admin", "admin-cli");

// Create the role
RoleRepresentation clientRoleRepresentation = new RoleRepresentation();
clientRoleRepresentation.setName("client_role");
clientRoleRepresentation.setClientRole(true);
kc.realm("RealmID").clients().findByClientId("ClientID").forEach(clientRepresentation ->
kc.realm("RealmID").clients().get(clientRepresentation.getId()).roles().create(clientRoleRepresentation)
);

// Create the user
UserRepresentation user = new UserRepresentation();
user.setUsername("test");
user.setEnabled(true);
Response response = kc.realm("RealmID").users().create(user);
String userId = getCreatedId(response);

// Assign role to the user
kc.realm("RealmID").clients().findByClientId("ClientID").forEach(clientRepresentation -> {
RoleRepresentation savedRoleRepresentation = kc.realm("RealmID").clients()
.get(clientRepresentation.getId()).roles().get("client_role").toRepresentation();
kc.realm("RealmID").users().get(userId).roles().clientLevel(clientRepresentation.getId())
.add(asList(savedRoleRepresentation));
});

// Update credentials to make sure, that the user can log in
UserResource userResource = kc.realm("RealmID").users().get(userId);
userResource.resetPassword(credential);

With the help method:

private String getCreatedId(Response response) {
URI location = response.getLocation();
if (!response.getStatusInfo().equals(Response.Status.CREATED)) {
Response.StatusType statusInfo = response.getStatusInfo();
throw new WebApplicationException("Create method returned status " +
statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); expected status: Created (201)", response);
}
if (location == null) {
return null;
}
String path = location.getPath();
return path.substring(path.lastIndexOf('/') + 1);
}

Keycloak - Add/Remove Realm role from a user using APIcalls

Endpoints are

Get Role Mappings:

GET /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Add Role Mappings:

POST /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Delete Role Mappings:

DELETE /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm

Example Add Role

You have a role e.g. named testrole with the id dc5572a5-b7e0-4c4b-b841-dc88108df70f (you see it in the url when you have opened the keycloak admin GUI, or you fetch it with some other RestAPI Request)

Now we have a Request of Type POST to the endpoint /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm with a body of type application/json and the following body-value

[
{
"id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
"name" : "testrole"
}
]

After successful execution you get a response with HTTP-Code 204 => The testrole - role mapping is applied to this user

Example Curl Request

curl --request POST \
--url http://localhost/auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm \
--header 'authorization: Bearer eyJh......h3RLw' \
--header 'content-type: application/json' \
--data '[
{
"id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
"name" : "testrole"
}
]'

If you want to delete it again, just send the same request (same body) but with the HTTP-method DELETE instead of POST

Please let me now if this solved your issue



Related Topics



Leave a reply



Submit