Spring Boot2 + Spring Security5 记住我功能(4)

前言

上篇文章介绍了Spring Boot Security配置了自定义登录
本篇文章,小编会介绍实现记住我功能

开始

Spring Security记住我功能,其实就是就是当用户勾选了"记住我"然后成功认证登录了,那在有效时间内免登录直接进入
那么,Spring Security实现记住我的方式有两种:

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

这里小编简单的说下流程,当Spring Security用户登录成功的时候,它会生成授权信息(token)
然后方法一的话,Spring Security会把token传输到用户本地浏览器cookie里面存储起来
方法二的话就是把token存入数据库中,那么相信大家也就清楚了

像token这种敏感的数据,是不建议暴露用户那边的,因为这样很容易会被中间人劫持,又或者被伪造请求(CSRF),所以小编是建议使用第二种办法

那么下面开始展示实现代码,,我们继上篇的代码,在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 {

    //数据源
    @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/>&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>

开始启动程序,之后打开数据库会发现自动创建了存储token的persistent_logins表表:
在这里插入图片描述
然后再看看登录效果:
在这里插入图片描述
当我点击登录并登录成功后,persistent_logins表就多了条信息:
在这里插入图片描述
那么基本代码和效果也演示完毕了

demo也已经放到github,获取方式在文章的Spring Boot2 + Spring Security5 系列搭建教程开头篇(1) 结尾处

如果小伙伴遇到什么问题,或者哪里不明白欢迎评论或私信,也可以在公众号里面私信问都可以,谢谢大家~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值