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 quick tutorial, weβre going to illustrate how to customize Spring Securityβs authentication failures handling in a Spring Boot application. The goal is to authenticate users using a form login approach.
For an introduction to Spring Security and Form Login in Spring Boot, please refer to this and this article, respectively.
2. Authentication and Authorization
Authentication and Authorization are often used in conjunction because they play an essential, and equally important, role when it comes to granting access to the system.
However, they have different meanings and apply different constraints when validating a request:
- Authentication β precedes Authorization; itβs about validating the received credentials; itβs where we verify that both username and password match the ones that our application recognizes
- Authorization βitβs about verifying if the successfully authenticated user has permissions to access a certain functionality of the application
We can customize both authentication and authorization failures handling, however, in this application, weβre going to focus on authentication failures.
3. Spring Securityβs AuthenticationFailureHandler
Spring Security provides a component that handles authentication failures for us by default.
However, itβs not uncommon to find ourselves in a scenario where the default behavior isnβt enough to meet requirements.
If that is the case, we can create our own component and provide the custom behavior we want by implementing the AuthenticationFailureHandler interface:
public class CustomAuthenticationFailureHandler
implements AuthenticationFailureHandler {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void onAuthenticationFailure(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception)
throws IOException, ServletException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
Map<String, Object> data = new HashMap<>();
data.put(
"timestamp",
Calendar.getInstance().getTime());
data.put(
"exception",
exception.getMessage());
response.getOutputStream()
.println(objectMapper.writeValueAsString(data));
}
}
By default, Spring redirects the user back to the login page with a request parameter containing information about the error.
In this application, weβll return a 401 response that contains information about the error, as well as the timestamp of its occurrence.
Besides the default component, Spring has others ready to use components that we can leverage depending on what we want to do:
- DelegatingAuthenticationFailureHandler delegates AuthenticationException subclasses to different AuthenticationFailureHandlers, meaning we can create different behaviors for different instances of AuthenticationException
- ExceptionMappingAuthenticationFailureHandler redirects the user to a specific URL depending on the AuthenticationExceptionβs full class name
- ForwardAuthenticationFailureHandler will forward the user to the specified URL regardless of the type of the AuthenticationException
- SimpleUrlAuthenticationFailureHandler is the component that is used by default, it will redirect the user to a failureUrl, if specified; otherwise, it will simply return a 401 response
Now that we have created our custom AuthenticationFailureHandler, letβs configure our application and override Springβs default handler:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user1 = User.withUsername("user1")
.password(passwordEncoder().encode("user1Pass"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user1);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.failureHandler(authenticationFailureHandler())
return http.build();
}
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return new CustomAuthenticationFailureHandler();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Note the failureHandler() call β itβs where we can tell Spring to use our custom component instead of using the default one.
4. Conclusion
In this example, we customized our applicationβs authentication failure handler leveraging Springβs AuthenticationFailureHandler interface.
When running locally, you can access and test the application at localhost:8080
