實現記住我的功能
記住我功能基本原理
記住我功能具體實現
1. 記住我功能基本原理
springsecruity基本原理
2. 記住我功能具體實現
1. 配置TokenRepository
2. 在configure中指定rememberMe需要的配置包含TokenRepository對象以及token過期時間
package com.example.demospringsecruity.config;
import com.example.demospringsecruity.filter.ValidateCodeFilter;
import com.example.demospringsecruity.handler.MyAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.sql.DataSource;
/**
* @author john
* @date 2020/1/6 - 10:07
*/
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
ValidateCodeFilter validateCodeFilter;
@Autowired
MyAuthenticationFailureHandler myAuthenticationFailureHandler;
@Autowired
private DataSource dataSource;
@Autowired
private MyUserDetailsService userDetailsService;
//手動將PasswordEncoder注入到ioc容器中
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// 1. 配置TokenRepository
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
tokenRepository.setCreateTableOnStartup(true);
return tokenRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
validateCodeFilter.setMyAuthenticationFailureHandler(myAuthenticationFailureHandler);
// 表單登錄
http //過濾器設置
// 將驗證碼過濾器配置到UsernamePasswordAuthenticationFilter前面
.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
//登錄設置
.formLogin()
.loginPage("/signin.html") //設置登錄路由
.loginProcessingUrl("/auth/form") //設置登錄處理url
.failureHandler(myAuthenticationFailureHandler)
.and()
//記住我的配置
// rememberMe需要的配置包含TokenRepository對象以及token過期時間
.rememberMe()
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60 * 60 * 24)
.userDetailsService(userDetailsService)
.and()
// 身份認證設置
.authorizeRequests()
.antMatchers("/signin.html").permitAll() //該路由不需要身份認賬
.antMatchers("/code/*").permitAll() //該路由不需要身份認賬
.anyRequest() //其他的路由均需要身份認證
.authenticated()
.and()
//先禁用防止跨站腳本攻擊的csrf token
.csrf()
.disable();
}
}
3. 測試
4. 代碼資源
鏈接:https://share.weiyun.com/5CJaNmB 密碼:njvcdv