title: Throwing Exception on Authentication Failure
body: <p>I've implemented some token based authentication in my <code>spring-boot</code> application. I have a filter and in that filter, I am doing the following:</p>
  
  <pre><code>@Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      HttpServletRequest httpRequest = (HttpServletRequest) request;
      String authToken = httpRequest.getHeader("X-TOKEN-AUTH");
      String username = null;
  
      if (securityEnabled) {
         if (authToken != null) {
  
              try {
                  username = userTokenService.validateToken(authToken);
                  UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                  UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), null, userDetails.getAuthorities());
                  auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                  SecurityContextHolder.getContext().setAuthentication(auth);
  
              } catch (AuthenticationException ae) {
                  //TODO log something about signature exception
                  log.warn(ae.getMessage());
              }
          }
  
      }
  
      chain.doFilter(request, response);
  }
  </code></pre>
  
  <p>I also have a custom AuthFailureHandler:</p>
  
  <pre><code>@Component
  public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
      @Override
      public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                          AuthenticationException exception) throws IOException, ServletException {
          response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  
          PrintWriter writer = response.getWriter();
          writer.write(exception.getMessage());
          writer.flush();
      }
  }
  </code></pre>
  
  <p>My code <code>username = userTokenService.validateToken(authToken);</code> throws an <code>AuthenticationException</code> for various reasons. <code>AuthenticationException</code> is a custom exception that extends <code>Exception</code>. When I catch this exception, I still want to return a 401, but I want my message to appear in what is currently being sent back as JSON by <code>Spring Security</code> as default:</p>
  
  <pre><code>{
      "timestamp": 1463408604943,
      "status": 401,
      "error": "Unauthorized",
      "message": "An Authentication object was not found in the SecurityContext",
      "path": "/api/brands/2"
  }
  </code></pre>
  
  <p>I would want, for example...</p>
  
  <pre><code>{
      "timestamp": 1463408604943,
      "status": 401,
      "error": "Unauthorized",
      "message": "Invalid Token: Expired",
      "path": "/api/brands/2"
  }
  </code></pre>
  
  <p>I'm unsure how to override this behavior.</p>