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.

Updating Dependencies

您首先需要将 Spring Security 添加到应用程序的类路径;有两种方法可以做到 use MavenGradle

You first need to add Spring Security to your application’s classpath; two ways to do this are to use Maven or Gradle.

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:

Running Spring Boot 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:

Querying a Secured Boot Application
$ 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:

Querying with Credentials
$ 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:

Runtime Expectations

Spring Boot 和 Spring Security 的默认设置在运行时提供了以下行为:

The default arrangement of Spring Boot and Spring Security affords the following behaviors at runtime:

了解 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):

Spring Boot Security Auto Configuration
@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);
    }
}
  1. Adds the @EnableWebSecurity annotation. (Among other things, this publishes Spring Security’s default Filter chain as a @Bean)

  2. Publishes a UserDetailsService @Bean with a username of user and a randomly generated password that is logged to the console

  3. Publishes an AuthenticationEventPublisher @Bean for publishing authentication events

Spring Boot 会将任何发布为 @BeanFilter 添加到应用程序的过滤器链中。这意味着,在 Spring Boot 中与 @EnableWebSecurity 联合使用会自动为每个请求注册 Spring Security 的过滤器链。

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.

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:

如果没有符合您要寻找的内容,请考虑按以下顺序思考您的应用程序:

In case none of those match what you are looking for, consider thinking about your application in the following order:

  1. Protocol: First, consider the protocol your application will use to communicate. For servlet-based applications, Spring Security supports HTTP as well as Websockets.

  2. Authentication: Next, consider how users will authenticate and if that authentication will be stateful or stateless

  3. Authorization: Then, consider how you will determine what a user is authorized to do

  4. Defense: Finally, integrate with Spring Security’s default protections and consider which additional protections you need