Realm role is not assigned while creating user

Hi everyone,

I’m trying to create user and assign credentials and one role to him using admin client. Currently user is created and credentials are assigned, but role is not assigned. I created this role manually using administrator console. Here is what my code looks like:

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

     UserRepresentation user = new UserRepresentation();
     user.setEmail("pokusaj4.spring@live.com");
     user.setFirstName("Pokusaj");
     user.setLastName("Spring");
     user.setUsername("pokusaj4.spring");
     user.setEnabled(true);

    user.setRealmRoles(Arrays.asList("profesor"));

    CredentialRepresentation cred = new CredentialRepresentation();
    cred.setType(CredentialRepresentation.PASSWORD);
    cred.setValue("password");
    cred.setTemporary(false);

    user.setCredentials(Arrays.asList(cred));

    Response response = keycloak.realm("realm-test").users().create(user);

And i am using keycloak 9.0.3

Thanks in advance!

I also tried to set roles this way but it didn’t work for me so I tried this workaround and it’s working perfectly, which consist of setting roles in a different request as shown in the code below

    private void assignRoles(String userId, List<String> roles) {
    List<RoleRepresentation> roleList = rolesToRealmRoleRepresentation(roles);
    keycloak.realm("my_realm")
        .users()
        .get(userId)
        .roles()
        .realmLevel()
        .add(roleList);

}

private List<RoleRepresentation> rolesToRealmRoleRepresentation(List<String> roles) {
    List<RoleRepresentation> existingRoles = keycloak.realm(REALM)
        .roles()
        .list();

    List<String> serverRoles = existingRoles
        .stream()
        .map(RoleRepresentation::getName)
        .collect(Collectors.toList());
    List<RoleRepresentation> resultRoles = new ArrayList<>();

    for (String role : roles) {
        int index = serverRoles.indexOf(role);
        if (index != -1) {
            resultRoles.add(existingRoles.get(index));
        } else {
            log.info("Role doesn't exist");
        }
    }
    return resultRoles;
}
1 Like

Thank you very much for the response, it works now

1 Like

Hi,
Can anyone please share the Rest API (JSON) request for role creation. I have been able to create user but not able to update the role.

Hi,
I send Rest API (JSON) through postman with realmRoles. I have been able to create user but not able to assign the realmRole.

I have the same situation. Have to create user then assign realmRole separately.