前言
上篇文章介绍了Spring Boot Security配置了自定义登录 本篇文章,博主会介绍实现记住我功能
开始
Spring Security记住我功能,其实就是就是当用户勾选了"记住我"然后成功认证登录了,那在有效时间内免登录直接进入 那么,Spring Security实现记住我的方式有两种:
- 1.本地存储(cookie)
- 2.持久化存储
这里博主简单的说下流程,当Spring Security用户登录成功的时候,它会生成授权信息(token) 然后方法一的话,Spring Security会把token传输到用户本地浏览器cookie里面存储起来 方法二的话就是把token存入数据库中,那么相信大家也就清楚了
像token这种敏感的数据,是不建议暴露用户那边的,因为这样很容易会被中间人劫持,又或者被伪造请求(CSRF),所以博主是建议使用第二种办法
那么下面开始展示实现代码,,我们继上篇的代码,在Spring Security配置类上添加持久化配置:
/**
* Copyright 2020. javaymw.com Studio All Right Reserved
* <p>
* Create on 2020-06-05 21:58
* Created by zhaoxinguo
* Version 2.0.0
*/
package com.javaymw.demo.config;
import com.javaymw.demo.core.LoginValidateAuthenticationProvider;
import com.javaymw.demo.core.handler.LoginFailureHandler;
import com.javaymw.demo.core.handler.LoginSuccessHandler;
import com.javaymw.demo.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;
/**
* @description: Spring Security 核心配置类
* @author zhaoxinguo
* @date 2020/6/5 21:57
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//数据源
@Resource
private DataSource dataSource;
//用户业务层
@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)//设置用户业务
.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();
//数据源设置
tokenRepository.setDataSource(dataSource);
//启动的时候创建表,这里只执行一次,第二次就注释掉,否则每次启动都重新创建表
tokenRepository.setCreateTableOnStartup(true);
return tokenRepository;
}
}
首先,要想存储到数据库种,那是需要创建数据库表存储,这里通过tokenRepository.setCreateTableOnStartup(true)方法就可以让Spring Security自动创建数据库表,不过记得下次启动的时候一定要注释起来
其次就是在权限核心配置方法中追加了.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>
$("#loginBtn").click(function () {
$.ajax({
type: "POST",
url: "/login",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (data) {
console.log(data);
//window.location.href = "/index";
}
});
});
</body>
</html>
开始启动程序,之后打开数据库会发现自动创建了存储token的persistent_logins表:
然后再看看登录效果:
当我点击登录并登录成功后,persistent_logins表就多了条信息:
那么基本代码和效果也演示完毕了
源码获取方式加加入QQ交流群(660164226),进群找群主要源码,如果有问题,可以提出疑问,群主会尽量帮助解决~
希望能帮助到大家,如果有不好或者错误的地方希望能多多提出,谢谢大家~
注意:本文归作者所有,未经作者允许,不得转载