If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:
>> LEARN SPRING SECURITYMocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
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.
Further reading:
Spring Security - permitAll() and web.ignoring()
Spring Security Form Login
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 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:
- Integrating application security with a custom security provider
- 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 {
@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername("user")
.password(passwordEncoder.encode("password"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(passwordEncoder.encode("admin"))
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(request -> request.anyRequest()
.authenticated())
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
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.
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("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"));
}
}
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:
- Resource Server β @EnableResourceServer
- 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 of the information, head over to Maven Central.
Additionally, in our security configuration, we need to include the oauth2ResourceServer() DSL:
@Configuration
public class JWTSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
...
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
...
}
}
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 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. 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.
