Add role to user using Keycloak Admin Java API

1.8k Views Asked by At

The goal is to manager user's roles from my Angular front. The front will send me updated roles given for a user.

Actually the user have ["ROLE_A"]

The administrator updates user's role.

Now the front sends me : ["ROLE_A","ROLE_B","ROLE_C"] for the given user.

My goal is to be able to update roles of this user.

There can be more or less rights than before. (the "differences list" "is working"..(404 error) only when there is new role than before.. but not when i remove some roles..)


public void updateUserRoles() {
        
        keycloak = keycloakService.getInstance();
        List<RoleRepresentation> rolesOfUserActual = keycloak.realm("api").users().get("95315cf6-b10f-4b6c-a8ac-f60ca4820307").roles().realmLevel().listAll();
        List<RoleRepresentation> rolesOfUserActualNew = keycloak.realm("api").users().get("95315cf6-b10f-4b6c-a8ac-f60ca4820307").roles().realmLevel().listAll();

        RoleRepresentation newrole = new RoleRepresentation("ROLE_READ_GROUPS", null, false); // this role already exists in keycloak.
        rolesOfUserActualNew.add(newrole);
        
        
        List<RoleRepresentation> differences = rolesOfUserActual.stream()
                .filter(name -> !rolesOfUserActualNew.contains(name))
                .collect(Collectors.toList());
        
        
        List<RoleRepresentation> roleToAdd = new ArrayList();
        List<RoleRepresentation> roleToDelete = new ArrayList();

        
        differences.forEach((role) -> {
            if(rolesOfUserActual.contains(role)) {
                roleToDelete.add(role);
            }else {
                roleToAdd.add(role);
            }
        });
        
        keycloak.realm("api").users().get("95315cf6-b10f-4b6c-a8ac-f60ca4820307").roles().realmLevel().add(roleToAdd);
        keycloak.realm("api").users().get("95315cf6-b10f-4b6c-a8ac-f60ca4820307").roles().realmLevel().remove(roleToDelete);

    }

I don't understand why it is so complicated (many list) to update roles :(

I don't think i took the good road..

1

There are 1 best solutions below

0
On

Answer found here : Comparing two lists and getting differences

CollectionUtils.removeAll(rolesOfUserActual, rolesOfUserActualNew); // roles added
CollectionUtils.removeAll(rolesOfUserActualNew, rolesOfUserActual); //roles deleted