Search code examples
javakeycloakkeycloak-services

Keycloak: Create role with attributes in Java Client


I am trying to create a client role in Keycloak(11.0.0) with keycloak-admin-client (11.0.0) with a few custom attributes. The role gets created, but the attribute field is simply ignored by Keycloak. Has anybody an idea how to get it working?

This is the simplified code I am using:

public void createRole(String name) {
    RoleRepresentation roleRepresentation = new RoleRepresentation();
    Map<String, List<String>> attributes = new HashMap<>();
    attributes.put("att1", Collections.singletonList("attribute1"));
    attributes.put("att2", Collections.singletonList("attribute2"));
    roleRepresentation.setAttributes(attributes);
    roleRepresentation.setClientRole(true);
    roleRepresentation.setName(name);
    realm.clients().get(client.getId()).roles().create(roleRepresentation);
}

I would greatly appreciate any help with this issue. Thanks!


Solution

  • For everyone who is struggling with the same problem: I just found a workaround myself. You need to update the newly created role with the same object and it works.

    public void createRole(String name) {
            RoleRepresentation roleRepresentation = new RoleRepresentation();
            Map<String, List<String>> attributes = new HashMap<>();
            attributes.put("att1", Collections.singletonList("attribute1"));
            attributes.put("att2", Collections.singletonList("attribute2"));
            roleRepresentation.setAttributes(attributes);
            roleRepresentation.setClientRole(true);
            roleRepresentation.setName(name);
            realm.clients().get(client.getId()).roles().create(roleRepresentation);
            
            // Now update the new role immediately
            RoleResource roleResource = realm.clients().get(client.getId()).roles().get(name);
            roleResource.update(roleRepresentation);
        }