对于最新的稳定版本,请使用 Spring Security 7.0.4spring-doc.cadn.net.cn

使用WebFlux应用程序入门

这节内容涵盖了如何在响应式应用中使用Spring Security与Spring Boot的最小配置。spring-doc.cadn.net.cn

The completed application can be found 在我们的示例仓库中。 For your convenience, you can download a minimal Reactive Spring Boot + Spring Security 应用程序 点击这里spring-doc.cadn.net.cn

更新依赖项

您可以将Spring Security 添加到您的Spring Boot 项目中,通过添加spring-boot-starter-securityspring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
    implementation 'org.springframework.boot:spring-boot-starter-security'

开始 Hello Spring Security Boot

现在,您可以使用Maven插件的https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-running-with-the-maven-plugin 目标来 运行Spring Boot应用程序。 以下示例展示了如何执行此操作(以及执行后的初始输出):spring-doc.cadn.net.cn

运行 Spring Boot 应用程序
$ ./mvnw spring-boot:run
...
INFO 23689 --- [  restartedMain] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336

...
$ ./gradlew bootRun
...
INFO 23689 --- [  restartedMain] .s.s.UserDetailsServiceAutoConfiguration :

Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336

...

正在认证

您可以通过访问 localhost:8080/ 来使用应用程序,这将把浏览器重定向到默认登录页面。您可以使用默认用户名 user 和随机生成的密码进行登录,该密码会记录在控制台上。然后浏览器会被导向最初请求的页面。spring-doc.cadn.net.cn

要注销,请访问 http://localhost:8080/logout,然后确认您希望注销。spring-doc.cadn.net.cn

Spring Boot 自动配置

Spring Boot 自动添加了 Spring Security,这要求所有请求必须进行身份验证。此外,它还会生成一个用户并为其随机生成一个密码,该密码会记录在控制台中,可以使用表单或基础身份验证方式对其进行认证。spring-doc.cadn.net.cn