From eac4974a930894ed2288b8f6a5d7d23c7eb1c00d Mon Sep 17 00:00:00 2001
From: lakshankarunathilake <manualsplash@gmail.com>
Date: Wed, 23 Feb 2022 12:53:30 +0530
Subject: [PATCH] Support overriding state variable

---
 openid_connect.js                 | 4 ++--
 openid_connect.server_conf        | 4 ++--
 openid_connect_configuration.conf | 5 +++++
 3 files changed, 9 insertions(+), 4 deletions(-)

diff --git a/openid_connect.js b/openid_connect.js
index 54c395d..e968063 100644
--- a/openid_connect.js
+++ b/openid_connect.js
@@ -259,7 +259,7 @@ function getAuthZArgs(r) {
 
         authZArgs += "&code_challenge_method=S256&code_challenge=" + pkce_code_challenge + "&state=" + r.variables.pkce_id;
     } else {
-        authZArgs += "&state=0";
+        authZArgs += "&state=" + r.variables.state;
     }
     return authZArgs;
 }
@@ -272,4 +272,4 @@ function idpClientAuth(r) {
     } else {
         return "code=" + r.variables.arg_code + "&client_secret=" + r.variables.oidc_client_secret;
     }   
-}
\ No newline at end of file
+}
diff --git a/openid_connect.server_conf b/openid_connect.server_conf
index 13456d2..e9aa967 100644
--- a/openid_connect.server_conf
+++ b/openid_connect.server_conf
@@ -39,7 +39,7 @@
         internal;
         proxy_ssl_server_name on; # For SNI to the IdP
         proxy_set_header      Content-Type "application/x-www-form-urlencoded";
-        proxy_set_body        "grant_type=authorization_code&client_id=$oidc_client&$args&redirect_uri=$redirect_base$redir_location";
+        proxy_set_body        "grant_type=authorization_code&client_id=$oidc_client&state=$state&$args&redirect_uri=$redirect_base$redir_location";
         proxy_method          POST;
         proxy_pass            $oidc_token_endpoint;
    }
@@ -51,7 +51,7 @@
         internal;
         proxy_ssl_server_name on; # For SNI to the IdP
         proxy_set_header      Content-Type "application/x-www-form-urlencoded";
-        proxy_set_body        "grant_type=refresh_token&refresh_token=$arg_token&client_id=$oidc_client&client_secret=$oidc_client_secret";
+        proxy_set_body        "grant_type=refresh_token&refresh_token=$arg_token&client_id=$oidc_client&state=$state&client_secret=$oidc_client_secret";
         proxy_method          POST;
         proxy_pass            $oidc_token_endpoint;
     }
diff --git a/openid_connect_configuration.conf b/openid_connect_configuration.conf
index 753832c..5b2d852 100644
--- a/openid_connect_configuration.conf
+++ b/openid_connect_configuration.conf
@@ -43,6 +43,11 @@ map $host $oidc_hmac_key {
     default "ChangeMe";
 }
 
+map $host $state {
+    # Unable to use this state if PKCE is enabled
+    default 0;
+}
+
 map $proto $oidc_cookie_flags {
     http  "Path=/; SameSite=lax;"; # For HTTP/plaintext testing
     https "Path=/; SameSite=lax; HttpOnly; Secure;"; # Production recommendation