ErrorHandling in Spring Security for @PreAuthorize AccessDeniedException returns 500 rather then 401 ErrorHandling in Spring Security for @PreAuthorize AccessDeniedException returns 500 rather then 401 spring spring

ErrorHandling in Spring Security for @PreAuthorize AccessDeniedException returns 500 rather then 401


Based on the discussion of another post (see here) I came to the conclusion that the error handling for @PreAuthorize and authentication uses different concepts. The only way is to use in spring 3.2 the new concept of a generic error handler with @ControllerAdvice and @ExceptionHandler annotation. So you can reuse the error handler class.

Example

@Component@ControllerAdvicepublic class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {  @Override  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException, ServletException {        response.setContentType("application/json");    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);    response.getOutputStream().println("{ \"error\": \"" + authException.getMessage() + "\" }");  }  @ExceptionHandler(value = { AccessDeniedException.class })  public void commence(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex ) throws IOException {    response.setContentType("application/json");    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);    response.getOutputStream().println("{ \"error\": \"" + ex.getMessage() + "\" }");  }}