1. 程式人生 > 其它 >springsecurity整合springboot實現記住我自動登入

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;
記得快樂