我正在编写此问题,以便了解如何控制用户可以引用Spring Security的会话数 在春天,我可以定义所有用户必须拥有的最大会话数,即通过我定义的会话管理,例如,不应允许所有用户拥有超过3个会话
.sessionManagement().maximumSessions(3)
仅此一点是不够的,即我们需要为servlet容器提供一种通知spring安全性来更新会话或删除会话等的方法,因此我们需要配置HttpSessionEventPublishet
@Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
}
现在问题是如何配置类似的东西: 应允许管理员用户将最大会话数设置为8个会话专业管理员用户,但不应允许普通用户每个用户拥有多个会话。
答案 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());