Spring Boot Security5 記住我功能(4)

前言

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

開始

Spring Security記住我功能铐尚,其實就是就是當用戶勾選了"記住我"然后成功認證登錄了竟纳,那在有效時間內免登錄直接進入
那么稠曼,Spring Security實現(xiàn)記住我的方式有兩種:

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

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

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

那么下面開始展示實現(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è)務層
    @Resource
    private UserService userService;

    //自定義認證
    @Resource
    private LoginValidateAuthenticationProvider loginValidateAuthenticationProvider;

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

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


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

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

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

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

}

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

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

接下來秩霍,在前端登錄頁面上篙悯,需要新添加一個復選框,然后加上屬性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>

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


image.png

然后再看看登錄效果:


image.png

當我點擊登錄并登錄成功后鸽照,persistent_logins表就多了條信息:


image.png

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

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

如果小伙伴遇到什么問題颠悬,或者哪里不明白歡迎評論或私信矮燎,也可以在公眾號里面私信問都可以,謝謝大家~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末赔癌,一起剝皮案震驚了整個濱河市诞外,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌灾票,老刑警劉巖峡谊,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡既们,警方通過查閱死者的電腦和手機濒析,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來贤壁,“玉大人悼枢,你說我怎么就攤上這事埠忘∑⒉穑” “怎么了?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵莹妒,是天一觀的道長名船。 經(jīng)常有香客問我,道長旨怠,這世上最難降的妖魔是什么渠驼? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮鉴腻,結果婚禮上迷扇,老公的妹妹穿的比我還像新娘。我一直安慰自己爽哎,他們只是感情好蜓席,可當我...
    茶點故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著课锌,像睡著了一般厨内。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上渺贤,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天雏胃,我揣著相機與錄音,去河邊找鬼志鞍。 笑死瞭亮,一個胖子當著我的面吹牛,可吹牛的內容都是我干的固棚。 我是一名探鬼主播统翩,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼玻孟!你這毒婦竟也來了唆缴?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤黍翎,失蹤者是張志新(化名)和其女友劉穎面徽,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡趟紊,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年氮双,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片霎匈。...
    茶點故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡戴差,死狀恐怖,靈堂內的尸體忽然破棺而出铛嘱,到底是詐尸還是另有隱情暖释,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布墨吓,位于F島的核電站球匕,受9級特大地震影響,放射性物質發(fā)生泄漏帖烘。R本人自食惡果不足惜亮曹,卻給世界環(huán)境...
    茶點故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望秘症。 院中可真熱鬧照卦,春花似錦、人聲如沸乡摹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽趟卸。三九已至蹄葱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锄列,已是汗流浹背图云。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留邻邮,地道東北人竣况。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像筒严,于是被迫代替她去往敵國和親丹泉。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,941評論 2 355