【问题标题】:Spring Security concurrent session control per User group or per single user每个用户组或单个用户的 Spring Security 并发会话控制
【发布时间】:2015-01-01 20:55:27
【问题描述】:

我写这个问题是为了了解如何控制用户可以参考 Spring Security 的会话数 在春季,我可以定义所有用户必须拥有的最大会话数,即通过我定义的会话管理,例如,所有用户不应被允许拥有超过 3 个会话

.sessionManagement().maximumSessions(3)

仅此还不够,即我们需要为 servlet 容器提供一种方法来通知 Spring Security 更新会话或删除会话等。因此我们需要配置 HttpSessionEventPublishet

@Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
    return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
}

现在的问题是我如何配置这样的东西: 应该允许管理员用户将最大会话数设置为 8 个会话 pro 管理员用户,但不应允许普通用户每个用户拥有超过一个会话。

【问题讨论】:

  • 根据ConcurrentSessionControlAuthenticationStrategy 类实施您自己的策略。您需要覆盖 getMaximumSessionsForThisUser 方法并在那里实现您的逻辑。然后将您的自定义实施与sessionmanagement 连接起来。
  • Deinum 感谢您的回复,我将花一周时间处理该信息并让您知道这是否是答案,这对我来说似乎是合理的。再次感谢您的快速反馈。

标签: spring concurrency spring-security


【解决方案1】:

默认策略只允许在全局范围内设置最大会话数,而不管用户如何。该属性在类ConcurrentSessionControlAuthenticationStrategy 上设置,该类具有该属性的简单设置器。

实际值在getMaximumSessionsForThisUser 方法中确定,在默认实现中,该方法返回maximumSession 属性的值。

您需要通过创建一个实现 SessionAuthenticationStrategy 的类来完全实现自己的策略,或者更简单地通过创建一个简单地覆盖 getMaximumSessionsForThisUser 方法的 ConcurrentSessionControlAuthenticationStrategy 的子类来实现自己的策略。

public class CustomConcurrentSessionControlAuthenticationStrategy extends ConcurrentSessionControlAuthenticationStrategy {

    protected int getMaximumSessionsForThisUser(Authentication authentication) {
        boolean admin = // Check authentication.getAuthorities() for the admin role
        return admin ? 8 : 1;

    }
}

然后在您的配置中为其创建一个 @Bean 并将该 bean 连接到配置的 sessionManagement 部分。

@Bean
public CustomConcurrentSessionControlAuthenticationStrategy sessionControlStrategy() {
    return new CustomConcurrentSessionControlAuthenticationStrategy(new SessionRegistryImpl());
}

然后在您的安全配置代码中执行类似的操作

sessionManagement().sessionAuthenticationStrategy(sessionControlStrategy());

【讨论】:

  • M. Deinum 现在已经完成了我的测试,它可以工作了!再次感谢。
  • 我只想添加以下内容,我必须创建一个 bean SessionRegistryImpl 并将该 bean 传递给 CustomConcurrentSessionControlAuthenticationStrategy 构造函数,因为我没有定义隐式默认构造函数,这是因为 ConcurrentSessionControlAuthenticationStrategy 也没有。
猜你喜欢
  • 2015-12-26
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
  • 2021-04-18
  • 2011-08-29
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
相关资源
最近更新 更多