【问题标题】:reauthenticating users after promote them推广用户后重新认证用户
【发布时间】:2015-03-07 04:45:33
【问题描述】:

嗨,在 Spring mvc 3 和 Spring Security 3 中有一个应用程序。碰巧我决定提升一个用户(我有一个包含 user、role 和 user_role 表的数据库),但是当我将新角色添加到数据库时,问题就来了,如何在不注销用户的情况下更新主要权限?寻找答案我发现了这个:

// update database with new role
//... you fill in this part

// update the current Authentication
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>  (auth.getAuthorities());
authorities.add(new GrantedAuthorityImpl('ROLE_NEWROLE'));
Authentication newAuth = new UsernamePasswordToken(auth.getPrincipal(),auth.getCredentials(),authorities)
SecurityContextHolder.getContext().setAuthentication(newAuth);

现在,这种方法看起来不错,但我的问题是,鉴于 securitycontextholder 检索与调用他的当前用户有关的信息,我如何从我的管理员帐户将上述代码应用于系统中的每个用户? 我正在使用自己的身份验证提供程序。

【问题讨论】:

    标签: spring-security spring-3


    【解决方案1】:

    一种选择是实施以下策略:

    1. 保留角色已修改的用户的全局注册表。这可以使用ConcurrentHashMap(如果您有多个应用服务器,则使用分布式缓存)来实现。
    2. 管理员更改用户角色后,立即将用户(其角色已更改)的主体(电子邮件地址、用户名等)推送到此注册表。
    3. 编写一个过滤器,检查当前用户的主体是否在注册表中。如果主体在注册表中,过滤器会刷新用户的角色,然后从注册表中删除主体。然后像往常一样处理请求的其余部分。

    【讨论】:

    • 是的,这是个好主意,问题是当您说 SecurityContextHolder.getContext().setAuthentication(newAuth) 时,您指的是一个用户,我需要的是对许多用户进行身份验证。 Tnks
    • 默认 Spring Security 实现将身份验证令牌存储在 HTTP 会话对象中。由于安全原因,无法访问自己的会话以外的会话。因此,在标准环境中,不可能同时访问allmany 用户的身份验证令牌。您可以创建SecurityContextRepository 的自定义实现来存储身份验证令牌,例如可过期的内存缓存。这将为您提供 HTTP 会话语义,并允许您在需要时访问所有令牌。
    • SecurityContextRepository 的示例实现可以在here 找到。代码在 Scala 中,但您可以轻松地将其转换为 Java 代码。
    • 如果您的应用程序运行在多台服务器上,您将需要使用分布式缓存来模拟容器提供的会话复制。
    • 非常感谢您正在研究这种方法。
    猜你喜欢
    • 2019-12-22
    • 1970-01-01
    • 2013-10-14
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    相关资源
    最近更新 更多