Hi,
Can someone show me a working example of changing the realm set of roles for a user?Here is an example that does not appear to work in KC1.9.3 - after the execution, there is no effect in the console, the user roles remain unchanged. No error whatsoever???
private static void updateRoles(Plan newPlan, UserResource user, RealmResource realm) {
//Get all realm roles
RolesResource realmRoles = realm.roles();//Get the user's realm level roles
RoleScopeResource userRoles = user.roles().realmLevel();//Get all existing plan roles to be removed
List<RoleRepresentation> rolesToRemove = userRoles.listEffective()
.stream()
.filter((RoleRepresentation r) -> !Roles.isPlanRole(r.getName()) && !Roles.isExpiredPlanRole(r.getName()))
.collect(Collectors.toList());//Add the new plan role
List<RoleRepresentation> rolesToAdd = new ArrayList<>(1);
realmRoles
.list()
.stream()
.filter(r -> r.getName().equals(newPlan.role.getName()))
.findFirst().ifPresent((RoleRepresentation r) -> rolesToAdd.add(r));
//Perform remove
userRoles.remove(rolesToRemove);
//Perform add
userRoles.add(rolesToAdd);
//Go check the admin console - Surprise .. nothing really changed???}
And here is another example that does nothing:
...
RealmResource realm = admin.realm(RealmAdmin.REALM_NAME);
UserResource userResource = realm.users().get(userId);
UserRepresentation userRepresentation = userResource.toRepresentation();
...
//Assign new plan role
updateRoles(request.plan, userResource);
userResource.update(userRepresentation);private static void updateRoles(Plan newPlan, UserRepresentation userRepresentation) {
List<String> newRoles = userRepresentation.getRealmRoles();
if(newRoles!=null){
newRoles.stream()
.filter(r -> !Roles.isPlanRole(r) && !Roles.isExpiredPlanRole(r))
.collect(Collectors.toList());
}else{
newRoles = new ArrayList<>(1);
}
newRoles.add(newPlan.role.getName());
userRepresentation.setRealmRoles(newRoles);
}/Hristo Stoyanov
_______________________________________________ keycloak-user mailing list keycloak-user@lists.jboss.org https://lists.jboss.org/mailman/listinfo/keycloak-user