Spring Boot Security Auto-Configuration – Spring Boot安全自动配置

最后修改: 2018年 2月 23日

1. Overview


In this tutorial, we’ll have a look at Spring Boot’s opinionated approach to security.

在本教程中,我们将看一下Spring Boot对安全的意见方法。

Simply put, we’re going to focus on the default security configuration and how we can disable or customize it if we need to.


2. Default Security Setup


In order to add security to our Spring Boot application, we need to add the security starter dependency:

为了给我们的Spring Boot应用程序添加安全性,我们需要添加security starter dependency


This will also include the SecurityAutoConfiguration class containing the initial/default security configuration.

这也将包括包含初始/默认安全配置的SecurityAutoConfiguration 类。

Notice how we didn’t specify the version here, with the assumption that the project is already using Boot as the parent.


By default, the Authentication gets enabled for the Application. Also, content negotiation is used to determine if basic or formLogin should be used.


There are some predefined properties:



If we don’t configure the password using the predefined property spring.security.user.password and start the application, a default password is randomly generated and printed in the console log:


Using default security password: c8be15de-4488-4490-9dc6-fab3f91435c6

For more defaults, see the security properties section of the Spring Boot Common Application Properties reference page.

有关更多的默认值,请参阅Spring Boot通用应用程序属性参考页中的安全属性部分。

3. Disabling the Auto-Configuration


To discard the security auto-configuration and add our own configuration, we need to exclude the SecurityAutoConfiguration class.


We can do this via a simple exclusion:


@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class SpringBootSecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSecurityApplication.class, args);

Or we can add some configuration into the application.properties file:



However, there are also some particular cases in which this setup isn’t quite enough.


For example, almost each Spring Boot application is started with Actuator in the classpath. This causes problems because another auto-configuration class needs the one we’ve just excluded. So, the application will fail to start.

例如,几乎每个Spring Boot应用程序在启动时都在classpath中加入了Actuator。这就造成了问题,因为另一个自动配置类需要我们刚刚排除的那个。因此,应用程序将无法启动。

In order to fix this issue, we need to exclude that class; and, specific to the Actuator situation, we also need to exclude ManagementWebSecurityAutoConfiguration.


3.1. Disabling vs Surpassing Security Auto-Configuration


There’s a significant difference between disabling auto-configuration and surpassing it.


Disabling it is just like adding the Spring Security dependency and the whole setup from scratch. This can be useful in several cases:

禁用它就像添加Spring Security依赖,整个设置从头开始。这在一些情况下是很有用的。

  1. Integrating application security with a custom security provider
  2. Migrating a legacy Spring application with already-existing security setup — to Spring Boot

But most of the time we won’t need to fully disable the security auto-configuration.


That’s because Spring Boot is configured to permit surpassing the auto-configured security by adding in our new/custom configuration classes. This is typically easier since we’re just customizing an existing security setup to fulfill our needs.

这是因为Spring Boot的配置允许我们通过添加新的/自定义配置类来超越自动配置的安全性。这通常比较容易,因为我们只是定制了一个现有的安全设置来满足我们的需求。

4. Configuring Spring Boot Security

4.配置Spring Boot安全

If we’ve chosen the path of disabling security auto-configuration, we naturally need to provide our own configuration.


As we’ve discussed before, this is the default security configuration. We then customize it by modifying the property file.


For example, we can override the default password by adding our own:



If we want a more flexible configuration, with multiple users and roles for example, we need to make use of a full @Configuration class:


public class BasicConfiguration {

    public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = User.withUsername("user")

        UserDetails admin = User.withUsername("admin")
            .roles("USER", "ADMIN")

        return new InMemoryUserDetailsManager(user, admin);

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http.build();

    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return encoder;

The @EnableWebSecurity annotation is crucial if we disable the default security configuration.


The application will fail to start if it’s missing.


Also, notice that we need to use the PasswordEncoder to set the passwords when using Spring Boot 2. For more details, see our guide on the Default Password Encoder in Spring Security 5.

此外,请注意,在使用Spring Boot 2时,我们需要使用PasswordEncoder来设置密码。有关详细信息,请参阅我们关于Spring Security 5的Default Password Encoder的指南。

Now we should verify that our security configuration applies correctly with a couple of quick live tests:


@SpringBootTest(webEnvironment = RANDOM_PORT)
public class BasicConfigurationIntegrationTest {

    TestRestTemplate restTemplate;
    URL base;
    @LocalServerPort int port;

    public void setUp() throws MalformedURLException {
        restTemplate = new TestRestTemplate("user", "password");
        base = new URL("http://localhost:" + port);

    public void whenLoggedUserRequestsHomePage_ThenSuccess()
     throws IllegalStateException, IOException {
        ResponseEntity<String> response =
          restTemplate.getForEntity(base.toString(), String.class);
        assertEquals(HttpStatus.OK, response.getStatusCode());

    public void whenUserWithWrongCredentials_thenUnauthorizedPage() 
      throws Exception {
        restTemplate = new TestRestTemplate("user", "wrongpassword");
        ResponseEntity<String> response =
          restTemplate.getForEntity(base.toString(), String.class);
        assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

Spring Security is in fact behind Spring Boot Security, so any security configuration that can be done with this one or any integration this one supports can also be implemented into Spring Boot.

Spring Security实际上是在Spring Boot Security的背后,所以任何可以用这个做的安全配置或这个支持的任何集成也可以实现到Spring Boot中。

5. Spring Boot OAuth2 Auto-Configuration (Using Legacy Stack)

5.Spring Boot OAuth2自动配置(使用传统堆栈)

Spring Boot has a dedicated auto-configuration support for OAuth2.

Spring Boot对OAuth2有专门的自动配置支持。

The Spring Security OAuth support that came with Spring Boot 1.x was removed in later boot versions in lieu of first-class OAuth support that comes bundled with Spring Security 5. We’ll see how to use that in the next section.

Spring Boot 1.x所附带的Spring Security OAuth支持在后来的启动版本中被删除,取而代之的是Spring Security 5所捆绑的一流OAuth支持。我们将在下一节中看到如何使用它。

For the legacy stack (using Spring Security OAuth), we’ll first need to add a Maven dependency to start setting up our application:

对于传统的堆栈(使用Spring Security OAuth),我们首先需要添加一个Maven依赖,以开始设置我们的应用程序。


This dependency includes a set of classes that are capable of triggering the auto-configuration mechanism defined in OAuth2AutoConfiguration class.


Now we have multiple choices to continue depending on the scope of our application.


5.1. OAuth2 Authorization Server Auto-Configuration


If we want our application to be an OAuth2 provider, we can use @EnableAuthorizationServer.


On startup, we’ll notice in the logs that the auto-configuration classes will generate a client id and a client secret for our authorization server, and of course a random password for basic authentication:


Using default security password: a81cb256-f243-40c0-a585-81ce1b952a98
security.oauth2.client.client-id = 39d2835b-1f87-4a77-9798-e2975f36972e
security.oauth2.client.client-secret = f1463f8b-0791-46fe-9269-521b86c55b71

These credentials can be used to obtain an access token:


curl -X POST -u 39d2835b-1f87-4a77-9798-e2975f36972e:f1463f8b-0791-46fe-9269-521b86c55b71 \
 -d grant_type=client_credentials 
 -d username=user 
 -d password=a81cb256-f243-40c0-a585-81ce1b952a98 \
 -d scope=write  http://localhost:8080/oauth/token

Our other article provides further details on the subject.


5.2. Other Spring Boot OAuth2 Auto-Configuration Settings

5.2.其他Spring Boot OAuth2自动配置设置

There are some other use cases covered by Spring Boot OAuth2:

Spring Boot OAuth2还涉及一些其他用例。

  1. Resource Server@EnableResourceServer
  2. Client Application@EnableOAuth2Sso or @EnableOAuth2Client

If we need our application to be one of these types, we just have to add some configuration to application properties, as detailed by the links.


All OAuth2 specific properties can be found at Spring Boot Common Application Properties.

所有OAuth2的具体属性都可以在Spring Boot通用应用程序属性中找到。

6. Spring Boot OAuth2 Auto-Configuration (Using New Stack)

6.Spring Boot OAuth2自动配置(使用New Stack)

To use the new stack, we need to add dependencies based on what we want to configure — an authorization server, a resource server, or a client application.


Let’s look at them one by one.


6.1. OAuth2 Authorization Server Support


As we saw, the Spring Security OAuth stack offered the possibility of setting up an Authorization Server as a Spring Application. But the project has been deprecated, and Spring does not support its own authorization server as of now. Instead, it’s recommended to use existing well-established providers such as Okta, Keycloak and ForgeRock.

正如我们所看到的,Spring Security OAuth栈提供了将授权服务器设置为Spring应用程序的可能性。但该项目已被废弃,而且Spring目前不支持自己的授权服务器。相反,我们建议使用现有的成熟的供应商,如Okta、Keycloak和ForgeRock。

However, Spring Boot makes it easy for us to configure such providers. For an example Keycloak configuration, we can refer to either A Quick Guide to Using Keycloak With Spring Boot or Keycloak Embedded in a Spring Boot Application.

然而,Spring Boot使我们能够轻松地配置此类提供者。关于Keycloak配置的例子,我们可以参考在Spring Boot中使用Keycloak的快速指南嵌入Spring Boot应用程序中的Keycloak

6.2. OAuth2 Resource Server Support


To include support for a resource server, we need to add this dependency:



For the latest version information, head over to Maven Central.

有关最新的版本信息,请访问Maven Central

Additionally, in our security configuration, we need to include the oauth2ResourceServer() DSL:

此外,在我们的安全配置中,我们需要包括oauth2ResourceServer() DSL。

public class JWTSecurityConfig {
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
          .oauth2ResourceServer(oauth2 -> oauth2.jwt());

Our OAuth 2.0 Resource Server With Spring Security 5 gives an in-depth view of this topic.

我们的OAuth 2.0 Resource Server With Spring Security 5对该主题进行了深入探讨。

6.3. OAuth2 Client Support


Similar to how we configured a resource server, a client application also needs its own dependencies and DSLs.


Here’s the specific dependency for OAuth2 client support:



The latest version can be found at Maven Central.


Spring Security 5 also provides first-class login support via its oath2Login() DSL.

Spring Security 5还通过其oath2Login() DSL提供一流的登录支持。

For details on SSO support in the new stack, please refer to our article Simple Single Sign-On With Spring Security OAuth2.

有关新堆栈中SSO支持的详细信息,请参考我们的文章Simple Single Sign-On With Spring Security OAuth2

7. Conclusion


In this article, we focused on the default security configuration provided by Spring Boot. We saw how the security auto-configuration mechanism can be disabled or overridden. Then we looked at how a new security configuration can be applied.

在这篇文章中,我们重点讨论了Spring Boot提供的默认安全配置。我们看到安全自动配置机制是如何被禁用或推翻的。然后,我们研究了如何应用新的安全配置。

The source code for OAuth2 can be found on our OAuth2 GitHub repository, for legacy and new stack. The rest of the code can be found over on GitHub.

OAuth2的源代码可以在我们的OAuth2 GitHub仓库中找到,用于legacynew栈。其余的代码可以在GitHub上找到