title: Using Zuul as an authentication gateway
body: <p><strong>Background</strong></p>
  
  <p>I want to implement the design presented in this <a href="http://nordicapis.com/how-to-control-user-identity-within-microservices/" rel="noreferrer">article</a>.</p>
  
  <p>It can be summarised by the diagram below:
  <a href="https://i.stack.imgur.com/viaL4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/viaL4.png" alt="Security Architecture"></a></p>
  
  <ol>
  <li>The client first authenticate with the IDP (OpenID Connect/OAuth2)</li>
  <li>The IDP returns an access token (opaque token with no user info)</li>
  <li>The client makes a call through the API gateway use the access token in the Authorization header</li>
  <li>The API gateway makes a request to the IDP with the Access Token</li>
  <li>The IDP verifies that the Access Token is valid and returns user information in JSON format</li>
  <li>The API Gateway store the user information in a JWT and sign it with a private key. The JWT is then passed to the downstream service which verifies the JWT using the public key</li>
  <li>If a service must call another service to fulfil the request it passes the JWT along which serves as authentication and authorisation for the request</li>
  </ol>
  
  <p><strong>What I have so far</strong></p>
  
  <p>I have most of that done using:</p>
  
  <ul>
  <li>Spring cloud as a global framework</li>
  <li>Spring boot to launch individual services</li>
  <li>Netflix Zuul as the API gateway</li>
  </ul>
  
  <p>I have also written a Zuul PRE filter that checks for an Access Token, contacts the IDP and create a JWT. The JWT is then added to the header for the request forwarded to the downstream service.</p>
  
  <p><strong>Problem</strong></p>
  
  <p>Now my question is quite specific to Zuul and its filters. If authentication fails in the API gateway for any reason, how can I can stop the routing and respond directly with a 401 without continuing the filter chain and forwarding the call?</p>
  
  <p>At the moment if authentication fails the filter won't add the JWT to the header and the 401 will come from the downstream service. I was hoping my gateway could prevent this unnecessary call.</p>
  
  <p>I tried to see how I could use <code>com.netflix.zuul.context.RequestContext</code>to do this but the documentation is quite poor and I couldn't find a way. </p>