常规配置 增加监听
web.XML
<listener>
<listener-class>
org.springframework.security.ui.session.HttpSessionEventPublisher
</listener-class>
</listener>
spring-security.XML
<concurrent-session-control max-sessions="1" exception-if-maximum-exceeded="true" expired-url="/login.jsp"/> <http-basic /></http>如上配置就会其效果,但是有几种情况
如果spring security的一段<http/>中使用了自定义过滤器<custom-filter/>(特别是FORM_LOGIN_FILTER),或者配置了AuthenticationEntryPoint,或者使用了自定义的UserDetails、AccessDecisionManager、AbstractSecurityInterceptor、FilterInvocationSecurityMetadataSource、UsernamePasswordAuthenticationFilter等,上面的简单配置可能就不会生效了,Spring Security Reference Documentation里面3.3.3 Session Management是这样说的:
- If you are using a customized authentication filter for form-based login, then you have to configure concurrent session control support explicitly. More details can be found in the Session Management chapter.
此时,就需要UsernamePasswordAuthenticationFilter中增加<beans:property name="sessionAuthenticationStrategy" ref="sas"></beans:property>
<beans:bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
<beans:property name="maximumSessions" value="1"></beans:property>
<beans:property name="exceptionIfMaximumExceeded" value="true"></beans:property>
<beans:constructor-arg name="sessionRegistry" ref="sessionRegistry"></beans:constructor-arg>
</beans:bean>
<beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"></beans:bean>
</beans:beans>
解决问题
本文介绍了Spring Security中实现单用户登录会话管理的配置方法。当使用自定义过滤器、AuthenticationEntryPoint或其他自定义组件时,简单的配置可能无法生效。通过在UsernamePasswordAuthenticationFilter中设置sessionAuthenticationStrategy,并配合ConcurrentSessionControlStrategy和SessionRegistryImpl,可以实现并发会话控制,限制同一用户只能有一个有效登录。


928

被折叠的 条评论
为什么被折叠?



