Hello Spring Security
Hello Spring Security
This section covers the minimum setup for how to use Spring Security with Spring Boot and then points you to next steps after that.
本节介绍了如何将 Spring Security 与 Spring Boot 一起使用的最低设置,然后指导您接下来的步骤。
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.
可以在我们的示例存储库中找到完成的入门应用程序。为方便起见,您可以下载由 Spring Initializr 准备的最小 Spring Boot + Spring Security 应用程序。
Updating Dependencies
You first need to add Spring Security to your application’s classpath; two ways to do this are to use Maven or Gradle.
首先需要将Spring Security添加到应用程序的类路径中;有两种方法可以做到这一点,一种是使用 Maven 或 Gradle。
Starting Hello Spring Security Boot
With Spring Security on the classpath, 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:
当在类路径添加 Spring Security 上之后,您现在可以运行 Spring Boot 应用程序。以下代码片段显示了一些输出,这些输出指示应用程序中启用了 Spring Security:
$ ./mvnw spring-boot:run ... 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:
现在您已经运行了它,您可以尝试点击端点以查看会发生什么。如果命中(命中也可以说是访问)没有凭据(这个凭据是spring security验证过或者由spring security 提供)的端点,如下所示:
Querying a Secured Boot Application
$ curl -i http://localhost:8080/some/path HTTP/1.1 401 ...
then Spring Security denies access with a 401 Unauthorized. 然后 Spring Security 使用 401 未经授权拒绝访问。
【Tip】
If you provide the same URL in a browser, it will redirect to a default login page.
#如果您在浏览器中提供相同的 URL,它将重定向到默认登录页面。
And if you hit an endpoint with credentials (found in the console output) as follows:
如果使用凭据(在控制台输出中找到)访问一个 endpoint 端点,如下所示:
Querying with Credentials
$ curl -i -u user:8e557245-73e2-4286-969a-ff57fe326336 http://localhost:8080/some/path HTTP/1.1 404 ...
then Spring Boot will service the request, returning a 404 Not Found in this case since /some/path doesn’t exist.
然后 Spring Boot 将为请求提供服务,在本例中返回 404 Not Found,因为 /some/path 不存在。
From here, you can:
-
Better understand what Spring Boot enables in Spring Security by default 更好地了解 Spring Boot 默认情况下在 Spring Security 中启用的功能
-
Read about common use cases that Spring Security helps with 了解 Spring Security 可帮助处理的常见用例
-
Start configuring authentication 开始配置authentication
Runtime Expectations 运行时预期
The default arrangement of Spring Boot and Spring Security affords the following behaviors at runtime:
Spring Boot 和 Spring Security 的默认安排在运行时提供以下行为:
-
Requires an authenticated user for any endpoint (including Boot’s
/errorendpoint)- 任何端点(包括 Boot 的 /error 端点)都需要提供“经过身份验证的用户”
-
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)- 在启动时使用生成的密码注册默认用户(密码将记录到控制台;在前面的示例中,密码为 8e557245-73e2-4286-969a-ff57fe326336)
-
Protects password storage with BCrypt as well as others
- 使用 BCrypt 以及其他工具保护密码存储
-
Provides form-based login and logout flows
- 提供基于表单的登录和注销流程
-
Authenticates form-based login as well as HTTP Basic
- 验证基于表单的登录以及 HTTP Basic
-
Provides content negotiation; for web requests, redirects to the login page; for service requests, returns a
401 Unauthorized- 提供内容协商; 对于 Web 请求,重定向到登录页面; 对于服务请求(用于服务之间的调用),返回 401 未授权
-
Mitigates CSRF attacks
- 缓解 CSRF 攻击
-
Mitigates Session Fixation attacks
- 缓解会话固定攻击
-
Writes Strict-Transport-Security to ensure HTTPS
- 写入 Strict-Transport-Security 以确保 HTTPS
-
Writes X-Content-Type-Options to mitigate sniffing attacks
-
Writes Cache Control headers that protect authenticated resources
-
编写 X-Content-Type-Options 以缓解嗅探攻击
-
-
Writes X-Frame-Options to mitigate Clickjacking
- 编写 X-Frame-Options 以缓解点击劫持
-
Integrates with
HttpServletRequest's authentication methods- 与 HttpServletRequest 的身份验证方法集成
-
Publishes authentication success and failure events
- 发布身份验证成功和失败事件
It can be helpful to understand how Spring Boot is coordinating with Spring Security to achieve this. Taking a look at Boot’s security auto configuration, it does the following (simplified for illustration):
了解 Spring Boot 如何与 Spring Security 协调以实现这一目标可能会有所帮助。看一下 Boot 的安全自动配置,它会执行以下操作(为说明而简化):
Spring Boot Security Auto Configuration
@EnableWebSecurity① @Configuration public class DefaultSecurityConfig { @Bean @ConditionalOnMissingBean(UserDetailsService.class) InMemoryUserDetailsManager inMemoryUserDetailsManager() {② String generatedPassword = // ...; return new InMemoryUserDetailsManager(User.withUsername("user") .password(generatedPassword).roles("USER").build()); } @Bean @ConditionalOnMissingBean(AuthenticationEventPublisher.class) DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(ApplicationEventPublisher delegate) {③ return new DefaultAuthenticationEventPublisher(delegate); } }
-
Adds the
@EnableWebSecurityannotation. (Among other things, this publishes Spring Security’s defaultFilterchain as a@Bean)。 添加@EnableWebSecurity注解。(除其他事项外,这会将 Spring Security 的默认过滤器链发布为@Bean) -
Publishes a
UserDetailsService@Beanwith a username ofuserand a randomly generated password that is logged to the console。 发布一个 UserDetailsService @Bean,其中包含 user 的用户名和随机生成的密码,该密码将记录到控制台 -
Publishes an
AuthenticationEventPublisher@Beanfor publishing authentication events。 发布用于发布身份验证事件的 AuthenticationEventPublisher @Bean
【Note】
Spring Boot adds any Filter published as a @Bean to the application’s filter chain. This means that using @EnableWebSecurity in conjunction with Spring Boot
automatically registers Spring Security’s filter chain for every request.
Spring Boot 会将任何作为@Bean发布的 Filter 添加到应用程序的过滤器链中。这意味着将 @EnableWebSecurity 与 Spring Boot 结合使用会自动为每个请求注册成为 Spring Security 的 filter chain。
Security Use Cases
用例选择
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 我正在构建一个 REST API,我需要对 JWT 或其他持有者令牌进行身份验证
-
I am building a Web Application, API Gateway, or BFF and 我正在构建一个 Web 应用程序、API 网关或 BFF,并且
-
I need to login using OAuth 2.0 or OIDC 我需要使用 OAuth 2.0 或 OIDC 登录
-
I need to login using SAML 2.0 我需要使用 SAML 2.0 登录
-
I need to login using CAS 我需要使用 CAS 登录
-
-
I need to manage 我需要管理
-
Users in LDAP or Active Directory, with Spring Data, or with JDBC LDAP 或 Active Directory、Spring Data 或 JDBC 中的用户
-
Passwords 密码
-
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. 协议:首先,考虑应用程序将用于通信的协议。对于基于 servlet 的应用程序,Spring Security 支持 HTTP 以及 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 防御:最后,与 Spring Security 的默认保护集成,并考虑您需要哪些额外的保护

浙公网安备 33010602011771号