title: Handle Custom Exceptions in Spring Security
body: <p>We are creating a RESTful API with spring MVC + spring security + hibernate.
  The API can produce both JSON and HTML.
  Doing a good error handling for spring security is giving me a headache:</p>
  
  <p>Authentication can happen in various ways: BasicAuth, via different parameters in a POST request and also via web log-in.
  For each authentication mechanism, there is a filter declared in the <code>&lt;http&gt;</code> namespace element of the spring security xml config.</p>
  
  <p>We handle all our spring exceptions in a custom <code>HandlerExceptionResolver</code>. This works fine for all exceptions thrown in our controllers, but I don't know how to handle custom Exceptions thrown in the custom spring security filters.
  Since the spring security filter comes before any of our controllers are invoked we do not see exceptions that we throw in our custom spring security filters. </p>
  
  <p>I found this question here on stackoverflow: 
  <a href="https://stackoverflow.com/questions/12035133/use-custom-exceptions-in-spring-security">Use custom exceptions in Spring Security</a>. However I don't understand where they handle the exceptions that are thrown there.
  We tried this approach but our custom <code>HandlerExceptionResolver</code> is not called. Instead the user is presented with an ugly stacktrace rendered by tomcat.</p>
  
  <p><strong>Why do we need this?</strong> 
  Users can be activated and deactivated. If they are deactivated and try to perform certain actions we would like to return JSON with a custom error message. This should be different than what is displayed when spring security throws a <code>AccessDeniedException</code>. The <code>AccessDeniedException</code> somehow makes it to our <code>HandlerExceptionResolver</code>, but I could not follow how exactly.</p>
  
  <p><strong>Possible solution</strong> 
  We thought about using an <code>ExceptionTranslationFilter</code>, however this is not called when we throw our custom exceptions (set a breakpoint in the catch statement of the doFilter() method). In my understanding this catch block should be called and an authentication entry point should be used.</p>
  
  <p>Another possibility: We could do something similar to the <code>ExceptionTranslationFilter</code> in the spring security filter chain and do something similar to what its <code>AccessDeniedHandler</code> does:</p>
  
  <pre><code>RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
  dispatcher.forward(request, response);
  </code></pre>
  
  <p>We could add some parameters (error code, reason etc.) to the request and have it point to a controller which would take care of the rendering in JSON or HTML.</p>
  
  <p><strong>Here is a short excerpt of our configuration:</strong></p>
  
  <p>Spring Security:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;http create-session="stateless" use-expressions="true" &gt;
      &lt;!-- Try getting the authorization object from the request parameters. --&gt;
      &lt;security:custom-filter ref="filter1" after="SECURITY_CONTEXT_FILTER"/&gt;
      &lt;security:custom-filter ref="filter2" before="LOGOUT_FILTER"/&gt;
      &lt;!-- Intercept certain URLS differently --&gt;
  
      &lt;intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" /&gt;
      &lt;!-- Some more stuff here --&gt;
      &lt;intercept-url pattern="/**" access="denyAll" /&gt;  
      &lt;http-basic /&gt;
  &lt;/http&gt;
  </code></pre>
  
  <p>AppConfig of the HandlerExceptionResolver</p>
  
  <pre><code>@Bean
  public HandlerExceptionResolver handlerExceptionResolver(){
      logger.info("creating handler exception resolver");
      return new AllExceptionHandler();
  }
  </code></pre>
  
  <p>Our custom HandlerExceptionResolver</p>
  
  <pre><code>public class AllExceptionHandler implements HandlerExceptionResolver {
  
      private static final Logger logger = LoggerFactory
          .getLogger(AppConfig.class);
  
      @Override
      public ModelAndView resolveException(HttpServletRequest request,
              HttpServletResponse response, Object handler, Exception ex) {
      // This is just a snipped of the real method code
      return new ModelAndView("errorPage");
  }
  </code></pre>
  
  <p>The relevant part of one of our filters:</p>
  
  <pre><code>try {
      Authentication authResult = authenticationManger.authenticate(authRequest);
      SecurityContextHolder.getContext().setAuthentication(authResult);
  }
  
  catch(AuthenticationException failed) {
      SecurityContextHolder.clearContext();
      throw failed; 
  }
  </code></pre>
  
  <p>Web.xml</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"&gt;
  &lt;context-param&gt;
      &lt;param-name&gt;contextClass&lt;/param-name&gt;
      &lt;param-value&gt;org.springframework.web.context.support.AnnotationConfigWebApplicationContext&lt;/param-value&gt;
  &lt;/context-param&gt;
  &lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;xxx.xxx.xxx.config&lt;/param-value&gt;
  &lt;/context-param&gt;
  &lt;context-param&gt;
      &lt;param-name&gt;spring.profiles.default&lt;/param-name&gt;
      &lt;param-value&gt;LIVE&lt;/param-value&gt;
  &lt;/context-param&gt;
  &lt;listener&gt;
      &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
  &lt;/listener&gt;
  &lt;servlet&gt;
      &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
      &lt;!-- Add multipart support for files up to 10 MB --&gt;
      &lt;multipart-config&gt;
          &lt;max-file-size&gt;10000000&lt;/max-file-size&gt;
      &lt;/multipart-config&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  &lt;filter&gt;
      &lt;filter-name&gt;openEntityManagerInViewFilter&lt;/filter-name&gt;
      &lt;filter-class&gt;org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter&lt;/filter-class&gt;
  &lt;/filter&gt;
  
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;openEntityManagerInViewFilter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  &lt;filter&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
  &lt;/filter&gt;
  &lt;!-- Map filters --&gt;
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  &lt;error-page&gt;
      &lt;error-code&gt;404&lt;/error-code&gt;
      &lt;location&gt;/handle/404&lt;/location&gt;
  &lt;/error-page&gt;
  &lt;/web-app&gt;
  </code></pre>
  
  <p>Does anyone have any pointers on how we could solve this?
  I looked through many articles on google, most of them describe how to handle the AccessDeniedException thrown by spring security when no filter is able to authenticate the request.</p>
  
  <p>We're using Spring Security 3.1.0 and spring web mvc 3.1.0.</p>