UsernamePasswordAuthenticationFilter主要用来处理用户登录时的验证操作. 它的一般用法请参考Spring Security学习笔记之整体配置
ConcurrentSessionFilter的作用比较简单, 它会对每一个请求都作判断:
1) 如果session没过期, 就会更新session里的"last update" date/time;
2) 如果session过期, 就会调用logout handlers(一般是LogoutFilter)去销毁session, 然后跳转到expiredUrl;
(注意这里的session是指储存在SessionRegistry里的SessionInformation实例, 不是HttpSession)
ConcurrentSessionFilter的构造函数需要两个参数(第二个可以省略)
sessionRegistry: 一般是SessionRegistryImpl的实例
expiredUrl: session过期后跳转的页面
这里主要介绍一下如何使用这两个过滤器来防止用户重复登录的问题.
UsernamePasswordAuthenticationFilter的父类AbstractAuthenticationProcessingFilter有一个属性sessionStrategy, 就是用它来指定具体的防止重复登录的策略. 它的默认值是NullAuthenticatedSessionStrategy. NullAuthenticatedSessionStrategy只是一个抽象类, 不做任何操作, 源码如下:
- public final class NullAuthenticatedSessionStrategy implements SessionAuthenticationStrategy {
-
- public void onAuthentication(Authentication authentication, HttpServletRequest request,
- HttpServletResponse response) {
- }
- }
我们一般会把sessionStrategy绑定到一个CompositeSessionAuthenticationStrategy的实例. CompositeSessionAuthenticationStrategy只是一个代理类, 也不做具体的操作. 具体的操作会交给它的delegateStrategies属性所指定的
所有SessionAuthenticationStrategy实例来操作, 常用的有RegisterSessionAuthenticationStrategy和ConcurrentSessionControlAuthenticationStrategy.
注意, delegateStrategies 是一个集合, 可绑定多个SessionAuthenticationStrategy的实例:
- public class CompositeSessionAuthenticationStrategy implements SessionAuthenticationStrategy {
- private final Log logger = LogFactory.getLog(getClass());
- private final List delegateStrategies;
- ...
- }
绑定的配置如下:
- <bean id="loginAuthenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
- ...
- <property name="sessionAuthenticationStrategy" ref="compositeSessionAuthenticationStrategy">property>
- bean>
-
- <bean id="compositeSessionAuthenticationStrategy" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy">
- <constructor-arg>
- <list>
- <bean id="registerSessionAuthenticationStrategy" class="org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy">
- <constructor-arg ref="sessionRegistry"/>
- bean>
- <bean id="concurrentSessionControlAuthenticationStrategy" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
- <constructor-arg ref="sessionRegistry"/>
- <property name="maximumSessions" value="1">property>
-
-