js_include conf.d/oauth2.js; map $http_authorization $access_token { "~*^bearer (.*)$" $1; default $http_authorization; } # This is where token introspection responses will be stored if proxy_cache is enabled proxy_cache_path /var/cache/nginx/tokens levels=1 keys_zone=token_responses:1m max_size=10m; server { listen 80; # Use TLS in production # OAuth 2.0 Token Introspection configuration resolver 8.8.8.8; # For DNS lookup of OAuth server subrequest_output_buffer_size 16k; # To fit a complete response from OAuth server #error_log /var/log/nginx/error.log debug; # Enable to see introspection details #set $access_token $http_apikey; # Where to find the token. Remove when using Authorization header set $oauth_token_endpoint "https://idp.example.com/oauth/token/introspect"; set $oauth_token_hint "access_token"; # E.g. access_token, refresh_token set $oauth_client_id "my-client-id"; # Will use HTTP Basic authentication unless empty set $oauth_client_secret "my-client-secret"; # If id is empty this will be used as a bearer token location / { auth_request /_oauth2_token_introspection; # Any member of the token introspection response is available as $sent_http_token_member #auth_request_set $username $sent_http_token_username; #proxy_set_header X-Username $username; proxy_pass http://my_backend; } location = /_oauth2_token_introspection { # This location implements an auth_request server that uses the JavaScript # module to perform the token introspection request. internal; js_content introspectAccessToken; } location = /_oauth2_send_introspection_request { # This location is called by introspectAccessToken(). We use the proxy_ # directives to construct an OAuth 2.0 token introspection request, as per: # https://tools.ietf.org/html/rfc7662#section-2 internal; gunzip on; # Decompress if necessary proxy_method POST; proxy_set_header Authorization $arg_authorization; proxy_set_header Content-Type "application/x-www-form-urlencoded"; proxy_set_body "token=$arg_token&token_hint=$oauth_token_hint"; proxy_pass $oauth_token_endpoint; 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 } } # vim: syntax=nginx