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:
-
Better understand servlet-hello-auto-configuration
-
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:
-
Requires an authenticated user for any endpoint (including Boot’s
/error
endpoint) -
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
) -
Protects password storage with BCrypt as well as others
-
Authenticates form-based login as well as HTTP Basic
-
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
-
Writes Cache Control headers that protect authenticated resources
-
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);
}
}
-
Adds the
@EnableWebSecurity
annotation. (Among other things, this publishes Spring Security’s defaultFilter
chain as a@Bean
) -
Publishes a
UserDetailsService
@Bean
with a username ofuser
and a randomly generated password that is logged to the console -
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:
-
I am building a REST API, and I need to authenticate a JWT or other bearer token
-
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
-
I need to login using CAS
-
-
I need to manage
-
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: First, consider the protocol your application will use to communicate. For servlet-based applications, Spring Security supports HTTP as well as Websockets.
-
Authentication: Next, consider how users will authenticate and if that authentication will be stateful or stateless
-
Authorization: Then, consider how you will determine what a user is authorized to do
-
Defense: Finally, integrate with Spring Security’s default protections and consider which additional protections you need