springsecurity整合springboot实现记住我自动登录
springsecurity整合springboot实现记住我自动登录
springsecurity实现记住我自动登录原理:用户登录时将token通过cookie保存在浏览器同时插入数据库,下一次登录时会从浏览器获取token查询数据进行匹配,匹配成功则自动登录
编写配置类继承WebSecurityConfigurerAdapter
package com.yl.config;
import com.yl.service.impl.MyUserDetailService;
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.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.sql.DataSource;
/**
* spring security配置类
*
* @author Y-wee
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailService myUserDetailService;
@Autowired
private DataSource dataSource;
/**
* 在容器中创建操作token对象
*
* @return
*/
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
// 设置数据源
jdbcTokenRepository.setDataSource(dataSource);
// 自动创建表persistent_logins存储token,也可以不开启自己手动创建
jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 记住我配置
http.rememberMe()
// 设置操作token对象
.tokenRepository(persistentTokenRepository())
// 设置token过期时间,单位是s
.tokenValiditySeconds(60)
// 设置UserDetailsService实现类
.userDetailsService(myUserDetailService);
}
}
注意:表单记住我属性名称必须设置为remember-me
<input type="checkbox" name="remember-me">记住我
persistent_logins建表sql
CREATE TABLE `persistent_logins` (
`username` varchar(64) NOT NULL,
`series` varchar(64) NOT NULL,
`token` varchar(64) NOT NULL,
`last_used` timestamp NOT NULL,
PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
记得快乐