Home > Mobile >  ControllerAdvice catch AuthenticationException before Spring Security
ControllerAdvice catch AuthenticationException before Spring Security

Time:11-07

I am using ControllerAdvice for handling exceptions in my app and it is working properly. However, I started to use Spring Security and normally I should catch the AuthenticationExceptions in the following method.

@Override
    public void commence(HttpServletRequest request, HttpServletResponse response, 
        AuthenticationException authException)
            throws IOException, ServletException {
        logger.error("Unauthorized error: {}", authException.getMessage());

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        final Map<String, Object> body = new HashMap<>();
        body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
        body.put("error", "Unauthorized");
        body.put("message", authException.getMessage());
        body.put("path", request.getServletPath());

        final ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getOutputStream(), body);
    }

When I remove my exception handling classses, I can catch AuthenticationException in this method. BUT, when I use my exception handling mechanishm, it catche the AuthenticationExceptions before this commence method.

I tried to use @Order(value = Ordered.LOWEST_PRECEDENCE), but it does not make any sens. So, how can I catch AuthenticationException in this commence method by preventing ControllerAdvice catched them?

CodePudding user response:

So try to add annotation @ExceptionHandler(AuthenticationException.class):

@ControllerAdvice
public class ControllerExceptionHandler {

@ExceptionHandler(AuthenticationException.class)
  ...
  public ErrorMessage resourceNotFoundException(AuthenticationException exception) {
    ...
  }
}

See more at: https://www.baeldung.com/exception-handling-for-rest-with-spring Deep in dive Spring MVC Handling Exception:

  • Related