1、创建SpringBoot项目,并引入SpringSecurity
pom.xml
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/>
</parent>
<groupId>org.example</groupId>
<artifactId>spring_security_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
</project>
2、创建测试类
TestController.java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class TestController {
@GetMapping("test")
public String test() {
return "hello world";
}
}
3、启动项目
4、访问测试接口并验证
http://localhost:8080/test
1、浏览器访问http://localhost:8080/test后,页面重定向到了:http://localhost:8080/login。这是因为SpringSecurity默认所有请求必须登录后才可以访问。
2、在未登录状态访问时,页面会重定向到SpringSecurity提供的默认登录页。
3、SpringSecurity默认提供的账号是:user
4、SpringSecurity默认提供的密码是:在应用启动时,控制台会输出的一个由UUID生产的随机密码。在第3步中,用红色框选中部分。
5、点击“Sign in”后,显示测试请求成功