文章目录

  • 一、修改login.html
  • 二、两种实现方式
    • 2.1 Cookie 存储
    • 2.2 数据库存储
      • 2.2.1 基本原理
      • 2.2.2 代码实现
  • 三、运行程序

在上一章:SpringBoot集成Spring Security(1)——第一章,我们实现了入门程序,本篇为该程序加上自动登录的功能。

代码地址:https://github.com/FadeHub/spring-boot-learn/tree/master/spring-boot-security-2

一、修改login.html

在登陆页添加自动登录的选项,注意自动登录字段的 name 必须是 remember-me :

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>登陆</title>
</head>
<body>
<h1>登陆</h1>
<form method="post" action="/login"><div>用户名:<input type="text" name="username"></div><div>密码:<input type="password" name="password"></div><div><label><input type="checkbox" name="remember-me"/>自动登录</label><button type="submit">立即登陆</button></div>
</form>
</body>
</html>

二、两种实现方式

2.1 Cookie 存储

这种方式十分简单,只要在 WebSecurityConfig 中的 configure() 方法添加一个 rememberMe() 即可,如下所示:

protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login")// 设置登陆成功页.defaultSuccessUrl("/").permitAll().and()// 自定义登陆用户名和密码参数,默认为username和password// .usernameParameter("username")//  .passwordParameter("password").logout().permitAll()//基于内存自动登录.and().rememberMe();http.csrf().disable();}

当我们登陆时勾选自动登录时,会自动在 Cookie 中保存一个名为 remember-me 的cookie,默认有效期为2周,其值是一个加密字符串:

2.2 数据库存储

使用 Cookie 存储虽然很方便,但是大家都知道 Cookie 毕竟是保存在客户端的,而且 Cookie 的值还与用户名、密码这些敏感数据相关,虽然加密了,但是将敏感信息存在客户端,毕竟不太安全。

Spring security 还提供了另一种相对更安全的实现机制:在客户端的 Cookie 中,仅保存一个无意义的加密串(与用户名、密码等敏感数据无关),然后在数据库中保存该加密串-用户信息的对应关系,自动登录时,用 Cookie 中的加密串,到数据库中验证,如果通过,自动登录才算通过。

2.2.1 基本原理

当浏览器发起表单登录请求时,当通过 UsernamePasswordAuthenticationFilter 认证成功后,会经过 RememberMeService,在其中有个 TokenRepository,它会生成一个 token,首先将 token 写入到浏览器的 Cookie 中,然后将 token、认证成功的用户名写入到数据库中。

当浏览器下次请求时,会经过 RememberMeAuthenticationFilter,它会读取 Cookie 中的 token,交给 RememberMeService 从数据库中查询记录。如果存在记录,会读取用户名并去调用 UserDetailsService,获取用户信息,并将用户信息放入Spring Security 中,实现自动登陆。

RememberMeAuthenticationFilter 在整个过滤器链中是比较靠后的位置,也就是说在传统登录方式都无法登录的情况下才会使用自动登陆。

2.2.2 代码实现

首先需要创建一张表来存储 token 信息:

CREATE TABLE `persistent_logins` (`username` varchar(64) NOT NULL,`series` varchar(64) NOT NULL,`token` varchar(64) NOT NULL,`last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在 WebSecurityConfig 中注入 dataSource ,创建一个 PersistentTokenRepository 的Bean:

@Autowired
private DataSource dataSource;@Beanpublic PersistentTokenRepository persistentTokenRepository(){JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();tokenRepository.setDataSource(dataSource);// 如果token表不存在,使用下面语句可以初始化该表;若存在,请注释掉这条语句,否则会报错。
//        tokenRepository.setCreateTableOnStartup(true);return tokenRepository;}

在 config() 中按如下所示配置自动登陆:

@Override
protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()// 如果有允许匿名的url,填在下面
//                .antMatchers().permitAll().anyRequest().authenticated().and()// 设置登陆页.formLogin().loginPage("/login")// 设置登陆成功页.defaultSuccessUrl("/").permitAll()// 自定义登陆用户名和密码参数,默认为username和password
//                .usernameParameter("username")
//                .passwordParameter("password").and().logout().permitAll()// 自动登录.and().rememberMe().tokenRepository(persistentTokenRepository())// 有效时间:单位s.tokenValiditySeconds(60).userDetailsService(userDetailsService);// 关闭CSRF跨域http.csrf().disable();
}

三、运行程序

勾选自动登录后,Cookie 和数据库中均存储了 token 信息:

SpringBoot集成Spring Security —— 第二章自动登录相关推荐

  1. SpringBoot集成Spring Security(一)登录注销

    同个人网站 https://www.serendipper-x.cn/,欢迎访问 ! SpringBoot集成Spring Security(二)注册 .密码加密.修改密码 写在前面 Spring S ...

  2. SpringBoot集成Spring Security(二)注册 、密码加密、修改密码

    SpringBoot集成Spring Security(一)登录注销 写在前面 上一节创建了项目并且利用Spring Security完成了登录注销功能,这里继续说一下注册.密码加密和找回密码,代码注 ...

  3. SpringBoot集成Spring Security(2)——自动登录

    在上一章:SpringBoot集成Spring Security(1)--入门程序中,我们实现了入门程序,本篇为该程序加上自动登录的功能. 文章目录 一.修改login.html 二.两种实现方式 2 ...

  4. SpringBoot 集成 Spring Security

    Spring Security Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架.它实际上是保护基于spring的应用程序的标准. Spring Security是一个 ...

  5. springboot集成Spring Security oauth2(八)

    由于公司项目需要,进行SpringBoot集成Spring Security oauth2,几乎搜寻网上所有大神的案例,苦苦不能理解,不能完全OK. 以下是借鉴各大神的代码,终于demo完工,请欣赏 ...

  6. springBoot整合spring security+JWT实现单点登录与权限管理前后端分离

    在前一篇文章当中,我们介绍了springBoot整合spring security单体应用版,在这篇文章当中,我将介绍springBoot整合spring secury+JWT实现单点登录与权限管理. ...

  7. springBoot整合spring security+JWT实现单点登录与权限管理前后端分离--筑基中期

    写在前面 在前一篇文章当中,我们介绍了springBoot整合spring security单体应用版,在这篇文章当中,我将介绍springBoot整合spring secury+JWT实现单点登录与 ...

  8. springboot集成spring security实现登录和注销

    文章目录 一.导入坐标 二.Users实体类及其数据库表的创建 三.controller,service,mapper层的实现 四.核心–编写配置文件 五.页面的实现 运行结果 一.导入坐标 < ...

  9. SpringBoot集成Spring Security(3)——异常处理

    源码地址:https://github.com/jitwxs/blog_sample 文章目录 一.常见异常 二.源码分析 三.处理异常 不知道你有没有注意到,当我们登陆失败时候,Spring sec ...

最新文章

  1. 经典的Java基础面试题集锦
  2. Fedora15上实现桌面背景图片渐变
  3. 使用BCH提供的Cryptonize创建自己的加密代币
  4. ajax为什么会全局刷新,为什么发送ajax请求页面也会刷新呢?
  5. stm32无法进入串口接收中断
  6. Flume日志收集系统架构详解--转
  7. Go中bytes.Buffer理解
  8. php create database,sql create database 创建数据库命令
  9. python语言学习零基础教学视频_Python告白小白视频教程(零基础入门)
  10. Mac电脑上非常好用的英汉互译词典软件
  11. 【渝粤题库】广东开放大学 JavaScript 形成性考核
  12. 公有云和私有云,你了解吗?
  13. 互联网早报:哈啰科技发布新款助力车“白鸥”、小哈能量站等多款新产品
  14. 计算机芯片英文翻译,芯片的英文翻译,芯片英语怎么说
  15. #Paper Reading# Efficient Heterogeneous Collaborative Filtering without NS for Recommendation
  16. Java实现合并word文档并打开合并后文档
  17. Nginx sendfile作用
  18. ✔B【OPA1602 】【双运放】高性能 低噪声 极低失真度运放模块 35MHz带宽
  19. js es6转es5
  20. Office Excel VBA遇到的坑

热门文章

  1. 基于VC++开发串口通信的方法
  2. sql group by having用法_神奇的 SQL 为什么 GROUP BY 之后不能直接引用原表中的列?...
  3. mysql sshd_制作Docker镜像之mysqlkeepalivedsshd
  4. luogu p3515 Lightning Conductor
  5. 【Python】4500字、10个案例分享几个Python可视化小技巧,助你绘制高质量图表
  6. 全球首届“AI球球大作战:Go-Bigger多智能体决策智能挑战赛”开启
  7. 【深度学习】收藏|神经网络调试Checklist
  8. Tensorlfow2.0 二分类和多分类focal loss实现和在文本分类任务效果评估
  9. 时间序列里面最强特征之一
  10. 点击率预估又有新花样?