How to reload authorities on user update with Spring Security

前端 未结 6 1818
情话喂你
情话喂你 2020-12-04 08:44

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

6条回答
  •  时光取名叫无心
    2020-12-04 09:24

    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);
    

提交回复
热议问题