gpt4 book ai didi

java - 通过 Spring SecurityContextHolder 更新权限

转载 作者:太空宇宙 更新时间:2023-11-04 14:11:09 25 4
gpt4 key购买 nike

我正在使用 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);

主要问题是什么时候做这件事合适?框架命中 Controller 或拦截器之前的一些过滤器链?它有多安全?线程安全?

假设我将它放入拦截器中,当我在一个请求中更新 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);

}
}

最佳答案

如果我错了,请纠正我。

从您的问题中可以看出,您显然希望基于请求进行Authority更改。理想情况下,管理员将有一个不同的 UI,他可以在其中删除/添加权限。这些更改必须近乎实时地反射(reflect)在任何登录的用户 session 中。

目前,您提供的代码片段是您可以做到这一点的唯一方法。

解答您的疑虑。

主要问题是什么时候做这件事合适?

如果您希望它仅应用于登录的用户,那么您必须将其放在拦截器中,因为它只会在 Spring 安全过滤器链之后应用。

Some filter chain before framework hit controller or interceptor?

是的,在您的请求到达 Controller 或拦截器之前,将首先调用 DelegatingFilterProxy 和 FilterChainProxy。

And how safe it is? Thread safe?

是的,如果您使用具有默认设置的SecurityContextHolder,它将使用线程安全的ThreadLocalSecurityContextHolderStrategy

由于所有请求都必须经过拦截器,因此性能会受到影响。而且,由于只有在权限更改得更好时,您才需要更改权限,以便在重新设置身份验证

之前在拦截器中进行检查
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);

// If contents of auth.getAuthorities() equals authorities then no need to re-set.
Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities);
SecurityContextHolder.getContext().setAuthentication(newAuth);

}
}

关于java - 通过 Spring SecurityContextHolder 更新权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28311922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com