Spring Boot + Spring Security添加记住我功能

  • 功能:

当用户勾选了记住我选项并登陆成功后,Spring Security会生成一个token标识,而后将该token标识持久化到数据库,而且生成一个与该token相对应的cookie返回给浏览器。当用户过段时间再次访问系统时,若是该cookie没有过时,Spring Security便会根据cookie包含的信息从数据库中获取相应的token信息,而后帮用户自动完成登陆操做html

注:本博文在Spring Boot+Spring Security图形验证码的基础上来添加记住个人功能。java

  • 引入依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

Spring Security的记住我功能的实现须要使用数据库来持久化token。mysql

  • 创建表:
CREATE TABLE persistent_logins (
    username VARCHAR (64) NOT NULL,
    series VARCHAR (64) PRIMARY KEY,
    token VARCHAR (64) NOT NULL,
    last_used TIMESTAMP NOT NULL
)
  • 配置yml:
server:
  port: 8004
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/security?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456
  • 修改MySecurityConfig,兵备之配置token持久化对象
@Component
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyAuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private MyAuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private ValidateCodeFilter validateCodeFilter;
    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private DataSource dataSource;

    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        jdbcTokenRepository.setCreateTableOnStartup(false);
        return jdbcTokenRepository;
    }
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
                .formLogin() // 表单登陆
                // http.httpBasic() // HTTP Basic
                .loginPage("/authentication/require") // 登陆跳转 URL
                .loginProcessingUrl("/login") // 处理表单登陆 URL
                .failureHandler(authenticationFailureHandler) // 处理登陆失败
                .successHandler(authenticationSuccessHandler)
                 .and()
                 .rememberMe() // 启用rememberMe
                 .tokenRepository(persistentTokenRepository()) // 配置 token 持久化仓库
                 .tokenValiditySeconds(3600) // remember 过时时间,单为秒
                 .userDetailsService(userDetailService) // 处理自动登陆逻辑
                .and()
                .authorizeRequests() // 受权配置
                .antMatchers("/authentication/require",
                        "/login.html",
                        "/code/image").permitAll() // 无需认证的请求路径
                .anyRequest()  // 全部请求
                .authenticated() // 都须要认证
                .and().csrf().disable();
    }
}
  • 修改login.html(记住个人标签 name="remember-me"不然会报错)
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
</head>
<body>
<form class="login-page" action="/login" method="post">
    <div class="form">
        <h3>帐户登陆</h3>
        <input type="text" placeholder="用户名" name="username" required="required" >
        <input type="password" placeholder="密码" name="password" required="required" >

    <input type="text" name="imageCode" placeholder="验证码" style="width: 50%;"/>
    <img src="/code/image"/>
        <input type="checkbox" name="remember-me"/> 记住我
        <button type="submit">登陆</button>
    </div>
</form>
</body>
</html>

点击记住我以后,登录成功:git

表中:github

本文代码正常运行!spring

源代码地址:https://github.com/ttdys/springboot/tree/master/springboot_security/04_remember_mesql

相关文章
相关标签/搜索