title: Nginx to introspect OAUTH token
body: <p>I am setting an Nginx reverse proxy that routes requests to various backend microservices based on path. Additionally, before routing requests, I would like Nginx to verify the validity of the oauth token passed in request header. I use Keycloak as oauth server, though I could introspect the token from other applications (and postman) I find it hard to implement in Nginx. </p>
  
  <p><code>nginx.conf</code></p>
  
  <pre><code>map $http_authorization $token {
    ~*^Bearer\s+([\S]+)$ $1;
  }
  
  location / {
    auth_request /auth;
    error_page 401 =401 /auth;
    proxy_pass http://backend-api/; 
  }
  </code></pre>
  
  <hr>
  
  <p>Token verify block</p>
  
  <pre><code>location = /auth {
    # internal;
    gunzip on;
    proxy_method POST;
    proxy_set_header Authorization "Basic base64encoded-uid-pwd";
    proxy_set_header Content-Type "application/x-www-form-urlencoded";
    proxy_set_body "token=$token";
    proxy_pass https://keycloak-server/auth/realms/myrealm/protocol/openid-connect/token/introspect;
  
    # proxy_cache           token_responses; # Enable caching of token introspection responses
    # proxy_cache_key       $access_token;   # Cache the response for each unique access token
    # proxy_cache_lock      on;              # Don't allow simultaneous requests for same token
    # proxy_cache_valid     200 10s;         # How long to use cached introspection responses
    # proxy_cache_use_stale error timeout;   # Use old responses if we cannot reach the server
    # proxy_ignore_headers  Cache-Control Expires Set-Cookie; # Cache even when receiving these
  
  }
  </code></pre>
  
  <p>The Nginx is send the request to the Keycloak server, I have verified the log, but I get the below error response from Keycloak</p>
  
  <pre><code>{
  "active": false
  }
  </code></pre>
  
  <p>I found this error was due to the token not properly passed as body param in the request. What am I missing in the script? Actually I have to take only the auth token passed in <code>Authorization</code> header and pass it to the Keycloak server in body param.</p>
  
  <p>PS: The Keycloak expects the oauth token as param in the <code>x-www-form-urlencoded</code> body as <code>token</code>.</p>