title: Propagating AccessDeniedException in Spring Security
body: <p>In my web application I am using Spring Security and Spring MVC.
  I have secured a couple of methods with <code>@Secured</code> annotation and configured Spring Security in such a way that when one of those methods is accessed without the proper role, the user is taken to the login page. However, I do not want that behaviour when the offending request comes from Ajax, so I implemented the custom <code>@ExceptionHandler</code> annotated method to determine the request's context.</p>
  
  <p>This is my exception handler:</p>
  
  <pre><code>@ExceptionHandler(AccessDeniedException.class)
  public void handleAccessDeniedException(AccessDeniedException ex, HttpServletRequest request, HttpServletResponse response) throws Exception {
  
      if (isAjax(request)) {
          response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      } else {
          throw ex;
      }
  }
  </code></pre>
  
  <p>This way I can both handle the exception myself (for example, log an attempt of accessing the <code>@Secured</code> method) and then let Spring do its part and redirect the user to the login page by rethrowing the AccessDeniedException. Also, when the request comes from Ajax I set the response status to <code>SC_UNAUTHORIZED</code> and handle the error on the client side.
  Now, this <em>seems</em> to be working fine, but I am getting the following ERROR each time I rethrow the exception from the <code>handleAccessDeniedException</code> method:</p>
  
  <pre><code>ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: public void app.controller.BaseController.handleAccessDeniedException(org.springframework.security.access.AccessDeniedException,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.lang.Exception
  org.springframework.security.access.AccessDeniedException: 
      at app.controller.BaseController.handleAccessDeniedException(BaseController.java:23)
      at app.controller.BaseController$$FastClassByCGLIB$$8f052058.invoke(&lt;generated&gt;)
      at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
      (...)
  </code></pre>
  
  <p>I have not added any exception handling specifics to spring xml configuration files.</p>
  
  <p>I do not see any issues with the app itself, but the error is there and since I am quite new to Spring MVC and Spring Security, I am guessing that I am not doing this properly. Any suggestions? Thanks!</p>