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

相關文章
相關標籤/搜索