spring-security 实现记住我,免登录 - Hash-Based Token
介绍
先贴一个官方介绍:
https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#remember-me
“记住我”,这个功能有两种实现形式,一种是将token保存在Hash中,即 Simple Hash-Based Token Approach。
一种是将token保存在数据库中,即 Persistent Token Approach。
因 Simple Hash-Based Token Approach 存在安全隐患,因此并不推荐。但这里仍然介绍下其实现。
当用户登录成功后,服务器则会向浏览器发送一个cookie。此cookie的生成方式为
base64(username + ":" + expirationTime + ":" +
md5Hex(username + ":" + expirationTime + ":" password + ":" + key))
key: 防止修改令牌的私钥
cookie会有一个过期时间,在没有过期之前,用户名、密码和key都不会改变,所以如果有人劫持到cookie,则能够
登录你的帐号,你只有改变密码,这个cookie才会失效。
相关文章
spring-security 实现记住我,免登录 - Persistent Token
练习
使用IDEA新建Maven项目
修改pom.xml,引入Spring Boot
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sqber</groupId>
<artifactId>RememberMeHashBased</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
</dependencies>
</project>
创建控制器和视图
我们创建一个简单的 HomeController
package com.sqber.hashbased.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home/index";
}
@GetMapping("/login")
public String login() {
return "home/login";
}
}
一个首页,一个登录页
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Security with Spring Boot</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>登录</title>
</head>
<body>
<div th:if="${param.error}">
<h1 style="color:red">用户名或密码错误</h1>
</div>
<div th:if="${param.logout}">
<h1 style="color:blue">退出登录</h1>
</div>
<form th:action="@{/login}" method="post">
<div>用户名: <input type="text" name="username"/> </div>
<div>密码: <input type="password" name="password"/> </div>
<div>记住我: <input type="checkbox" name="remember-me" /> </div>
<div><input type="submit" value="登录"/></div>
</form>
</body>
</html>
Security 配置
我们只配置一个 user 用户,且密码也为 user
package com.sqber.hashbased.config;
import org.springframework.beans.factory.annotation.Autowired;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.rememberMe()
.key("uniqueAndSecret")
.rememberMeCookieName("remember-me")
.tokenValiditySeconds(24 * 60 * 60) //1天
.and()
.logout()
.deleteCookies("JSESSIONID")
.permitAll();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password(new BCryptPasswordEncoder().encode("user")).roles("USER");
}
}
注意配置 BCryptPasswordEncoder,否则会报错:There is no PasswordEncoder mapped for the id “null”
查看效果
在浏览器中打开 localhost:8080 ,则会跳转到 login 页面。 输入 user,user 后,并选择 记住我 ,登录。
我们会看到两个 cookie
删除掉 JSESSIONID 这个cookie后,重新刷新,不会跳转到登录页。
完。
*昵称:
*邮箱:
个人站点:
*想说的话: