Spring Boot Security Auto-Configuration

1. Overview

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

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:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

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

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:

spring.security.user.name
spring.security.user.password

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.

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:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

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.

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:

  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.

4. Configuring Spring Boot Security

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:

spring.security.user.password=password

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

@Configuration
@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    	PasswordEncoder encoder = 
          PasswordEncoderFactories.createDelegatingPasswordEncoder();
    	auth
          .inMemoryAuthentication()
          .withUser("user")
          .password(encoder.encode("password"))
          .roles("USER")
          .and()
          .withUser("admin")
          .password(encoder.encode("admin"))
          .roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .anyRequest()
          .authenticated()
          .and()
          .httpBasic();
    }
}

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

The application will fail to start if it’s missing. So, the annotation is only optional if we’re just overriding the default behavior using a WebSecurityConfigurerAdapter.

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.

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

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class BasicConfigurationIntegrationTest {

    TestRestTemplate restTemplate;
    URL base;
    @LocalServerPort int port;

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

    @Test
    public void whenLoggedUserRequestsHomePage_ThenSuccess()
     throws IllegalStateException, IOException {
        ResponseEntity<String> response =
          restTemplate.getForEntity(base.toString(), String.class);
 
        assertEquals(HttpStatus.OK, response.getStatusCode());
        assertTrue(response.getBody().contains("VietMX"));
    }

    @Test
    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());
        assertTrue(response.getBody().contains("Unauthorized"));
    }
}

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.

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

Spring Boot has a dedicated auto-configuration support for 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.

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

<dependency>
   <groupId>org.springframework.security.oauth</groupId>
   <artifactId>spring-security-oauth2</artifactId>
</dependency>

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

There are some other use cases covered by 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.

6. Spring Boot OAuth2 Auto-Configuration (Using 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.

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.

6.2. OAuth2 Resource Server Support

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>    
</dependency>

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

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

@Configuration
public class JWTSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          ...
          .oauth2ResourceServer(oauth2 -> oauth2.jwt());
          ...
	}
}

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

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:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

The latest version can be found at Maven Central.

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

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

7. Spring Boot 2 Security vs Spring Boot 1 Security

Compared to Spring Boot 1, Spring Boot 2 has greatly simplified the auto-configuration.

In Spring Boot 2, if we want our own security configuration, we can simply add a custom WebSecurityConfigurerAdapter. This will disable the default auto-configuration and enable our custom security configuration.

Spring Boot 2 also uses most of Spring Security’s defaults. So, some of the endpoints that were unsecured by default in Spring Boot 1 are now secured by default.

These endpoints include static resources such as /css/**, /js/**, /images/**, /webjars/**, /**/favicon.ico and the error endpoint. If we need to allow unauthenticated access to these endpoints, we can explicitly configure that.

To simplify the security-related configuration, Spring Boot 2 has removed these Spring Boot 1 properties:

security.basic.authorize-mode
security.basic.enabled
security.basic.path
security.basic.realm
security.enable-csrf
security.headers.cache
security.headers.content-security-policy
security.headers.content-security-policy-mode
security.headers.content-type
security.headers.frame
security.headers.hsts
security.headers.xss
security.ignored
security.require-ssl
security.sessions

8. 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.

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.