title: Spring Boot + REST + Spring Security: how to generate a custom JSON response for HTTP 403
body: <p>I have a Spring-Boot REST controller, protected by Spring-Security. It works fine. If the client sends an HTTP request without having the proper access token on the HTTP header then he gets back an HTTP 403 response, as I expect.</p>
  
  <p><strong>curl -i localhost:8301/user/11:</strong></p>
  
  <pre><code>HTTP/1.1 403 
  X-Content-Type-Options: nosniff
  X-XSS-Protection: 1; mode=block
  Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  Pragma: no-cache
  Expires: 0
  X-Frame-Options: DENY
  Content-Type: application/json;charset=UTF-8
  Transfer-Encoding: chunked
  Date: Thu, 07 Nov 2019 16:25:45 GMT
  
  {
    "timestamp" : 1573143945072,
    "status" : 403,
    "error" : "Forbidden",
    "message" : "Access Denied",
    "path" : "/user/11"
  }
  </code></pre>
  
  <p>I also have a custom error handler, it handles all the errors appear in the REST methods:</p>
  
  <pre><code>@Order(Ordered.HIGHEST_PRECEDENCE)
  @ControllerAdvice
  public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
  
      @Override
      protected ResponseEntity&lt;Object&gt; handleHttpMessageNotReadable(
              HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
          ...
          return new ResponseEntity&lt;&gt;(json, httpStatus);
      }
  
      @Override
      protected ResponseEntity&lt;Object&gt; handleMethodArgumentNotValid(
              MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
  
          return new ResponseEntity&lt;&gt;(json, httpStatus);
      }
  }
  </code></pre>
  
  <p>Now what I would like to do is to customize the error response in case of HTTP 403 and I want to send back a custom JSON response to the client (same JSON what I send back in the <code>ControllerExceptionHandler</code>).</p>
  
  <p>Unfortunately, the error handler above does not handle the HTTP 403 because the request is blocked by Spring-Security somewhere before it reaches my REST method.</p>
  
  <p>It seems that I need to add some extra code to Spring Security but I am not sure.</p>
  
  <p>Could you please put me in the right direction?</p>