SpringSecurity3.X--remember-me

http://blog.sina.com.cn/s/blog_8020e411010155lf.html html

SpringSecurity3.X--remember-me

  (2012-04-20 15:03:14)
標籤: 

it

分類: javaEE

在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">  收藏代碼
  1. <input id="_spring_security_remember_me" name="_spring_security_remember_me" type="checkbox" value="true"/>  
 

看上去挺簡單的,但是筆者測試後發現並未起做用,google了一下,也未見有人提起過該問題,因而乎翻出源碼一探究竟,果真發現了問題。 spring

 

這裏先簡要說明一下SpringSecurity的登陸過程: cookie

Xml代碼   收藏代碼
  1. UsernamePasswordAuthenticationFilter :得到用戶提交的用戶名和密碼信息  
  2. -->UserDetailsService :由其封裝用戶對象  
  3. -->AbstractUserDetailsAuthenticationProvider :轉由其進行密碼和權限驗證,驗證經過後封裝一個Authentication  
  4. -->ProviderManager:會將Authentication封裝到SecurityContext中(默認狀況下,ProviderManager會在認證成功後清除掉Authentication的密碼信息,但會保留用戶名稱)  
  5. -->AbstractRememberMeServices :判斷請求參數中是否包含_spring_security_remember_me參數,若是包含而且值爲(true,on,yes,1)中的任意一個,則將用戶名和密碼信息保存進cookie,不然不作處理  
  6. -->AccessDecisionManager :由其決定是否放行  
  7.   
  8. 以後在請求被保護的資源時,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">  收藏代碼
  1. <authentication-manager erase-credentials="false">  
  2.         <authentication-provider user-service-ref="userService">  
  3.             <password-encoder hash="md5" />  
  4.         </authentication-provider>  
  5. </authentication-manager>  
     

 增長該配置後,則cookie信息被成功保存。 jsp

 

 默認狀況下,cookie的有效期爲兩個星期,若是但願修改這個有效期,能夠在<remember-me />中進行配置: ide

Xml代碼 " quality="high" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">  收藏代碼
  1. <remember-me  token-validity-seconds="123456789"/>  
 

 

不知道爲何ProviderManager要這樣處理,也許是我還沒搞清楚原因,但願與各位討論。 測試

http://hanqunfeng.iteye.com/blog/1157022 google

相關文章
相關標籤/搜索