David L David L - 3 months ago 19
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
.getContext().getAuthentication();

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) {
Authorities_new.add(tmpsga);
}
}

SimpleGrantedAuthority role_signer_auth = new SimpleGrantedAuthority("ROLE_SIGNER");
Authorities_new.add(role_signer_auth);

PreAuthenticatedAuthenticationToken authtoken_new = new PreAuthenticatedAuthenticationToken(
authtoken_orig.getPrincipal(), authtoken_orig.getCredentials(), Authorities_new);
SecurityContextHolder.clearContext();
SecurityContextHolder.createEmptyContext().setAuthentication(authtoken_new);


Please could you advice ?

Thanks in advance

David L.

Answer

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:

SecurityContextHolder.getContext().setAuthentication(auth);