如何使用Spring Security重新加载用户更新的权限 [英] How to reload authorities on user update with Spring Security

查看:992
本文介绍了如何使用Spring Security重新加载用户更新的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

如果你需要动态更新a登录用户的权限(当这些已更改时,无论出于何种原因),当然不需要注销并登录,您只需要重置身份验证对象(安全令牌) )在Spring SecurityContextHolder

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重新加载用户更新的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆