[keycloak-user] Example of the oles manipulation via Rest API?
Hristo Stoyanov
hr.stoyanov at peruncs.com
Wed May 4 02:28:01 EDT 2016
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.jboss.org/pipermail/keycloak-user/attachments/20160504/d2f983bf/attachment-0001.html
More information about the keycloak-user
mailing list