Handle spring security authentication exceptions with @ExceptionHandler

Cover Image for Handle spring security authentication exceptions with @ExceptionHandler
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Handling Spring Security Authentication Exceptions with @ExceptionHandler

If you've been working with Spring MVC's @ControllerAdvice and @ExceptionHandler, you might have encountered a common problem: it works fine for exceptions thrown by web MVC controllers, but not for exceptions thrown by Spring Security custom filters. These filters run before the controller methods are invoked.

One scenario where this problem might arise is when you have a custom Spring Security filter for token-based authentication. Let's take a look at an example:

public class AegisAuthenticationFilter extends GenericFilterBean {
    // ...
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        try {
            // ...
        } catch(AuthenticationException authenticationException) {
            SecurityContextHolder.clearContext();
            authenticationEntryPoint.commence(request, response, authenticationException);
        }
    }
}

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    }
}

@ControllerAdvice
public class RestEntityResponseExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class })
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public RestError handleAuthenticationException(Exception ex) {
        int errorCode = AegisErrorCode.GenericAuthenticationError;
        if(ex instanceof AegisException) {
            errorCode = ((AegisException)ex).getCode();
        }
        RestError re = new RestError(
            HttpStatus.UNAUTHORIZED,
            errorCode, 
            "...",
            ex.getMessage());
        return re;
    }
}

In this example, we have a custom Spring Security filter (AegisAuthenticationFilter) and an authentication entry point (RestAuthenticationEntryPoint). We also have a ControllerAdvice class (RestEntityResponseExceptionHandler) to handle exceptions globally.

The issue here is that when an AuthenticationException is thrown in the AegisAuthenticationFilter, it is caught and forwarded to the RestAuthenticationEntryPoint, which then sends an unauthorized error response. However, this response does not go through the @ExceptionHandler in the RestEntityResponseExceptionHandler, which means we cannot return a detailed JSON body for the AuthenticationException.

To make the Spring Security AuthenticationEntryPoint and Spring MVC @ExceptionHandler work together, we can use a simple solution:

  1. Create a custom exception class, let's call it CustomAuthenticationException, that extends AuthenticationException.

    public class CustomAuthenticationException extends AuthenticationException { public CustomAuthenticationException(String message) { super(message); } }
  2. In the AegisAuthenticationFilter, catch the AuthenticationException and rethrow it as CustomAuthenticationException.

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try { // ... } catch(AuthenticationException authenticationException) { SecurityContextHolder.clearContext(); throw new CustomAuthenticationException(authenticationException.getMessage()); } }
  3. Update the RestEntityResponseExceptionHandler to also handle CustomAuthenticationException.

    @ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class, CustomAuthenticationException.class }) @ResponseStatus(value = HttpStatus.UNAUTHORIZED) @ResponseBody public RestError handleAuthenticationException(Exception ex) { // ... }

With these changes, when an AuthenticationException is thrown in the AegisAuthenticationFilter, it will be caught and transformed into a CustomAuthenticationException. This new exception can then be handled by the @ExceptionHandler in the RestEntityResponseExceptionHandler, allowing us to return a detailed JSON body for it.

Remember to update your dependencies if you're using different versions of Spring Security and Spring MVC.

So go ahead and give this solution a try! Handle your Spring Security authentication exceptions with ease, and provide your users with meaningful error responses. If you found this blog post helpful, don't forget to share it with your fellow developers. And if you have any questions or suggestions, feel free to leave a comment below. Happy coding! ✨👩‍💻🚀


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello