Spring security记住我基本原理:

登录的时候,请求发送给过滤器UsernamePasswordAuthenticationFilter,当该过滤器认证成功后,会调用RememberMeService,会生成一个token,将token写入到浏览器cookie,同时RememberMeService里边还有个TokenRepository,将token和用户信息写入到数据库中。这样当用户再次访问系统,访问某一个接口时,会经过一个RememberMeAuthenticationFilter的过滤器,他会读取cookie中的token,交给RememberService,RememberService会用TokenRepository根据token从数据库中查是否有记录,如果有记录会把用户名取出来,再调用UserDetailService根据用户名获取用户信息,然后放在SecurityContext里。

RememberMeAuthenticationFilter在Spring Security中认证过滤器链的倒数第二个过滤器位置,当其他认证过滤器都没法认证成功的时候,就会调用RememberMeAuthenticationFilter尝试认证。

实现:

1,登录表单加上<input type="checkbox" name="remember-me" value="true"/>,SpringSecurity在SpringSessionRememberMeServices类里定义了一个常量,默认值就是remember-me

2,根据上边的原理图可知,要配置TokenRepository,把生成的token存进数据库,这是一个配置bean的配置,放在了BrowserSecurityConfig里

3,在configure里配置

4,在BrowserProperties里加上自动登录时间,把记住我时间做成可配置的

//记住我秒数配置
private int rememberMeSeconds = 10;齐活

package com.imooc.security.browser;

@Configuration //这是一个配置
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{ //读取用户配置的登录页配置
@Autowired
private SecurityProperties securityProperties; //自定义的登录成功后的处理器
@Autowired
private AuthenticationSuccessHandler imoocAuthenticationSuccessHandler; //自定义的认证失败后的处理器
@Autowired
private AuthenticationFailureHandler imoocAuthenticationFailureHandler; //数据源
@Autowired
private DataSource dataSource; @Autowired
private UserDetailsService userDetailsService; //注意是org.springframework.security.crypto.password.PasswordEncoder
@Bean
public PasswordEncoder passwordencoder(){
//BCryptPasswordEncoder implements PasswordEncoder
return new BCryptPasswordEncoder();
} /**
* 记住我TokenRepository配置,在登录成功后执行
* 登录成功后往数据库存token的
* @Description: 记住我TokenRepository配置
* @param @return JdbcTokenRepositoryImpl
* @return PersistentTokenRepository
* @throws
* @author lihaoyang
* @date 2018年3月5日
*/
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
//启动时自动生成相应表,可以在JdbcTokenRepositoryImpl里自己执行CREATE_TABLE_SQL脚本生成表
jdbcTokenRepository.setCreateTableOnStartup(true);
return jdbcTokenRepository;
} //版本二:可配置的登录页
@Override
protected void configure(HttpSecurity http) throws Exception {
//验证码过滤器
ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
//验证码过滤器中使用自己的错误处理
validateCodeFilter.setAuthenticationFailureHandler(imoocAuthenticationFailureHandler);
//配置的验证码过滤url
validateCodeFilter.setSecurityProperties(securityProperties);
validateCodeFilter.afterPropertiesSet(); //实现需要认证的接口跳转表单登录,安全=认证+授权
//http.httpBasic() //这个就是默认的弹框认证
//
http //把验证码过滤器加载登录过滤器前边
.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
//表单认证相关配置
.formLogin()
.loginPage("/authentication/require") //处理用户认证BrowserSecurityController
//登录过滤器UsernamePasswordAuthenticationFilter默认登录的url是"/login",在这能改
.loginProcessingUrl("/authentication/form")
.successHandler(imoocAuthenticationSuccessHandler)//自定义的认证后处理器
.failureHandler(imoocAuthenticationFailureHandler) //登录失败后的处理
.and()
//记住我相关配置
.rememberMe()
.tokenRepository(persistentTokenRepository())//TokenRepository,登录成功后往数据库存token的
.tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())//记住我秒数
.userDetailsService(userDetailsService) //记住我成功后,调用userDetailsService查询用户信息
.and()
//授权相关的配置
.authorizeRequests()
// /authentication/require:处理登录,securityProperties.getBrowser().getLoginPage():用户配置的登录页
.antMatchers("/authentication/require",
securityProperties.getBrowser().getLoginPage(),//放过登录页不过滤,否则报错
"/verifycode/image").permitAll() //验证码
.anyRequest() //任何请求
.authenticated() //都需要身份认证
.and()
.csrf().disable() //关闭csrf防护
;
}
}

其中由于要和数据库打交道,所以需要注入一个数据源:application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/imooc-demo
spring.datasource.username=root
spring.datasource.password=root

启动应用,访问 localhost:8080/user,需要登录

登录成功:

数据库:生成一个persistent_logins表,存进去了一条数据

停止服务,从新启动(注释掉生成保存token表的jdbcTokenRepository.setCreateTableOnStartup(true);)因为我们的用户登录信息都存在了session中,所以重启服务后,再访问localhost:8080/user,本应该重新引导到登录页,但是由于配置了记住我,所以能够直接访问,拿到了接口数据

请求头:

至此基本的rememberMe已做好

完整代码放在了github:https://github.com/lhy1234/spring-security

打个广告

最近在玩今日头条头条号,录一些北京打工生活,想看的请搜索“北漂小阳”点击关注

Spring Security构建Rest服务-0900-rememberMe记住我的更多相关文章

  1. Spring Security构建Rest服务-1300-Spring Security OAuth开发APP认证框架之JWT实现单点登录

    基于JWT实现SSO 在淘宝( https://www.taobao.com )上点击登录,已经跳到了 https://login.taobao.com,这是又一个服务器.只要在淘宝登录了,就能直接访 ...

  2. Spring Security构建Rest服务-1202-Spring Security OAuth开发APP认证框架之重构3种登录方式

    SpringSecurityOAuth核心源码解析 蓝色表示接口,绿色表示类 1,TokenEndpoint 整个入口点,相当于一个controller,不同的授权模式获取token的地址都是 /oa ...

  3. Spring Security构建Rest服务-0702-短信验证码登录

    先来看下 Spring Security密码登录大概流程,模拟这个流程,开发短信登录流程 1,密码登录请求发送给过滤器 UsernamePasswordAuthenticationFilter 2,过 ...

  4. Spring Security构建Rest服务-1001-spring social开发第三方登录之spring social基本原理

    OAuth协议是一个授权协议,目的是让用户在不将服务提供商的用户名密码交给第三方应用的条件下,让第三方应用可以有权限访问用户存在服务提供商上的资源. 接着上一篇说的,在第三方应用获取到用户资源后,如果 ...

  5. Spring Security构建Rest服务-1201-Spring Security OAuth开发APP认证框架之实现服务提供商

    实现服务提供商,就是要实现认证服务器.资源服务器. 现在做的都是app的东西,所以在app项目写代码  认证服务器: 新建 ImoocAuthenticationServerConfig 类,@Ena ...

  6. Spring Security构建Rest服务-1200-SpringSecurity OAuth开发APP认证框架

    基于服务器Session的认证方式: 前边说的用户名密码登录.短信登录.第三方登录,都是普通的登录,是基于服务器Session保存用户信息的登录方式.登录信息都是存在服务器的session(服务器的一 ...

  7. Spring Security构建Rest服务-1401-权限表达式

    Spring Security 的权限表达式 用法,在自定义的BrowserSecurityConfig extends WebSecurityConfigurerAdapter 配置文件里,每一个a ...

  8. Spring Security构建Rest服务-1205-Spring Security OAuth开发APP认证框架之Token处理

    token处理之二使用JWT替换默认的token JWT(Json Web Token) 特点: 1,自包含:jwt token包含有意义的信息 spring security oauth默认生成的t ...

  9. Spring Security构建Rest服务-1204-Spring Security OAuth开发APP认证框架之Token处理

    token处理之一基本参数配置 处理token时间.存储策略,客户端配置等 以前的都是spring security oauth默认的token生成策略,token默认在org.springframe ...

随机推荐

  1. s28 LNMP架构服务搭建

    nginx-location使用 location语法 location使用的语法例子为: location [=|~|~*|^~] uri{ 对location语法列表说明. |1ocation | ...

  2. UVa 11464 Even Parity (二进制法枚举)

    题意:给你一个n*n的01矩阵,让你把最少的0变成1,使得每个元素的上,下,左,右的元素(如果有的话)之和均为偶数. 析:最好想的的办法就是暴力,就是枚举每个数字是变还是不变,但是...时间复杂度也太 ...

  3. js函数预编译

    function fn(a){ console.log(a); var a = 123; function a(){} console.log(a); var b = function(){} con ...

  4. 浅析基于AXIS框架的WebService

    一.写在前面 之前做项目用到了基于Axis的WebService,为了更进一步的理解和记忆,在这里通过代码实践和源码分析来完整的做一遍Axis的WebService以及对应的客户端调用实践,并和其它的 ...

  5. (二进制 异或)Team Formation --ZOJ --3870

    链接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3870 http://acm.hust.edu.cn/vjudge/ ...

  6. 使用ABP框架踩过的坑系列1

        企业级(例如ERP)应用, 一遍一遍的在重复:认证.验证.异常处理.日志.国际化和本地化.数据库连接管理.配置管理. 审计记录等,同时.NET有很多最佳实践:分层.模块化.DDD领域驱动.DI ...

  7. application/force-download 不生效

    不管用什么方式都无法下载txt 设置application/force-download也不生效 很无奈 胡搞瞎搞 最终解决方案:但是没搞明白什么原理 问题解决 @RequestMapping(val ...

  8. uwp ListView列表滑动特效

    在看过一篇文章 WPF自定义控件之列表滑动特效 PowerListBox  http://www.cnblogs.com/ShenNan/p/4993374.html#3619585 实现了滑动的特效 ...

  9. s11 day 102 python Linux环境安装 与路飞项目 微信平台接口

    1.微信公众号平台沙箱环境地址 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login 二.结算中心业务 结算中心: -购物车,删 ...

  10. leetcode 121. 买卖股票的最佳时机 JAVA

    题目: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润. 注意你不能在买入股票前卖出股票 ...