diff --git a/README.md b/README.md index 2b3b006..93ff3b3 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,10 @@ This repository describes how to enable OpenID Connect integration for [NGINX Pl This implementation assumes the following environment: - * The identity provider (IdP) supports OpenID Connect 1.0 - * The authorization code flow is in use - * NGINX Plus is configured as a relying party - * The IdP knows NGINX Plus as a confidential client or a public client using PKCE +- The identity provider (IdP) supports OpenID Connect 1.0 +- The authorization code flow is in use +- NGINX Plus is configured as a relying party +- The IdP knows NGINX Plus as a confidential client or a public client using PKCE With this environment, both the client and NGINX Plus communicate directly with the IdP at different stages during the initial authentication event. @@ -67,6 +67,7 @@ Finally, create a clone of the GitHub repository. All files can be copied to **/etc/nginx/conf.d** ### Non-standard directories + The GitHub repository contains [`include`](http://nginx.org/en/docs/ngx_core_module.html#include) files for NGINX configuration, and JavaScript code for token exchange and initial token validation. These files are referenced with a relative path (relative to /etc/nginx). If NGINX Plus is running from a non-standard location then copy the files from the GitHub repository to `/path/to/conf/conf.d` and use the `-p` flag to start NGINX with a prefix path that specifies the location where the configuration files are located. ```shell @@ -74,6 +75,7 @@ $ nginx -p /path/to/conf -c /path/to/conf/nginx.conf ``` ### Running in containers + This implementation is suitable for running in a container provided that the [base image](https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-docker/) includes the NGINX JavaScript module. The GitHub repository is designed to facilitate testing with a container by binding the cloned repository to a mount volume on the container. ```shell @@ -82,20 +84,22 @@ $ docker run -d -p 8010:8010 -v $PWD:/etc/nginx/conf.d nginx-plus nginx -g 'daem ``` ### Running behind another proxy or load balancer + When NGINX Plus is deployed behind another proxy, the original protocol and port number are not available. NGINX Plus needs this information to construct the URIs it passes to the IdP and for redirects. By default NGINX Plus looks for the X-Forwarded-Proto and X-Forwarded-Port request headers to construct these URIs. ## Configuring your IdP - * Create an OpenID Connect client to represent your NGINX Plus instance - * Choose the **authorization code flow** - * Set the **redirect URI** to the address of your NGINX Plus instance (including the port number), with `/_codexch` as the path, e.g. `https://my-nginx.example.com:443/_codexch` - * Ensure NGINX Plus is configured as a confidential client (with a client secret) or a public client (with PKCE S256 enabled) - * Make a note of the `client ID` and `client secret` if set +- Create an OpenID Connect client to represent your NGINX Plus instance + + - Choose the **authorization code flow** + - Set the **redirect URI** to the address of your NGINX Plus instance (including the port number), with `/_codexch` as the path, e.g. `https://my-nginx.example.com:443/_codexch` + - Ensure NGINX Plus is configured as a confidential client (with a client secret) or a public client (with PKCE S256 enabled) + - Make a note of the `client ID` and `client secret` if set - * If your IdP supports OpenID Connect Discovery (usually at the URI `/.well-known/openid-configuration`) then use the `configure.sh` script to complete configuration. In this case you can skip the next section. Otherwise: - * Obtain the URL for `jwks_uri` or download the JWK file to your NGINX Plus instance - * Obtain the URL for the **authorization endpoint** - * Obtain the URL for the **token endpoint** +- If your IdP supports OpenID Connect Discovery (usually at the URI `/.well-known/openid-configuration`) then use the `configure.sh` script to complete configuration. In this case you can skip the next section. Otherwise: + - Obtain the URL for `jwks_uri` or download the JWK file to your NGINX Plus instance + - Obtain the URL for the **authorization endpoint** + - Obtain the URL for the **token endpoint** ## Configuring NGINX Plus @@ -103,45 +107,49 @@ Configuration can typically be completed automatically by using the `configure.s Manual configuration involves reviewing the following files so that they match your IdP(s) configuration. - * **openid_connect_configuration.conf** - this contains the primary configuration for one or more IdPs in `map{}` blocks - * Modify all of the `map…$oidc_` blocks to match your IdP configuration - * Modify the URI defined in `map…$oidc_logout_redirect` to specify an unprotected resource to be displayed after requesting the `/logout` location - * Set a unique value for `$oidc_hmac_key` to ensure nonce values are unpredictable - * If NGINX Plus is deployed behind another proxy or load balancer, modify the `map…$redirect_base` and `map…$proto` blocks to define how to obtain the original protocol and port number. +- **openid_connect_configuration.conf** - this contains the primary configuration for one or more IdPs in `map{}` blocks + + - Modify all of the `map…$oidc_` blocks to match your IdP configuration + - Modify the URI defined in `map…$oidc_logout_redirect` to specify an unprotected resource to be displayed after requesting the `/logout` location + - Set a unique value for `$oidc_hmac_key` to ensure nonce values are unpredictable + - If NGINX Plus is deployed behind another proxy or load balancer, modify the `map…$redirect_base` and `map…$proto` blocks to define how to obtain the original protocol and port number. + +- **frontend.conf** - this is the reverse proxy configuration + + - Modify the upstream group to match your backend site or app + - Configure the preferred listen port and [enable SSL/TLS configuration](https://docs.nginx.com/nginx/admin-guide/security-controls/terminating-ssl-http/) + - Modify the severity level of the `error_log` directive to suit the deployment environment + - Comment/uncomment the `auth_jwt_key_file` or `auth_jwt_key_request` directives based on whether `$oidc_jwt_keyfile` is a file or URI, respectively - * **frontend.conf** - this is the reverse proxy configuration - * Modify the upstream group to match your backend site or app - * Configure the preferred listen port and [enable SSL/TLS configuration](https://docs.nginx.com/nginx/admin-guide/security-controls/terminating-ssl-http/) - * Modify the severity level of the `error_log` directive to suit the deployment environment - * Comment/uncomment the `auth_jwt_key_file` or `auth_jwt_key_request` directives based on whether `$oidc_jwt_keyfile` is a file or URI, respectively +- **openid_connect.server_conf** - this is the NGINX configuration for handling the various stages of OpenID Connect authorization code flow - * **openid_connect.server_conf** - this is the NGINX configuration for handling the various stages of OpenID Connect authorization code flow - * No changes are usually required here - * Modify the `resolver` directive to match a DNS server that is capable of resolving the IdP defined in `$oidc_token_endpoint` - * If using [`auth_jwt_key_request`](http://nginx.org/en/docs/http/ngx_http_auth_jwt_module.html#auth_jwt_key_request) to automatically fetch the JWK file from the IdP then modify the validity period and other caching options to suit your IdP + - No changes are usually required here + - Modify the `resolver` directive to match a DNS server that is capable of resolving the IdP defined in `$oidc_token_endpoint` + - If using [`auth_jwt_key_request`](http://nginx.org/en/docs/http/ngx_http_auth_jwt_module.html#auth_jwt_key_request) to automatically fetch the JWK file from the IdP then modify the validity period and other caching options to suit your IdP - * **openid_connect.js** - this is the JavaScript code for performing the authorization code exchange and nonce hashing - * No changes are required unless modifying the code exchange or validation process +- **openid_connect.js** - this is the JavaScript code for performing the authorization code exchange and nonce hashing + - No changes are required unless modifying the code exchange or validation process ### Configuring the Key-Value Store The key-value store is used to maintain persistent storage for ID tokens and refresh tokens. The default configuration should be reviewed so that it suits the environment. This is part of the advanced configuration in **openid_connect_configuration.conf**. ```nginx -keyval_zone zone=oidc_id_tokens:1M state=conf.d/oidc_id_tokens.json timeout=1h; -keyval_zone zone=refresh_tokens:1M state=conf.d/refresh_tokens.json timeout=8h; -keyval_zone zone=oidc_pkce:128K timeout=90s; +keyval_zone zone=oidc_id_tokens:1M state=conf.d/oidc_id_tokens.json timeout=1h; +keyval_zone zone=oidc_access_tokens:1M state=conf.d/oidc_access_tokens.json timeout=1h; +keyval_zone zone=refresh_tokens:1M state=conf.d/refresh_tokens.json timeout=8h; +keyval_zone zone=oidc_pkce:128K timeout=90s; ``` Each of the `keyval_zone` parameters are described below. - * **zone** - Specifies the name of the key-value store and how much memory to allocate for it. Each session will typically occupy 1-2KB, depending on the size of the tokens, so scale this value to exceed the number of unique users that may authenticate. +- **zone** - Specifies the name of the key-value store and how much memory to allocate for it. Each session will typically occupy 1-2KB, depending on the size of the tokens, so scale this value to exceed the number of unique users that may authenticate. - * **state** (optional) - Specifies where all of the ID Tokens in the key-value store are saved, so that sessions will persist across restart or reboot of the NGINX host. The NGINX Plus user account, typically **nginx**, must have write permission to the directory where the state file is stored. Consider creating a dedicated directory for this purpose. +- **state** (optional) - Specifies where all of the ID Tokens in the key-value store are saved, so that sessions will persist across restart or reboot of the NGINX host. The NGINX Plus user account, typically **nginx**, must have write permission to the directory where the state file is stored. Consider creating a dedicated directory for this purpose. - * **timeout** - Expired tokens are removed from the key-value store after the `timeout` value. This should be set to value slightly longer than the JWT validity period. JWT validation occurs on each request, and will fail when the expiry date (`exp` claim) has elapsed. If JWTs are issued without an `exp` claim then set `timeout` to the desired session duration. If JWTs are issued with a range of validity periods then set `timeout` to exceed the longest period. +- **timeout** - Expired tokens are removed from the key-value store after the `timeout` value. This should be set to value slightly longer than the JWT validity period. JWT validation occurs on each request, and will fail when the expiry date (`exp` claim) has elapsed. If JWTs are issued without an `exp` claim then set `timeout` to the desired session duration. If JWTs are issued with a range of validity periods then set `timeout` to exceed the longest period. - * **sync** (optional) - If deployed in a cluster, the key-value store may be synchronized across all instances in the cluster, so that all instances are able to create and validate authenticated sessions. Each instance must be configured to participate in state sharing with the [zone_sync module](http://nginx.org/en/docs/stream/ngx_stream_zone_sync_module.html) and by adding the `sync` parameter to the `keyval_zone` directives above. +- **sync** (optional) - If deployed in a cluster, the key-value store may be synchronized across all instances in the cluster, so that all instances are able to create and validate authenticated sessions. Each instance must be configured to participate in state sharing with the [zone_sync module](http://nginx.org/en/docs/stream/ngx_stream_zone_sync_module.html) and by adding the `sync` parameter to the `keyval_zone` directives above. ## Session Management @@ -157,6 +165,7 @@ To delete a single session: ```shell $ curl -iX PATCH -d '{"":null}' localhost:8010/api/6/http/keyvals/oidc_id_tokens +$ curl -iX PATCH -d '{"":null}' localhost:8010/api/6/http/keyvals/oidc_access_tokens $ curl -iX PATCH -d '{"":null}' localhost:8010/api/6/http/keyvals/refresh_tokens ``` @@ -164,6 +173,7 @@ To delete all sessions: ```shell $ curl -iX DELETE localhost:8010/api/6/http/keyvals/oidc_id_tokens +$ curl -iX DELETE localhost:8010/api/6/http/keyvals/oidc_access_tokens $ curl -iX DELETE localhost:8010/api/6/http/keyvals/refresh_tokens ``` @@ -171,17 +181,17 @@ $ curl -iX DELETE localhost:8010/api/6/http/keyvals/refresh_tokens The **openid_connect.server_conf** file defines several [`status_zone`](http://nginx.org/en/docs/http/ngx_http_api_module.html#status_zone) directives to collect metrics about OpenID Connect activity and errors. Separate metrics counters are recorded for: - * **OIDC start** - New sessions are counted here. See step 2 in Figure 2, above. Success is recorded as a 3xx response. +- **OIDC start** - New sessions are counted here. See step 2 in Figure 2, above. Success is recorded as a 3xx response. - * **OIDC code exchange** - Counters are incremented here when the browser returns to NGINX Plus after authentication. See steps 6-10 in Figure 2, above. Success is recorded as a 3xx response. +- **OIDC code exchange** - Counters are incremented here when the browser returns to NGINX Plus after authentication. See steps 6-10 in Figure 2, above. Success is recorded as a 3xx response. - * **OIDC logout** - Requests to the /logout URI are counted here. Success is recorded as a 3xx response. +- **OIDC logout** - Requests to the /logout URI are counted here. Success is recorded as a 3xx response. - * **OIDC error** - Counters are incremented here when errors in the code exchange process are actively detected. Typically there will be a corresponding error_log entry. +- **OIDC error** - Counters are incremented here when errors in the code exchange process are actively detected. Typically there will be a corresponding error_log entry. - To obtain the current set of metrics: +To obtain the current set of metrics: - ```shell +```shell $ curl localhost:8010/api/6/http/location_zones ``` @@ -191,33 +201,38 @@ In addition, the [NGINX Plus Dashboard](https://docs.nginx.com/nginx/admin-guide Any errors generated by the OpenID Connect flow are logged to the error log, `/var/log/nginx/error.log`. Check the contents of this file as it may include error responses received by the IdP. The level of detail recorded can be modified by adjusting the severity level of the `error_log` directive. - * **400 error from IdP** - * This is typically caused by incorrect configuration related to the client ID and client secret. - * Check the values of the `map…$oidc_client` and `map…$oidc_client_secret` variables against the IdP configuration. +- **400 error from IdP** + + - This is typically caused by incorrect configuration related to the client ID and client secret. + - Check the values of the `map…$oidc_client` and `map…$oidc_client_secret` variables against the IdP configuration. + +- **500 error from nginx after successful authentication** + - Check for `could not be resolved` and `empty JWK set while sending to client` messages in the error log. This is common when NGINX Plus cannot reach the IdP's `jwks_uri` endpoint. + - Check the `map…$oidc_jwt_keyfile` variable is correct. + - Check the `resolver` directive in **openid_connect.server_conf** is reachable from the NGINX Plus host. + - Check for `OIDC authorization code sent but token response is not JSON.` messages in the error log. This is common when NGINX Plus cannot decompress the IdP's response. Add the following configuration snippet to the `/_jwks_uri` and `/_token` locations to **openid_connect.server_conf**: - * **500 error from nginx after successful authentication** - * Check for `could not be resolved` and `empty JWK set while sending to client` messages in the error log. This is common when NGINX Plus cannot reach the IdP's `jwks_uri` endpoint. - * Check the `map…$oidc_jwt_keyfile` variable is correct. - * Check the `resolver` directive in **openid_connect.server_conf** is reachable from the NGINX Plus host. - * Check for `OIDC authorization code sent but token response is not JSON.` messages in the error log. This is common when NGINX Plus cannot decompress the IdP's response. Add the following configuration snippet to the `/_jwks_uri` and `/_token` locations to **openid_connect.server_conf**: ```nginx proxy_set_header Accept-Encoding "gzip"; ``` - * **Authentication is successful but browser shows too many redirects** - * This is typically because the JWT sent to the browser cannot be validated, resulting in 'authorization required' `401` response and starting the authentication process again. But the user is already authenticated so is redirected back to NGINX, hence the redirect loop. - * Avoid using `auth_jwt_require` directives in your configuration because this can also return a `401` which is indistinguishable from missing/expired JWT. - * Check the error log `/var/log/nginx/error.log` for JWT/JWK errors. - * Ensure that the JWK file (`map…$oidc_jwt_keyfile` variable) is correct and that the nginx user has permission to read it. +- **Authentication is successful but browser shows too many redirects** + + - This is typically because the JWT sent to the browser cannot be validated, resulting in 'authorization required' `401` response and starting the authentication process again. But the user is already authenticated so is redirected back to NGINX, hence the redirect loop. + - Avoid using `auth_jwt_require` directives in your configuration because this can also return a `401` which is indistinguishable from missing/expired JWT. + - Check the error log `/var/log/nginx/error.log` for JWT/JWK errors. + - Ensure that the JWK file (`map…$oidc_jwt_keyfile` variable) is correct and that the nginx user has permission to read it. + +- **Logged out but next request does not require authentication** + + - This is typically caused by the IdP issuing its own session cookie(s) to the client. NGINX Plus sends the request to the IdP for authentication and the IdP immediately sends back a new authorization code because the session is still valid. + - Check your IdP configuration if this behavior is not desired. - * **Logged out but next request does not require authentication** - * This is typically caused by the IdP issuing its own session cookie(s) to the client. NGINX Plus sends the request to the IdP for authentication and the IdP immediately sends back a new authorization code because the session is still valid. - * Check your IdP configuration if this behavior is not desired. +- **Failed SSL/TLS handshake to IdP** + - Indicated by error log messages including `peer closed connection in SSL handshake (104: Connection reset by peer) while SSL handshaking to upstream`. + - This can occur when the IdP requires Server Name Indication (SNI) information as part of the TLS handshake. Additional configuration is required to satisfy this requirement. + - Edit **openid_connect.server_conf** and for each of the `/_jwks_uri`, `/_token`, and `/_refresh` locations, add the following configuration snippet: - * **Failed SSL/TLS handshake to IdP** - * Indicated by error log messages including `peer closed connection in SSL handshake (104: Connection reset by peer) while SSL handshaking to upstream`. - * This can occur when the IdP requires Server Name Indication (SNI) information as part of the TLS handshake. Additional configuration is required to satisfy this requirement. - * Edit **openid_connect.server_conf** and for each of the `/_jwks_uri`, `/_token`, and `/_refresh` locations, add the following configuration snippet: ```nginx proxy_set_header Host ; proxy_ssl_name ; @@ -229,10 +244,10 @@ This reference implementation for OpenID Connect is supported for NGINX Plus sub ## Changelog - * **R15** Initial release of OpenID Connect reference implementation - * **R16** Added support for opaque session tokens using key-value store - * **R17** Configuration now supports JSON Web Key (JWK) set to be obtained by URI - * **R18** Opaque session tokens now used by default. Added support for refresh tokens. Added `/logout` location. - * **R19** Minor bug fixes - * **R22** Separate configuration file, supports multiple IdPs. Configurable scopes and cookie flags. JavaScript is imported as an indepedent module with `js_import`. Container-friendly logging. Additional metrics for OIDC activity. - * **R23** PKCE support. Added support for deployments behind another proxy or load balancer. +- **R15** Initial release of OpenID Connect reference implementation +- **R16** Added support for opaque session tokens using key-value store +- **R17** Configuration now supports JSON Web Key (JWK) set to be obtained by URI +- **R18** Opaque session tokens now used by default. Added support for refresh tokens. Added `/logout` location. +- **R19** Minor bug fixes +- **R22** Separate configuration file, supports multiple IdPs. Configurable scopes and cookie flags. JavaScript is imported as an indepedent module with `js_import`. Container-friendly logging. Additional metrics for OIDC activity. +- **R23** PKCE support. Added support for deployments behind another proxy or load balancer. diff --git a/frontend.conf b/frontend.conf index d79f10d..56b50f8 100644 --- a/frontend.conf +++ b/frontend.conf @@ -27,6 +27,7 @@ server { # Successfully authenticated users are proxied to the backend, # with 'sub' claim passed as HTTP header proxy_set_header username $jwt_claim_sub; + #proxy_set_header Authorization "Bearer $access_token"; # Enable when using access token proxy_pass http://my_backend; # The backend site/app access_log /var/log/nginx/access.log main_jwt; diff --git a/openid_connect.js b/openid_connect.js index e4f2084..88a4309 100644 --- a/openid_connect.js +++ b/openid_connect.js @@ -104,6 +104,11 @@ function auth(r, afterSyncCheck) { // ID Token is valid, update keyval r.log("OIDC refresh success, updating id_token for " + r.variables.cookie_auth_token); r.variables.session_jwt = tokenset.id_token; // Update key-value store + if (tokenset.access_token) { + r.variables.access_token = tokenset.access_token; + } else { + r.variables.access_token = ""; + } // Update refresh token (if we got a new one) if (r.variables.refresh_token != tokenset.refresh_token) { @@ -187,6 +192,11 @@ function codeExchange(r) { // Add opaque token to keyval session store r.log("OIDC success, creating session " + r.variables.request_id); r.variables.new_session = tokenset.id_token; // Create key-value store entry + if (tokenset.access_token) { + r.variables.new_access_token = tokenset.access_token; + } else { + r.variables.new_access_token = ""; + } r.headersOut["Set-Cookie"] = "auth_token=" + r.variables.request_id + "; " + r.variables.oidc_cookie_flags; r.return(302, r.variables.redirect_base + r.variables.cookie_auth_redir); } @@ -255,7 +265,8 @@ function validateIdToken(r) { function logout(r) { r.log("OIDC logout for " + r.variables.cookie_auth_token); - r.variables.session_jwt = "-"; + r.variables.session_jwt = "-"; + r.variables.access_token = '-'; r.variables.refresh_token = "-"; r.return(302, r.variables.oidc_logout_redirect); } diff --git a/openid_connect_configuration.conf b/openid_connect_configuration.conf index e8a9759..ca2f446 100644 --- a/openid_connect_configuration.conf +++ b/openid_connect_configuration.conf @@ -87,15 +87,18 @@ map $http_x_forwarded_proto $proto { proxy_cache_path /var/cache/nginx/jwk levels=1 keys_zone=jwk:64k max_size=1m; # Change timeout values to at least the validity period of each token type -keyval_zone zone=oidc_id_tokens:1M state=conf.d/oidc_id_tokens.json timeout=1h; -keyval_zone zone=refresh_tokens:1M state=conf.d/refresh_tokens.json timeout=8h; +keyval_zone zone=oidc_id_tokens:1M state=conf.d/oidc_id_tokens.json timeout=1h; +keyval_zone zone=oidc_access_tokens:1M state=conf.d/oidc_id_tokens.json timeout=1h; +keyval_zone zone=refresh_tokens:1M state=conf.d/refresh_tokens.json timeout=8h; keyval_zone zone=oidc_pkce:128K timeout=90s; # Temporary storage for PKCE code verifier. -keyval $cookie_auth_token $session_jwt zone=oidc_id_tokens; # Exchange cookie for JWT -keyval $cookie_auth_token $refresh_token zone=refresh_tokens; # Exchange cookie for refresh token -keyval $request_id $new_session zone=oidc_id_tokens; # For initial session creation -keyval $request_id $new_refresh zone=refresh_tokens; # '' -keyval $pkce_id $pkce_code_verifier zone=oidc_pkce; +keyval $cookie_auth_token $session_jwt zone=oidc_id_tokens; # Exchange cookie for JWT +keyval $cookie_auth_token $access_token zone=oidc_access_tokens; # Exchange cookie for access token +keyval $cookie_auth_token $refresh_token zone=refresh_tokens; # Exchange cookie for refresh token +keyval $request_id $new_session zone=oidc_id_tokens; # For initial session creation +keyval $request_id $new_access_token zone=oidc_access_tokens; +keyval $request_id $new_refresh zone=refresh_tokens; # '' +keyval $pkce_id $pkce_code_verifier zone=oidc_pkce; auth_jwt_claim_set $jwt_audience aud; # In case aud is an array js_import oidc from conf.d/openid_connect.js;