0

So we have implemented an interceptor middleware in java spring boot. The intention is to use this middleware in any client application (rest api clients) and validate all incoming http requests to prevent any CSRF attack. We are using this middleware inside one of our rest client, say java-demo. Everything works fine except the case when an invalid url i.e. the end point which does not exist, is hit.

   For ex: localhost:8080/java-demo/doesnotexist

In this case, when the interceptor logic raises CSRFException, it does not go to the ControllerAdvice where we have defined Exception handler for this particular exception. And in result, we get status 200 in postman, whereas we should get the exception with http status code as 403 which we throw with the response entity.

But when we hit a valid url,

For ex: localhost:8080/java-demo/exists

and if the exception is raised from the interceptor logic, then ControllerAdvice catches the exception and throws to the client, which is expected behaviour.

What can be the possible reason ControllerAdvice is not able to catch the exception when the url is not valid.

For the sake of clarity: When invalid url is hit and interceptor does not throw any exception, we get 404 not found error in postman.

ExceptionHandler class code which is present inside csrf middleware

    @ControllerAdvice
public class CSRFExceptionHandler {
    @ExceptionHandler({CSRFException.class})
    public ResponseEntity<ErrorResponse> handleCSRFException(CSRFException e) {
        return new ResponseEntity<>(new ErrorResponse(e.getErrorCode(), e.getMessage()), HttpStatus.FORBIDDEN);
    }

    @ExceptionHandler({ExpectedArgNotAvailableException.class})
    public ResponseEntity<ErrorResponse> handleExpectedArgsNotAvailable(ExpectedArgNotAvailableException e) {
        return new ResponseEntity<>(new ErrorResponse(e.getErrorCode(), e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Dhiren
  • 428
  • 1
  • 3
  • 12

0 Answers0