Spring MVC AccessDeniedException 500 error received instead of custom 401 error for @PreAuthorized unauth requests
OK guys, wasn't able to get any help from the community BUT I did find a solution -- although it's not a direct solution.
@ControllerAdvice
public class SecurityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({AccessDeniedException.class})
public ResponseEntity<Object> handleAccessDeniedException(Exception ex, WebRequest request) {
if(ex.getMessage().toLowerCase().indexOf("access is denied") > -1) {
return new ResponseEntity<Object>("Unauthorized Access", new HttpHeaders(), HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<Object>(ex.getMessage(), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
This new file in my app will allow me to control what happens during an exception. Now I can just manually inspect the problem to see if it was "access is denied" and then redirect to 401 which DOES WORK. The problem above was that the code to redirect to the 401 wasn't ever being hit. This code DOES get executed.
Again, this isn't a direct solution as we're manipulating a different piece of Spring MVC and kind of hacking default behavior to get it to work.
If anyone has a more elegant solution, please do post.