Hello Spring Security
本部分涵盖如何将 Spring Security 与 Spring Boot 配合使用的最小设置,然后在此基础上指导您采取后续步骤。
This section covers the minimum setup for how to use Spring Security with Spring Boot and then points you to next steps after that.
可以在 我们的示例存储库 中找到已完成的启动应用程序。出于方便,您可以 prepared by Spring Initializr下载一个最小的 Spring Boot + Spring Security 应用程序。 The completed starter application can be found in our samples repository. For your convenience, you can download a minimal Spring Boot + Spring Security application prepared by Spring Initializr. |
Starting Hello Spring Security Boot
使用 Spring Security on the classpath,您现在可以 运行 Spring Boot 应用程序。以下代码段显示了指示应用程序中已启用 Spring Security 的部分输出:
With Spring Security servlet-hello-dependencies, you can now run the Spring Boot application. The following snippet shows some of the output that indicates that Spring Security is enabled in your application:
-
Maven
-
Gradle
-
Jar
$ ./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
...
$ java -jar target/myapplication-0.0.1.jar
...
INFO 23689 --- [ restartedMain] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
...
现在您已运行它,可以尝试访问一个端点,看看会发生什么。如果您访问不带凭据的端点,如下所示:
Now that you have it running, you might try hitting an endpoint to see what happens. If you hit an endpoint without credentials like so:
$ curl -i http://localhost:8080/some/path
HTTP/1.1 401
...
那么 Spring Security 将通过 401 Unauthorized
拒绝访问。
then Spring Security denies access with a 401 Unauthorized
.
如果您在浏览器中提供了相同的 URL,它将会重定向到默认登录页面。 |
If you provide the same URL in a browser, it will redirect to a default login page. |
如果您访问带凭据(在控制台输出中找到)的端点,如下所示:
And if you hit an endpoint with credentials (found in the console output) as follows:
$ curl -i -u user:8e557245-73e2-4286-969a-ff57fe326336 http://localhost:8080/some/path
HTTP/1.1 404
...
那么 Spring Boot 将处理请求,在这种情况下返回 404 Not Found
,因为 /some/path
不存在。
then Spring Boot will service the request, returning a 404 Not Found
in this case since /some/path
doesn’t exist.
在此基础上,您可以:
From here, you can:
-
更好地了解 what Spring Boot enables in Spring Security by default
-
Better understand servlet-hello-auto-configuration
-
阅读 Spring Security 有助于 common use cases
-
Read about security-use-cases that Spring Security helps with
-
Start configuring authentication
Runtime Expectations
Spring Boot 和 Spring Security 的默认设置在运行时提供了以下行为:
The default arrangement of Spring Boot and Spring Security affords the following behaviors at runtime:
-
需要认证的用户 for any endpoint(包括 Boot 的 `/error`端点)
-
Requires an authenticated user for any endpoint (including Boot’s
/error
endpoint) -
Registers a default user 在启动时生成密码(密码记录到控制台;在前面的示例中,密码是
8e557245-73e2-4286-969a-ff57fe326336
) -
Registers a default user with a generated password at startup (the password is logged to the console; in the preceding example, the password is
8e557245-73e2-4286-969a-ff57fe326336
) -
保护 password storage with BCrypt 及其他
-
Protects password storage with BCrypt as well as others
-
认证 form-based login 以及 HTTP Basic
-
Authenticates form-based login as well as HTTP Basic
-
提供内容协商;对于 Web 请求,重定向到登录页面;对于服务请求,返回
401 Unauthorized
-
Provides content negotiation; for web requests, redirects to the login page; for service requests, returns a
401 Unauthorized
-
Mitigates CSRF attacks
-
Mitigates Session Fixation attacks
-
Writes Strict-Transport-Security to ensure HTTPS
-
Writes X-Content-Type-Options to mitigate sniffing attacks
-
编写 Cache Control headers,以保护经认证的资源
-
Writes Cache Control headers that protect authenticated resources
-
将 X-Frame-Options 写入以缓解 Clickjacking
-
Writes X-Frame-Options to mitigate Clickjacking
-
Integrates with `HttpServletRequest’s authentication methods
了解 Spring Boot 如何与 Spring Security 协调来实现这一点非常有用。了解 {spring-boot-api-url}org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.html[Boot 的安全自动配置] 后,它会执行以下操作(为说明目的进行简化):
It can be helpful to understand how Spring Boot is coordinating with Spring Security to achieve this. Taking a look at {spring-boot-api-url}org/springframework/boot/autoconfigure/security/servlet/SecurityAutoConfiguration.html[Boot’s security auto configuration], it does the following (simplified for illustration):
@EnableWebSecurity 1
@Configuration
public class DefaultSecurityConfig {
@Bean
@ConditionalOnMissingBean(UserDetailsService.class)
InMemoryUserDetailsManager inMemoryUserDetailsManager() { 2
String generatedPassword = // ...;
return new InMemoryUserDetailsManager(User.withUsername("user")
.password(generatedPassword).roles("ROLE_USER").build());
}
@Bean
@ConditionalOnMissingBean(AuthenticationEventPublisher.class)
DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(ApplicationEventPublisher delegate) { 3
return new DefaultAuthenticationEventPublisher(delegate);
}
}
-
添加
@EnableWebSecurity
注释。(尤其,这将发布 Spring Security’s defaultFilter
chain 作为@Bean
) -
Adds the
@EnableWebSecurity
annotation. (Among other things, this publishes Spring Security’s defaultFilter
chain as a@Bean
) -
发布具有用户名
user
和随机生成的密码(已记录到控制台)的UserDetailsService
@Bean
-
Publishes a
UserDetailsService
@Bean
with a username ofuser
and a randomly generated password that is logged to the console -
发布用于发布认证事件的
AuthenticationEventPublisher
@Bean
-
Publishes an
AuthenticationEventPublisher
@Bean
for publishing authentication events
Spring Boot 会将任何发布为 |
Spring Boot adds any |
Security Use Cases
您可能希望从此处开始。为了了解您和您的应用程序的下一步工作,请考虑 Spring Security 构建来解决的以下常见用例:
There are a number of places that you may want to go from here. To figure out what’s next for you and your application, consider these common use cases that Spring Security is built to address:
-
我正在构建一个 REST API,并且我需要 authenticate a JWT 或 other bearer token
-
I am building a REST API, and I need to authenticate a JWT or other bearer token
-
我正在构建 Web 应用程序、API 网关或 BFF,并且
-
I need to login using OAuth 2.0 or OIDC
-
I need to login using SAML 2.0
-
我需要 login using CAS
-
I need to login using CAS
-
I am building a Web Application, API Gateway, or BFF and
-
I need to login using OAuth 2.0 or OIDC
-
I need to login using SAML 2.0
-
我需要 login using CAS
-
I need to login using CAS
-
I need to manage
-
在 LDAP 或 Active Directory 中的用户,具有 Spring Data,或具有 JDBC
-
Users in LDAP or Active Directory, with Spring Data, or with JDBC
-
如果没有符合您要寻找的内容,请考虑按以下顺序思考您的应用程序:
In case none of those match what you are looking for, consider thinking about your application in the following order:
-
Protocol:首先,考虑应用程序将用于进行通信的协议。对于基于 servlet 的应用程序,Spring Security 支持 HTTP 和 Websockets。
-
Protocol: First, consider the protocol your application will use to communicate. For servlet-based applications, Spring Security supports HTTP as well as Websockets.
-
Authentication:其次,考虑用户将如何 authenticate,以及该认证是状态有穷或无穷
-
Authentication: Next, consider how users will authenticate and if that authentication will be stateful or stateless
-
Authorization:然后,考虑如何确定 what a user is authorized to do
-
Authorization: Then, consider how you will determine what a user is authorized to do
-
Defense:最后,integrate with Spring Security’s default protections,并且考虑 which additional protections you need
-
Defense: Finally, integrate with Spring Security’s default protections and consider which additional protections you need