Spring Boot Security5 記住我功能(4)

前言

上篇文章介紹了Spring Boot Security配置了自定義登錄
本篇文章,小編會(huì)介紹實(shí)現(xiàn)記住我功能

開始

Spring Security記住我功能,其實(shí)就是就是當(dāng)用戶勾選了"記住我"然后成功認(rèn)證登錄了,那在有效時(shí)間內(nèi)免登錄直接進(jìn)入
那么,Spring Security實(shí)現(xiàn)記住我的方式有兩種:

  1. 本地存儲(chǔ)(cookie)
  2. 持久化存儲(chǔ)

這里小編簡單的說下流程,當(dāng)Spring Security用戶登錄成功的時(shí)候,它會(huì)生成授權(quán)信息(token)
然后方法一的話,Spring Security會(huì)把token傳輸?shù)接脩舯镜貫g覽器cookie里面存儲(chǔ)起來
方法二的話就是把token存入數(shù)據(jù)庫中,那么相信大家也就清楚了

像token這種敏感的數(shù)據(jù),是不建議暴露用戶那邊的,因?yàn)檫@樣很容易會(huì)被中間人劫持,又或者被偽造請求(CSRF),所以小編是建議使用第二種辦法

那么下面開始展示實(shí)現(xiàn)代碼,,我們繼上篇的代碼,在Spring Security配置類上添加持久化配置:

SecurityConfig .java

package com.demo.ssdemo.config;

import com.demo.ssdemo.core.LoginValidateAuthenticationProvider;
import com.demo.ssdemo.core.handler.LoginFailureHandler;
import com.demo.ssdemo.core.handler.LoginSuccessHandler;
import com.demo.ssdemo.sys.service.UserService;
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.EnableWebSecurity;
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.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //數(shù)據(jù)源
    @Resource
    private DataSource dataSource;

    //用戶業(yè)務(wù)層
    @Resource
    private UserService userService;

    //自定義認(rèn)證
    @Resource
    private LoginValidateAuthenticationProvider loginValidateAuthenticationProvider;

    //登錄成功handler
    @Resource
    private LoginSuccessHandler loginSuccessHandler;

    //登錄失敗handler
    @Resource
    private LoginFailureHandler loginFailureHandler;
    
    /**
     * 權(quán)限核心配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //基礎(chǔ)設(shè)置
        http.httpBasic()//配置HTTP基本身份驗(yàn)證
            .and()
                .authorizeRequests()
                .anyRequest().authenticated()//所有請求都需要認(rèn)證
            .and()
                .formLogin() //登錄表單
                .loginPage("/login")//登錄頁面url
                .loginProcessingUrl("/login")//登錄驗(yàn)證url
                .defaultSuccessUrl("/index")//成功登錄跳轉(zhuǎn)
                .successHandler(loginSuccessHandler)//成功登錄處理器
                .failureHandler(loginFailureHandler)//失敗登錄處理器
                .permitAll()//登錄成功后有權(quán)限訪問所有頁面
            .and()
                .rememberMe()//記住我功能
                .userDetailsService(userService)//設(shè)置用戶業(yè)務(wù)層
                .tokenRepository(persistentTokenRepository())//設(shè)置持久化token
                .tokenValiditySeconds(24 * 60 * 60); //記住登錄1天(24小時(shí) * 60分鐘 * 60秒)


        //關(guān)閉csrf跨域攻擊防御
        http.csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //這里要設(shè)置自定義認(rèn)證
        auth.authenticationProvider(loginValidateAuthenticationProvider);
    }

    /**
     * BCrypt加密方式
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 記住我功能,持久化的token服務(wù)
     * @return
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        //數(shù)據(jù)源設(shè)置
        tokenRepository.setDataSource(dataSource);
        //啟動(dòng)的時(shí)候創(chuàng)建表,這里只執(zhí)行一次,第二次就注釋掉,否則每次啟動(dòng)都重新創(chuàng)建表
        //tokenRepository.setCreateTableOnStartup(true);
        return tokenRepository;
    }

}

首先,要想存儲(chǔ)到數(shù)據(jù)庫種,那是需要?jiǎng)?chuàng)建數(shù)據(jù)庫表存儲(chǔ),這里通過tokenRepository.setCreateTableOnStartup(true)方法就可以讓Spring Security自動(dòng)創(chuàng)建數(shù)據(jù)庫表,不過記得下次啟動(dòng)的時(shí)候一定要注釋起來

其次就是在權(quán)限核心配置方法中追加了.rememberMe()的一系列配置。

接下來,在前端登錄頁面上,需要新添加一個(gè)復(fù)選框,然后加上屬性name="remember-me"即可記住我

login.html

<input type="checkbox" name="remember-me"/>

完整代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登錄頁</title>

</head>
<body>

    <h2>登錄頁</h2>
    <form id="loginForm" action="/login" method="post">
        用戶名:<input type="text" id="username" name="username"/><br/><br/>
        密&nbsp;&nbsp;&nbsp;碼:<input type="password" id="password" name="password"/><br/><br/>
        <input type="checkbox" name="remember-me"/>記住我<br/><br/>
        <button id="loginBtn" type="button">登錄</button>
    </form>

<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">

    $("#loginBtn").click(function () {
        $.ajax({
            type: "POST",
            url: "/login",
            data: $("#loginForm").serialize(),
            dataType: "JSON",
            success: function (data) {
                console.log(data);
                //window.location.href = "/index";
            }
        });

    });

</script>
</body>
</html>

開始啟動(dòng)程序,之后打開數(shù)據(jù)庫會(huì)發(fā)現(xiàn)自動(dòng)創(chuàng)建了存儲(chǔ)token的persistent_logins表表:


image.png

然后再看看登錄效果:


image.png

當(dāng)我點(diǎn)擊登錄并登錄成功后,persistent_logins表就多了條信息:


image.png

那么基本代碼和效果也演示完畢了

demo也已經(jīng)放到github,獲取方式在文章的Spring Boot2 + Spring Security5 系列搭建教程開頭篇(1) 結(jié)尾處

如果小伙伴遇到什么問題,或者哪里不明白歡迎評(píng)論或私信,也可以在公眾號(hào)里面私信問都可以,謝謝大家~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容