http://blog.sina.com.cn/s/blog_8020e411010155lf.html html
SpringSecurity3.X--remember-me

(2012-04-20 15:03:14)
在SpringSecurity中配置remember-me时,遇到这样的问题,remember-me没有起做用,按照官方文档的讲解,只须要在<http>中增长<remember-me />配置,并在login.jsp中增长以下代码便可: java
Java代码 " quality="high" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
- <input id="_spring_security_remember_me" name="_spring_security_remember_me" type="checkbox" value="true"/>
看上去挺简单的,但是笔者测试后发现并未起做用,google了一下,也未见有人提起过该问题,因而乎翻出源码一探究竟,果真发现了问题。 spring
这里先简要说明一下SpringSecurity的登陆过程: cookie
Xml代码
- UsernamePasswordAuthenticationFilter :得到用户提交的用户名和密码信息
- -->UserDetailsService :由其封装用户对象
- -->AbstractUserDetailsAuthenticationProvider :转由其进行密码和权限验证,验证经过后封装一个Authentication
- -->ProviderManager:会将Authentication封装到SecurityContext中(默认状况下,ProviderManager会在认证成功后清除掉Authentication的密码信息,但会保留用户名称)
- -->AbstractRememberMeServices :判断请求参数中是否包含_spring_security_remember_me参数,若是包含而且值为(true,on,yes,1)中的任意一个,则将用户名和密码信息保存进cookie,不然不作处理
- -->AccessDecisionManager :由其决定是否放行
-
- 以后在请求被保护的资源时,RememberMeAuthenticationFilter会先判断是否Authentication已经失效,若是失效,则试图从cookie中寻找,找到则从新封装Authentication。
问题就出在ProviderManager中,其布尔属性eraseCredentialsAfterAuthentication默认值为true,若是为true则会在username和password验证成功后清除掉Authentication中的password信息,而AbstractRememberMeServices 保存cookie的条件则须要从Authentication中同时取得username和password,这就致使默认状况下AbstractRememberMeServices永远不会将username和password存储到cookie中,因此,为了保证username和password能够被正确的存储到cookie中,咱们须要修改eraseCredentialsAfterAuthentication的值为false,好在修改这个属性很方便,以下: app
Xml代码 " quality="high" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
- <authentication-manager erase-credentials="false">
- <authentication-provider user-service-ref="userService">
- <password-encoder hash="md5" />
- </authentication-provider>
- </authentication-manager>
增长该配置后,则cookie信息被成功保存。 jsp
默认状况下,cookie的有效期为两个星期,若是但愿修改这个有效期,能够在<remember-me />中进行配置: ide
Xml代码 " quality="high" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
- <remember-me token-validity-seconds="123456789"/>
不知道为何ProviderManager要这样处理,也许是我还没搞清楚原因,但愿与各位讨论。 测试
http://hanqunfeng.iteye.com/blog/1157022 google