Spring Security 構(gòu)建rest服務(wù)實(shí)現(xiàn)rememberme 記住我功能
Spring security記住我基本原理:
登錄的時候,請求發(fā)送給過濾器UsernamePasswordAuthenticationFilter,當(dāng)該過濾器認(rèn)證成功后,會調(diào)用RememberMeService,會生成一個token,將token寫入到瀏覽器cookie,同時RememberMeService里邊還有個TokenRepository,將token和用戶信息寫入到數(shù)據(jù)庫中。這樣當(dāng)用戶再次訪問系統(tǒng),訪問某一個接口時,會經(jīng)過一個RememberMeAuthenticationFilter的過濾器,他會讀取cookie中的token,交給RememberService,RememberService會用TokenRepository根據(jù)token從數(shù)據(jù)庫中查是否有記錄,如果有記錄會把用戶名取出來,再調(diào)用UserDetailService根據(jù)用戶名獲取用戶信息,然后放在SecurityContext里。

RememberMeAuthenticationFilter在Spring Security中認(rèn)證過濾器鏈的倒數(shù)第二個過濾器位置,當(dāng)其他認(rèn)證過濾器都沒法認(rèn)證成功的時候,就會調(diào)用RememberMeAuthenticationFilter嘗試認(rèn)證。

實(shí)現(xiàn):
1,登錄表單加上<input type="checkbox" name="remember-me" value="true"/>,SpringSecurity在SpringSessionRememberMeServices類里定義了一個常量,默認(rèn)值就是remember-me
2,根據(jù)上邊的原理圖可知,要配置TokenRepository,把生成的token存進(jìn)數(shù)據(jù)庫,這是一個配置bean的配置,放在了BrowserSecurityConfig里
3,在configure里配置
4,在BrowserProperties里加上自動登錄時間,把記住我時間做成可配置的
//記住我秒數(shù)配置
private int rememberMeSeconds = 10;齊活
package com.imooc.s@Configuration //這是一個配置
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
//讀取用戶配置的登錄頁配置
@Autowired
private SecurityProperties securityProperties;
//自定義的登錄成功后的處理器
@Autowired
private AuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
//自定義的認(rèn)證失敗后的處理器
@Autowired
private AuthenticationFailureHandler imoocAuthenticationFailureHandler;
//數(shù)據(jù)源
@Autowired
private DataSource dataSource;
@Autowired
private UserDetailsService userDetailsService;
//注意是org.springframework.security.crypto.password.PasswordEncoder
@Bean
public PasswordEncoder passwordencoder(){
//BCryptPasswordEncoder implements PasswordEncoder
return new BCryptPasswordEncoder();
}
/**
* 記住我TokenRepository配置,在登錄成功后執(zhí)行
* 登錄成功后往數(shù)據(jù)庫存token的
* @Description: 記住我TokenRepository配置
* @param @return JdbcTokenRepositoryImpl
* @return PersistentTokenRepository
* @throws
* @author lihaoyang
* @date 2018年3月5日
*/
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//啟動時自動生成相應(yīng)表,可以在JdbcTokenRepositoryImpl里自己執(zhí)行CREATE_TABLE_SQL腳本生成表
jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
//版本二:可配置的登錄頁
@Override
protected void configure(HttpSecurity http) throws Exception {
//驗(yàn)證碼過濾器
ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
//驗(yàn)證碼過濾器中使用自己的錯誤處理
validateCodeFilter.setAuthenticationFailureHandler(imoocAuthenticationFailureHandler);
//配置的驗(yàn)證碼過濾url
validateCodeFilter.setSecurityProperties(securityProperties);
validateCodeFilter.afterPropertiesSet();
//實(shí)現(xiàn)需要認(rèn)證的接口跳轉(zhuǎn)表單登錄,安全=認(rèn)證+授權(quán)
//http.httpBasic() //這個就是默認(rèn)的彈框認(rèn)證
//
http //把驗(yàn)證碼過濾器加載登錄過濾器前邊
.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
//表單認(rèn)證相關(guān)配置
.formLogin()
.loginPage("/authentication/require") //處理用戶認(rèn)證BrowserSecurityController
//登錄過濾器UsernamePasswordAuthenticationFilter默認(rèn)登錄的url是"/login",在這能改
.loginProcessingUrl("/authentication/form")
.successHandler(imoocAuthenticationSuccessHandler)//自定義的認(rèn)證后處理器
.failureHandler(imoocAuthenticationFailureHandler) //登錄失敗后的處理
.and()
//記住我相關(guān)配置
.rememberMe()
.tokenRepository(persistentTokenRepository())//TokenRepository,登錄成功后往數(shù)據(jù)庫存token的
.tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())//記住我秒數(shù)
.userDetailsService(userDetailsService) //記住我成功后,調(diào)用userDetailsService查詢用戶信息
.and()
//授權(quán)相關(guān)的配置
.authorizeRequests()
// /authentication/require:處理登錄,securityProperties.getBrowser().getLoginPage():用戶配置的登錄頁
.antMatchers("/authentication/require",
securityProperties.getBrowser().getLoginPage(),//放過登錄頁不過濾,否則報錯
"/verifycode/image").permitAll() //驗(yàn)證碼
.anyRequest() //任何請求
.authenticated() //都需要身份認(rèn)證
.and()
.csrf().disable() //關(guān)閉csrf防護(hù)
;
}
}ecurity.browser;
其中由于要和數(shù)據(jù)庫打交道,所以需要注入一個數(shù)據(jù)源:application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/imooc-demo spring.datasource.username=root spring.datasource.password=root
啟動應(yīng)用,訪問 localhost:8080/user,需要登錄


登錄成功:

數(shù)據(jù)庫:生成一個persistent_logins表,存進(jìn)去了一條數(shù)據(jù)

停止服務(wù),從新啟動(注釋掉生成保存token表的jdbcTokenRepository.setCreateTableOnStartup(true);)因?yàn)槲覀兊挠脩舻卿浶畔⒍即嬖诹藄ession中,所以重啟服務(wù)后,再訪問localhost:8080/user,本應(yīng)該重新引導(dǎo)到登錄頁,但是由于配置了記住我,所以能夠直接訪問,拿到了接口數(shù)據(jù)

請求頭:

至此基本的rememberMe已做好
完整代碼放在了github:https://github.com/lhy1234/spring-security
總結(jié)
以上所述是小編給大家介紹的Spring Security 構(gòu)建rest服務(wù)實(shí)現(xiàn)rememberme 記住我功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- SpringSecurity rememberme功能實(shí)現(xiàn)過程解析
- 詳解使用Spring Security進(jìn)行自動登錄驗(yàn)證
- Spring Security實(shí)現(xiàn)兩周內(nèi)自動登錄"記住我"功能
- spring security實(shí)現(xiàn)下次自動登錄功能過程解析
- Spring Security 自動踢掉前一個登錄用戶的實(shí)現(xiàn)代碼
- Spring security實(shí)現(xiàn)記住我下次自動登錄功能過程詳解
- Spring Security學(xué)習(xí)之rememberMe自動登錄的實(shí)現(xiàn)
相關(guān)文章
java對象和json的來回轉(zhuǎn)換知識點(diǎn)總結(jié)
在本篇文章里小編給大家分享了一篇關(guān)于java對象和json的來回轉(zhuǎn)換知識點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-01-01
Spring Boot使用Druid和監(jiān)控配置方法
Druid是Java語言中最好的數(shù)據(jù)庫連接池,并且能夠提供強(qiáng)大的監(jiān)控和擴(kuò)展功能。下面來說明如何在 Spring Boot 中配置使用Druid2017-04-04
快速搭建Spring Boot+MyBatis的項目IDEA(附源碼下載)
這篇文章主要介紹了快速搭建Spring Boot+MyBatis的項目IDEA(附源碼下載),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
IDEA生成servlet程序的實(shí)現(xiàn)步驟
這篇文章主要介紹了IDEA生成servlet程序的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Springboot與vue實(shí)現(xiàn)文件導(dǎo)入方法具體介紹
文件導(dǎo)入時大多數(shù)項目無法回避的問題,這兩天深入學(xué)習(xí)了文件導(dǎo)入,在這里進(jìn)行記錄,使用到的技術(shù)是Springboot+Vue,前端組件使用el-upload2023-02-02

