SpringSecurity之記住我功能
- 記住我功能基本原理
- 記住我功能具體實現
- 記住我功能SpringSecurity源碼分析
記住我功能基本原理
這篇文章有停留兩周的時間沒有完成了,工作忙是一方面,另一方面是由于對spring security的理解混亂,導致出現問題解決時沒有頭緒,為此,閱讀了《spring 實戰》一書中的spring security章節后才逐漸思路清晰。下面接著對這篇文章進行補充。
首先從頭對spring security的配置進行注釋和整理,幫助閱讀代碼:
@Configuration
@EnableWebSecurity
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
SecurityProperties securityProperties;
@Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
@Autowired
private MyAuthenticationFailHandler myAuthenticationFailHandler;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Autowired
private DataSource dataSource;
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PersistentTokenRepository persistenceTokenRepository(){
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
//tokenRepository.setCreateTableOnStartup(true);
return tokenRepository;
}
/*
* 對每個請求進行細粒度安全性控制的關鍵在于重載configure(HttpSecurity)方法
*
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
*/
@Override
protected void configure(HttpSecurity http) throws Exception{
ValidateCodeFilter validateCodeFilter =new ValidateCodeFilter();
validateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailHandler);
http
/*
* 在UsernamePasswordAuthenticationFilter過濾器之前添加短信驗證碼過濾器
*/
.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
/*
* 表單登錄適用于瀏覽器向restful api發起請求;如果是后臺程序直接發起請求訪問restful api,則設為HTTP BASIC模式
*/
.formLogin()
.loginPage("/login.html") //跳轉的登錄頁/authentication/require
.loginProcessingUrl("/authentication/form") //登錄時的請求
.successHandler(myAuthenticationSuccessHandler) //表單登錄成功時使用我們自己寫的處理類
.failureHandler(myAuthenticationFailHandler) //表單登錄失敗時使用我們自己寫的處理類
.and()
/*
* 調用rememberMe()方法啟用記住我功能,通過在cookie中存儲一個token完成
*/
.rememberMe()
//指定保存token的倉庫,此處實現為保存到指定的數據庫中
.tokenRepository(persistenceTokenRepository())
//tokenValiditySeconds()指定token的有效時間
.tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())
//指定登錄用戶、密碼和權限
.userDetailsService(userDetailsService)
.and()
/*
* 調用HttpSecurity類的authorizeRequests()方法所返回的對象的方法來配置請求級別的安全性細節
*/
.authorizeRequests()
//antMatchers()對指定路徑的請求需要進行認證,這個方法以ant開頭表示路徑支持Ant風格的通配符,permitAll()方法運行請求沒有任何的安全限制
.antMatchers("login.html","/code/image").permitAll()
//anyRequest()指定了匹配之外的所有請求,authenticated()要求在執行該請求時,必須已經登錄了應用
.anyRequest().authenticated()
.and()
/*
* 禁用CSRF(跨站請求偽造)防護功能
*/
.csrf().disable();
}
web安全配置類中的configure方法是配置入口點,每一項配置都應該按照上面的寫法進行分類,每種配置之間都通過and方法進行連接,如以".formLogin()"開頭的是表單登錄相關的配置,以".rememberMe()"開頭的是記住我功能的相關配置,以".authorizeRequests()"開頭的是請求的安全配置。我們先回顧一下第三項以authorizeRequests()開頭的請求配置。
請求配置主要分兩個方面:
1.要配置的請求的路徑是什么?為此可以使用antMatchers()方法來指定路徑;而往往指定了特定的路徑后,在最后使用anyRequest()表示的是除以上以外的所有請求。
2.指定路徑之后,這個路徑所代表的請求該如何保護。如permitAll()方法表明對應的路徑沒有任何的安全限制,可以直接方法;authenticated()方法則表示只有認證成功以后才可以訪問指定路徑。
根據以上兩點,上述代碼中的這段請求安全配置可以理解為:請求路徑為"login.html"和"/code/image"可以直接訪問,沒有安全限制,而除此之外的其他請求必須在身份認證通過以后才能訪問。
在理解了請求的安全配置后,我們再來看記住我功能是怎么實現的。記住我的原理是在第一次登陸成功后,生成一份保存用戶信息的token,一方面將這個token保存到指定的數據庫中,另一方面將這個token保存到瀏覽器的cookie中。這樣即使以后session丟失(如服務器重啟)而瀏覽器的cookie還在,再次訪問時仍可以通過cookie中的token來直接訪問具體的restful api,而不需要重新進行表單登錄。這就實現了記住我的功能。
下面我們來演示一下,首先我們已經寫好一個具體的restful api:
@GetMapping("/user")
public void helloWorld(HttpServletRequest request,HttpServletResponse response) throws Exception{
System.out.println("hello world");
}
然后我們訪問表單登錄頁面,http://localhost:8080/login.html,截圖如下:
填寫完正確的用戶名和密碼和驗證碼之后,點擊登錄,登錄成功后,重新訪問http://localhost:8080/user
這時就可以成功輸出hello world了。但這只能說明登錄成功后,usernamepassworldauthentication filter將登錄信息保存到session中了,如果我們重啟服務后再直接訪問http://localhost:8080/user時,就不能直接訪問到restful api了,而是重定向到登錄頁面,因為重啟了以后session就不見了,但是我們加了記住我的配置后,即使重啟應用后直接訪問http://localhost:8080/user也能成功,這就是因為用戶信息是保存到瀏覽器cookie中,只要cookie中存在用戶信息就可以直接訪問成功,而不需要先表單登錄來進行身份認證。