梦入琼楼寒有月,行过石树冻无烟

Spring security 自动登录

自动登录在很多登入页面中都有一定的需求和存在,有时候处于站点的相关密码安全等级设置,所以会要求用户在输入密码的时候要大于或等于多少个数字或字母,有的甚至会要求大小写和一些符号混合。这就会改变我们经常使用的密码,比如我经常使用的密码是wwcx2022.,但该站点所要求的密码规范是大小写,所以就会改变成Wwcx2022.,有的甚至会要求不允许密码符号,如钟山计算机端口安全联合漏洞共享平台中的前端和后端验证都不允许标点符号的存在。
所以在登录的时候会多个密码进行重试,有的甚至会选择忘记密码而增加站点的处理,为减少用户重新提交表单和加程序处理的频率,在系统开发之中会要求用户记住密码(俗称自动登录)的功能体验,这样做的唯一好处就是可以减少程序的处理数量和给用户带来便利,本文我们使用Spring security来实现自动登录,当然还有一些使用数据库来实现的自动登录,网上有很多文章可以用于实现,读者可自行进行学习,在项目开发的过程中,我们一般建议较少的使用数据库,减少系统资源。

DemoApplication.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class DemoApplication {

@GetMapping("/")
public String index() {
return "The is Spring security world!";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

}

WebSecurityConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin()
.and()
.rememberMe()
.userDetailsService(userDetailsService)
.and()
.csrf().disable();
}

}
⬅️ Go back