【发布时间】:2015-02-04 01:25:28
【问题描述】:
我正在使用 Spring Security 来验证用户。
问题是动态更新权限的最佳方式是什么? 我想根据请求更新它,现在我只在用户登录系统后执行一次。
我有基于管理器的应用程序,因此管理员可以随时决定用户可以做什么,并删除/添加角色。这种方法的问题是,用户只有在注销并重新登录后才能获得新的权限集。
我知道我可以使用
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);
主要问题是什么时候做这件事最合适?框架命中控制器或拦截器之前的一些过滤器链?它有多安全?线程安全吗?
假设我把它放在拦截器中,当我在一个请求中更新 SecurityContextHolder 时,另一个请求读取它 - 会发生什么?
快速草稿
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);
}
}
【问题讨论】:
标签: java spring spring-mvc spring-security