前言
上篇文章介紹了Spring Boot Security配置了自定義登錄
本篇文章蒋譬,小編會介紹實現(xiàn)記住我功能
開始
Spring Security記住我功能铐尚,其實就是就是當用戶勾選了"記住我"然后成功認證登錄了竟纳,那在有效時間內免登錄直接進入
那么稠曼,Spring Security實現(xiàn)記住我的方式有兩種:
- 本地存儲(cookie)
- 持久化存儲
這里小編簡單的說下流程僻族,當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/>
密 碼:<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表表:
然后再看看登錄效果:
當我點擊登錄并登錄成功后鸽照,persistent_logins表就多了條信息:
那么基本代碼和效果也演示完畢了
demo也已經(jīng)放到github,獲取方式在文章的Spring Boot2 + Spring Security5 系列搭建教程開頭篇(1) 結尾處
如果小伙伴遇到什么問題颠悬,或者哪里不明白歡迎評論或私信矮燎,也可以在公眾號里面私信問都可以,謝謝大家~