每个用户组或每个用户的Spring Security并发会话控制

时间:2014-11-05 15:36:45

标签: spring concurrency spring-security

我正在编写此问题,以便了解如何控制用户可以引用Spring Security的会话数 在春天,我可以定义所有用户必须拥有的最大会话数,即通过我定义的会话管理,例如,不应允许所有用户拥有超过3个会话

.sessionManagement().maximumSessions(3)

仅此一点是不够的,即我们需要为servlet容器提供一种通知spring安全性来更新会话或删除会话等的方法,因此我们需要配置HttpSessionEventPublishet

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

现在问题是如何配置类似的东西: 应允许管理员用户将最大会话数设置为8个会话专业管理员用户,但不应允许普通用户每个用户拥有多个会话。

1 个答案:

答案 0 :(得分:6)

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

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

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

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());