currently I try around with the Keycloak API and the Java client. At the moment I struggle to assign Roles to Groups programmatically. Unfortunately the documentation is not very elaborate at this point.
Here my example code:
@Test
public void testPushGroupWithRealmRoles() throws IOException {
GroupRepresentation group = new GroupRepresentation();
group.setName("JUnit Test Group realm roles");
String editRoleName = "junit_edit";
String deleteRoleName = "junit_delete";
RoleRepresentation editRole = getRealmRole(editRoleName);
if (editRole == null) {
editRole = new RoleRepresentation(editRoleName, "is allowed to edit", false);
getKeycloak().realm(clientConfig.getRealm()).roles().create(editRole);
}
RoleRepresentation deleteRole = getRealmRole(deleteRoleName);
if (deleteRole == null) {
deleteRole = new RoleRepresentation(deleteRoleName, "is allowed to delete", false);
getKeycloak().realm(clientConfig.getRealm()).roles().create(deleteRole);
}
group.setRealmRoles(Arrays.asList(editRole.getName(), deleteRole.getName()));
GroupResource existingGroup = getGroupRepresentation(group.getName());
if(existingGroup != null){
existingGroup.update(group);
} else{
getKeycloak().realm(clientConfig.getRealm()).groups().add(group);
}
}
The Group is created if not exists, the Roles are created if they don't exist but the assignment
group.setRealmRoles(Arrays.asList(editRole.getName(), deleteRole.getName()));
What needs to be given as arguments in the list of strings? The name of the role? The technical ID of the role? (both did not work for me).
Any help is appreciated!
UPDATE Thanks to ravthiru I was able to solve my problem. The working code is this:
@Test
public void testPushGroupWithRealmRoles() throws IOException {
/*
ensure the roles exist
*/
String editRoleName = "junit_edit";
String deleteRoleName = "junit_delete";
RoleRepresentation editRole = getRealmRole(editRoleName);
if (editRole == null) {
editRole = new RoleRepresentation(editRoleName, "is allowed to edit", false);
getKeycloak().realm(clientConfig.getRealm()).roles().create(editRole);
}
RoleRepresentation deleteRole = getRealmRole(deleteRoleName);
if (deleteRole == null) {
deleteRole = new RoleRepresentation(deleteRoleName, "is allowed to delete", false);
getKeycloak().realm(clientConfig.getRealm()).roles().create(deleteRole);
}
/*
ensure the group exists
*/
GroupRepresentation group = new GroupRepresentation();
group.setName("JUnit Test Group realm roles");
GroupResource existingGroup = getGroupResource(group.getName());
if (existingGroup != null) {
existingGroup.update(group);
} else {
getKeycloak().realm(clientConfig.getRealm()).groups().add(group);
}
/*
assign roles to group
*/
existingGroup.roles().realmLevel().add(Arrays.asList(editRole, deleteRole));
}