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. VS2010/MFC编程(对话框:模态对话框及其弹出过程)

    讲讲什么是模态对话框和非模态对话框,以及模态对话框怎样弹出. 一.模态对话框和非模态对话框 Windows对话框分为两类:模态对话框和非模态对话框. 模态对话框是这样的对话框,当它弹出后,本应用程序其 ...

  2. mysql图文安装教程(win7 32位 亲测)

    一.下载mysql:http://www.mysql.com/downloads/ 弹出: 你需要有一个 Oracle Web 帐户,没有的话,注册一个: 勾选许可: 输入搜索条件: 下载MySQL ...

  3. html5获取当前的位置..在地图中

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  4. Oracle sql 优化の常用方式

    1.不要用 '*' 代替所有列名,特别是字段比较多的情况下 使用select * 可以列出某个表的所有列名,但是这样的写法对于Oracle来说会存在动态解析问题.Oracle系统通过查询数据字典将 ' ...

  5. Team Foundation Server 开发流程管理管理研讨会

    这周,和微软公司的朋友一起,受北京某金融企业邀请,为企业软件部门一个70多人的软件团队提供了一场基于Team Foundation Server的软件软件流程的技术研讨会.在研讨会中,培训基于微软Te ...

  6. Android蓝牙联机Demo解析

    写在前面: 手游的双人对战实现方式有很多,比如: 联网对战(需要一个服务器负责转发客户端请求,各种大型手游的做法) 分屏对战(手机上下分屏,典型的例子就是切水果的双人对战) 蓝牙联机对战(通过蓝牙联机 ...

  7. 设计模式之适配器模式(Adapter Pattern)

    在正式开始之前,让我们先思考几个问题: 如果现有的新项目可以利用旧项目里大量的遗留代码,你打算从头开始完成新项目还是去了解旧项目的模块功能以及接口? 如果你了解过遗留代码之后,发现有几个重要的功能模块 ...

  8. 常用到的一些js方法,记录一下

    获取字符串长度 function GetStringLength(str) { return str.replace(/[^\x00-\xff]/g, "00").length; ...

  9. WebAPI的AuthorizeAttribute扩展类中获取POST提交的数据

    在WEBAPI中,AuthorizeAttribute类重写时,如何获取post数据是个难题,网上找资料也不好使,只能自己研究,通过研究发现,WEBAPI给了我们获取POST数据的可能,下面介绍一下: ...

  10. 先装VS2008之后,又装了2013,然后启动VS2008提示“Tools Version”有问题?

    这个网上资料一搜很多,我就是按照下面这个链接去解决的,删除 “14.0” 整个键值文件夹之后重启VS2008就好了, 注意:上面第一张图是我在网上找的08和10版本弹出的错误,我自己弹出的是提示14. ...