title: ErrorHandling in Spring Security for @PreAuthorize AccessDeniedException returns 500 rather then 401
body: <p>Dear all I like to customize the error handling in a Spring 4 Rest application so it should return a HTTP Code 401 rather a Server Error 500 in case the check in @PreAuthorize annotation in my controller fails.</p>
  
  <p>I have an own AuthenticationEntryPoint and AuthenticationFailureHandler registered which its commence / error handling methods returns a 401. This works fine for my JWT authentication but in case of a failed @PreAuthorize check with "AccessDeniedException" these error methods get never called and spring returns a server error 500. </p>
  
  <p>How can I customize that? Looks like I missed something? Thanks for any hints in advance.</p>
  
  <p>Here my AuthenticationEntryPoint class:</p>
  
  <pre><code>@Component
  public 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() + "\" }");
     }
  }
  </code></pre>
  
  <p>Here my AuthenticationFailureHandler:</p>
  
  <pre><code>public class JWTAuthenticationFailureHandler implements AuthenticationFailureHandler {
      @Override
      public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
      response.sendError(401, (new StringBuilder()).append("Authentication Failed: ").append(exception.getMessage()).toString());
      }
  }
  </code></pre>
  
  <p>Here my spring security configuration</p>
  
  <pre><code>&lt;security:global-method-security pre-post-annotations="enabled"/&gt;
  
  &lt;security:http  pattern="/api/**" entry-point-ref="restAuthenticationEntryPoint"  &gt;
      &lt;security:csrf disabled="true"/&gt;
      &lt;security:intercept-url pattern="/api/**" access="isAuthenticated()" /&gt;
      &lt;security:custom-filter ref="authenticationTokenProcessingFilter" before="FORM_LOGIN_FILTER"   /&gt;
  &lt;/security:http&gt;
  
  &lt;security:authentication-manager alias="authenticationManager"&gt;
      &lt;security:authentication-provider ref="jwtAuthenticationProvider" /&gt;
  &lt;/security:authentication-manager&gt;
  
  &lt;bean id="restAuthenticationEntryPoint" class="ch.megloff.common.webservice.jwt.RestAuthenticationEntryPoint"/&gt;
  
  &lt;bean id="authenticationTokenProcessingFilter" class="ch.megloff.common.webservice.jwt.JWTAuthenticationFilter"&gt;
      &lt;constructor-arg type="java.lang.String"&gt;&lt;value&gt;/api/**&lt;/value&gt;&lt;/constructor-arg&gt;
      &lt;property name="authenticationManager" ref="authenticationManager"&gt;&lt;/property&gt;
      &lt;property name="authenticationFailureHandler" ref="jwtAuthenticationFailureHandler" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="jwtAuthenticationProvider" class="ch.megloff.common.webservice.jwt.JWTAuthenticationProvider" /&gt;
  &lt;bean id="jwtAuthenticationFailureHandler" class="ch.megloff.common.webservice.jwt.JWTAuthenticationFailureHandler" /&gt;
  </code></pre>
  
  <p>Here my rest controller class</p>
  
  <pre><code>@RestController
  public class UserController {
  
     @Autowired
     private UserService userService;
  
     @PreAuthorize("hasAuthority('admin')")
     @RequestMapping(value = "/api/user/", method = RequestMethod.GET)
     public ResponseEntity&lt;List&lt;User&gt;&gt; listAllUsers(HttpServletRequest request,    HttpServletResponse response) {
      System.out.println("Fetching all Users");
      List&lt;User&gt; users = userService.getUsers();
      if(users.isEmpty()){
          return new ResponseEntity&lt;List&lt;User&gt;&gt;(HttpStatus.NO_CONTENT);
      }
      return new ResponseEntity&lt;List&lt;User&gt;&gt;(users, HttpStatus.OK);
  }
  </code></pre>
  
  <p>Here the stack trace from the server when @PreAuthorize check in the annotation fails:</p>
  
  <pre><code>SEVERE: Servlet.service() for servlet [myusers] in context with path    [/JWTAuthenticationExample] threw exception [Request processing failed; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied] with root cause
  org.springframework.security.access.AccessDeniedException: Access is denied
  at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
  at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
  at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
  at ch.megloff.myusers.UserController$$EnhancerBySpringCGLIB$$635caa86.listAllUsers(&lt;generated&gt;)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
  at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
  at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
  at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
  at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
  at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
  at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
  at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
  at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
  at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
  at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
  at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:720)
  at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
  at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
  at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
  at org.springframework.security.web.firewall.RequestWrapper$FirewalledRequestAwareRequestDispatcher.forward(RequestWrapper.java:154)
  at ch.megloff.common.webservice.jwt.JWTAuthenticationSuccessHandler.onAuthenticationSuccess(JWTAuthenticationSuccessHandler.java:23)
  at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.successfulAuthentication(AbstractAuthenticationProcessingFilter.java:326)
  at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:240)
  at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
  at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
  at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
  at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
  at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
  at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
  at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
  at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
  at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
  at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
  at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
  at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
  at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
  at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
  at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
  at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  at java.lang.Thread.run(Thread.java:745)`
  </code></pre>