实现记住我的功能
记住我功能基本原理
记住我功能具体实现
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