简体   繁体   中英

Add role to user using Keycloak Admin Java API

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..

Answer found here : Comparing two lists and getting differences

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM