How to customize Spring Security’s AuthenticationFailureHandler in a Spring Boot application?

Tech Insights

We handle successful authentications by implementing the onAuthenticationSuccess() method of Spring Security’s AuthenticationSuccessHandler Interface. We write our own code to handle the activities and flow for successfully logged in users. Similarly we can handle the authentication failures using Spring Security’s AuthenticationFailureHandler Interface.

Spring handles authentication failures and redirect users to the login page by itself but in some cases, this default behavior is not enough for us. In such cases, we can implement the AuthenticationFailureHandler and override onAuthenticationFailure() method to customize the default behavior. Check the following code part:

@Component
public class AuthFailureHandler implements AuthenticationFailureHandler {
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
		AuthenticationException exception) throws IOException, ServletException {
		
		//your code to customize the authentication
		//Eg: record the time of failed login attempts, redirect users to different URLs based on existing URL parameters using the request object, etc.
		
		redirectStrategy.sendRedirect(request, response, "/home?loginError");
	}
}

Above is your customized authentication failure handler. Next step is to add the customized handler in your application’s Security Configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	//showing only the code to override the default failure handler
	@Override
    protected void configure(HttpSecurity http) throws Exception {
		http
            .authorizeRequests()
			.anyRequest().authenticated()
			.and()
            .formLogin()
			.failureHandler(getAuthFailureHandler()); //to use our own custom failure handler
	}
	@Bean
	public AuthenticationFailureHandler getAuthFailureHandler(){
		return new AuthFailureHandler(); 
	}
}

That’s it!