I\'m doing an application with authentication by OpenID using Spring Security. When user is logged-in, some authorities are loaded in his session.
I have User with f
If you need to dynamically update a logged in user's authorities (when these have changed, for whatever reason), without having to log out and log in of course, you just need to reset the Authentication
object (security token) in the Spring SecurityContextHolder
.
Example:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List updatedAuthorities = new ArrayList<>(auth.getAuthorities());
updatedAuthorities.add(...); //add your role here [e.g., new SimpleGrantedAuthority("ROLE_NEW_ROLE")]
Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), updatedAuthorities);
SecurityContextHolder.getContext().setAuthentication(newAuth);