目录:
一、概念
自动登录是我们在软件开发时一个非常常见的功能,例如我们登录 QQ时,登录界面会有记住密码这个功能,下次进入qq会进行自动登录。
浏览器的自动登录是指用户在登录成功后,在某一段时间内,如果用户关闭了浏览器并重新打开,或者服务器重启了,都不需要用户重新登录了,用户依然可以直接访问接口数据。
那么应该如何实现呢,其实spring security已经提供了相应的支持。
二、实现
实战:
(1)创建spring工程,引入web和security的依赖。
pom.xml如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
(2)创建security配置类,在配置授权路径时添加 .rememberMe() 和 .key(“自定义”)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("fyf")
.roles("admin")
.password("123");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.rememberMe()
//key的作用:后端服务器重启,用户的自动登录不受影响,默认情况,服务器一重启,前端要重新登录
.key("250")
.and()
.csrf()
.disable();
}
}
(3)测试controller
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello";
}
}
(4)测试。
输入http://localhost:8080/hello,默认的登录页面多了一个选项,就是记住我。接着我们输入用户名密码,并且勾选上记住我这个框,然后点击登录按钮执行登录操作,/hello接口访问成功;
然后关闭浏览器直接访问http://localhost:8080/hello,无需登录直接访问成功。
最后我们可以将服务器重启,再来访问hello接口,也是无需登录直接访问成功。
三、原理:
我们在登录时的表单提交参数如下,如果你的登录页面是自定义登录页面,则添加上RememberMe的key-value即可。
此外,登录成功之后,就会自动跳转到 hello 接口了。注意,系统访问 hello 接口的时候,携带的 cookie:
remember-me类似于一个token,当你登录成功后每次请求都会携带这个key,后端会判断你是哪个用户。remember-me是经过base64编码且通过md5加密过后的字符串,格式如下:
username + “:” + tokenExpiryTime + “:” + password + “:” + key
此时,有人会想一旦令牌丢失,别人就可以拿着这个令牌随意登录我们的系统了,这是一个非常危险的操作。所以我们还要进行自动登录的安全优化。
那么如何让我们的 RememberMe 功能更加安全呢?
可以采用 二次校验或者持久化令牌 来解决。
参考:安全优化