David L David L - 1 year ago 111
Java Question

How to modify dynamically the roles of the logged user in Spring Security 4?

i'm trying to update the roles associated with the current logged user without log out, but it's not working as i wish.

Here is my code :

PreAuthenticatedAuthenticationToken authtoken_orig = (PreAuthenticatedAuthenticationToken) SecurityContextHolder

Collection<? extends GrantedAuthority> Authorities_orig = authtoken_orig.getAuthorities();
ArrayList<SimpleGrantedAuthority> Authorities_new = new ArrayList<SimpleGrantedAuthority>();

for (GrantedAuthority sga : Authorities_orig) {
SimpleGrantedAuthority tmpsga = (SimpleGrantedAuthority) sga;
if (tmpsga.getAuthority().compareTo("ROLE_UNKNOWN") != 0
&& tmpsga.getAuthority().compareTo("ROLE_SIGNER") != 0) {

SimpleGrantedAuthority role_signer_auth = new SimpleGrantedAuthority("ROLE_SIGNER");

PreAuthenticatedAuthenticationToken authtoken_new = new PreAuthenticatedAuthenticationToken(
authtoken_orig.getPrincipal(), authtoken_orig.getCredentials(), Authorities_new);

Please could you advice ?

Thanks in advance

David L.

Answer Source

First eval Granted Authority for the logged-in user like:

GrantedAuthority grantedAuthority = getNextRoleToAssign(context.getUserDetails());

Now, then initialiaze UsernamePasswordAuthenticationToken by using below code:

Authentication auth = new UsernamePasswordAuthenticationToken(authorisedUser, passowrd,Collections<GrantedAuthorities>);

Finally, set this Authentication into the Security context for the current User as mentioned below:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download