I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Introduction

In this article, 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 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.

Simply put, by default, the application will get Basic Authentication enabled. There are some predefined properties, such as:

security.user.name=user
security.basic.enabled=true

If we start the application, we’ll notice that the 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 Spring Boot Common Application Properties at the security properties chapter.

3. Disabling the Auto-Configuration

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

This can be done via a simple exclusion:

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

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

Or by adding some configuration into the application.properties file:

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

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 need to exclude ManagementWebSecurityAutoConfiguration.

3.1. Disabling vs. Surpassing Security Auto-Configuration

There’s a significant difference between disabling autoconfiguration and surpassing it.

By disabling it, it’s 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.

The way Spring Boot is configured permits surpassing the autoconfigured security by adding in our new/custom configuration classes. This is typically easier, as 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 can customize it by modifying the property file.

We can, for example, override the default password by adding our own:

security.user.password=password

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

@Configuration
@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("user")
            .password("password")
            .roles("USER")
            .and()
          .withUser("admin")
            .password("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.

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

Now, we should verify that our security configuration applies correctly by 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("Baeldung"));
    }

    @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"));
    }
}

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

5. Spring Boot OAuth2 Auto-Configuration

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

Before we get to that, let’s add the 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

5.2. Other Spring Boot OAuth2 Auto-Configuration Settings

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

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

If we need our application to be one of the types above we just have to add some configuration to application properties.

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

6. 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 and how a new security configuration can be applied.

The source code can be found over on Github.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of