<p dir="ltr">Hi,<br>
Can someone show me a working example of changing the realm set of roles for a user?</p>
<p dir="ltr">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???</p>
<p dir="ltr">private static void updateRoles(Plan newPlan, UserResource user, RealmResource realm) {<br>
//Get all realm roles<br>
RolesResource realmRoles = realm.roles();</p>
<p dir="ltr"> //Get the user's realm level roles<br>
RoleScopeResource userRoles = user.roles().realmLevel();</p>
<p dir="ltr"> //Get all existing plan roles to be removed<br>
List<RoleRepresentation> rolesToRemove = userRoles.listEffective()<br>
.stream()<br>
.filter((RoleRepresentation r) -> !Roles.isPlanRole(r.getName()) && !Roles.isExpiredPlanRole(r.getName()))<br>
.collect(Collectors.toList());</p>
<p dir="ltr"> //Add the new plan role <br>
List<RoleRepresentation> rolesToAdd = new ArrayList<>(1);<br>
realmRoles<br>
.list()<br>
.stream()<br>
.filter(r -> r.getName().equals(newPlan.role.getName()))<br>
.findFirst().ifPresent((RoleRepresentation r) -> rolesToAdd.add(r));<br>
<br>
                //Perform remove<br>
userRoles.remove(rolesToRemove);<br>
<br>
                //Perform add<br>
userRoles.add(rolesToAdd);<br>
                <br>
                //Go check the admin console - Surprise .. nothing really changed???</p>
<p dir="ltr"> }<br>
        <br>
And here is another example that does nothing:<br>
...<br>
         RealmResource realm = admin.realm(RealmAdmin.REALM_NAME);<br>
UserResource userResource = realm.users().get(userId);<br>
UserRepresentation userRepresentation = userResource.toRepresentation();<br>
         ...<br>
         //Assign new plan role<br>
updateRoles(request.plan, userResource);<br>
userResource.update(userRepresentation);</p>
<p dir="ltr"> private static void updateRoles(Plan newPlan, UserRepresentation userRepresentation) {<br>
List<String> newRoles = userRepresentation.getRealmRoles();<br>
if(newRoles!=null){<br>
newRoles.stream()<br>
.filter(r -> !Roles.isPlanRole(r) && !Roles.isExpiredPlanRole(r))<br>
.collect(Collectors.toList());<br>
}else{<br>
newRoles = new ArrayList<>(1);<br>
}<br>
newRoles.add(newPlan.role.getName());<br>
userRepresentation.setRealmRoles(newRoles);<br>
}</p>
<p dir="ltr">/Hristo Stoyanov</p>