【pom.xml】
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
【/resources/public/login.html】
<!DOCTYPE html>
<html>
<head>
<title>Spring Security Example </title>
</head>
<body>
<form action="/security/login2" method="get">
<div><label> User Name : <input type="text" name="username" value="user"/> </label></div>
<div><label> Password: <input type="password" name="password" value="123"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
【SecurityConfig.java】
package com.chz.mySpringSecurity.config;
import com.chz.mySpringSecurity.filter.AccessTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private AccessTokenFilter accessTokenFilter;
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
//访问"/"和"/home"路径的请求都允许
.antMatchers(
"/", // 这个会跳转到主页,要放过
"/home", // 这是主页的地址,要放过
"/security/login2" // 这个是提交登录的地址,要放过
)
.permitAll()
//而其他的请求都需要认证
.anyRequest()
.authenticated()
.and()
//修改Spring Security默认的登陆界面
.formLogin()
.loginPage("/security/login") // 登录地址是【/security/login】
.permitAll()
.and()