I am using Spring Security to Authenticate user.
Question is what would be the best way to dynamically update authorities? I would like to update it per request, now I just doing it once after user login into the system.
I have manager based application, so admin could decide what user could do at any time, and remove/add roles. Problem with this approach that user will get new set of permissions only after he log out and log in back.
I know I could use
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = Lists.newArrayList();
userDao.getAuthorities(authorities, user);
Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities);
SecurityContextHolder.getContext().setAuthentication(newAuth);
The main question is what would be the right moment to do it? Some filter chain before framework hit controller or interceptor? And how safe it is? Thread safe?
Lets say if I put it in interceptor, and while I am updating SecurityContextHolder in one request another request reading it - what will happen ?
Just quick draft
public class VerifyAccessInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = Lists.newArrayList();
userDao.getAuthorities(authorities, user);
Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities);
SecurityContextHolder.getContext().setAuthentication(newAuth);
}
}