问题描述
我正在做一个使用 Spring Security 通过 OpenID 进行身份验证的应用程序.当用户登录时,他的会话中会加载一些权限.
I'm doing an application with authentication by OpenID using Spring Security.When user is logged-in, some authorities are loaded in his session.
我拥有完全权限的用户,可以修改其他用户的权限(撤销、添加角色).我的问题是,如何动态更改用户会话权限?(无法使用 SecurityContextHolder 因为我想更改另一个用户会话).
I have User with full right which can modify authorities (revoke, add roles) of others users. My question is, how to change User session authorities dynamically ? (cannot use SecurityContextHolder because I want to change another User session).
简单的方法:使用户会话无效,但如何?更好的方法:使用新权限刷新用户会话,但如何?
Simple way : invalidate user session, but how to ?Better way : refresh user session with new authorities, but how to ?
推荐答案
如果您需要动态更新已登录用户的权限(当这些权限发生更改时,无论出于何种原因),当然无需注销和登录,您只需要在 Spring SecurityContextHolder
中重置 Authentication
对象(安全令牌).
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
.
示例:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> 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);
这篇关于如何使用 Spring Security 重新加载用户更新权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!