Skip to content

Add support to PKCE in OIDC connector - #3777

Merged
nabokihms merged 17 commits into
dexidp:masterfrom
johnvan7:feat/pkce-challenge-support
Feb 22, 2026
Merged

nabokihms merged 17 commits into
dexidp:masterfrom
johnvan7:feat/pkce-challenge-support

Conversation

@johnvan7

@johnvan7 johnvan7 commented Oct 2, 2024 •

Copy link
Copy Markdown
Contributor

Overview

This PR adds support for PKCE in the OIDC connector.

PKCE (Proof Key for Code Exchange) - RFC 7636 - is an extension to the Authorization Code flow to prevent CSRF (Cross-Site Request Forgery) and authorization code injection attacks.

PKCE Flow

                                             +-------------------+
                                             | Upstream Connector|
   +--------+                                | +---------------+ |
   |        |--(A)- Authorization Request ---->|               | |
   |        |       + t(code_verifier), t_m  | | Authorization | |
   |        |                                | |    Endpoint   | |
   |        |<-(B)---- Authorization Code -----|               | |
   |        |                                | +---------------+ |
   |   dex  |                                |                   |
   |        |                                | +---------------+ |
   |        |--(C)-- Access Token Request ---->|               | |
   |        |          + code_verifier       | |    Token      | |
   |        |                                | |   Endpoint    | |
   |        |<-(D)------ Access Token ---------|               | |
   +--------+                                | +---------------+ |
                                             +-------------------+

The PKCE flow requires a code challenge to be passed to the authorization endpoint and a code verifier to be sent to the token endpoint.

What this PR does / why we need it

Dex currently does not support PKCE flow for upstream OIDC providers.
However, some identity providers (IdPs) require PKCE flow support to complete the authentication process.

Key features

  • It uses dynamic configuration through OAuth2 discovery metadata (supports S256 and plain).
  • It is possible (but optional) to specify an algorithm to use in the PKCEChallenge key of the connector's config.
  • The generated code is saved in the connectorData of the auth request in the database, allowing the management of multiple PKCE connections simultaneously across multiple running instances of dex.

Does this PR introduce a user-facing change?

  • Adds the optional PKCEChallenge configuration option to the OIDC connector to specify an algorithm to use in the PKCE flow.

Special notes for your reviewer

Related PRs:

Related discussions:

@ClaudioNTT

ClaudioNTT commented Oct 2, 2024 •

Copy link
Copy Markdown

I've tested the PR, and it works as expected, using the PKCE flow with OAuth0 and PingFederate
@nabokihms @johnvan7 @cameronbrunner

@kratosmat

Copy link
Copy Markdown

Hi Giovanni,
I hope you receive the approval, we also need this feature, thanks a lot.

Comment thread connector/oidc/oidc.go Resolved
Comment thread connector/oidc/oidc.go Resolved
Comment thread connector/oidc/oidc.go Resolved
Comment thread connector/oidc/oidc.go Resolved
@nabokihms

nabokihms commented Oct 18, 2024 •

Copy link
Copy Markdown
Member

Could you also please sign your commits? DCO will not pass otherwise

@johnvan7 johnvan7 changed the title Add support to PKCE in OIDC connector Add support to PKCE in OIDC connector Signed-off-by: johnvan7 <[email protected]> Oct 19, 2024
@johnvan7 johnvan7 changed the title Add support to PKCE in OIDC connector Signed-off-by: johnvan7 <[email protected]> Add support to PKCE in OIDC connector Oct 19, 2024
@johnvan7
johnvan7 force-pushed the feat/pkce-challenge-support branch 2 times, most recently from 4c63988 to 6eee8c1 Compare October 19, 2024 15:17
@johnvan7

Copy link
Copy Markdown
Contributor Author

@nabokihms I've done the requested changes and signed my commits.
I've added pkceVerifierCache to handle multiple concurrent connections, inspired by PR #3195.

@johnvan7
johnvan7 requested a review from nabokihms October 19, 2024 15:24
Comment thread connector/oidc/oidc.go Resolved
Signed-off-by: johnvan7 <[email protected]>
Signed-off-by: Giovanni Vella <[email protected]>
Signed-off-by: johnvan7 <[email protected]>
Signed-off-by: Giovanni Vella <[email protected]>
Signed-off-by: johnvan7 <[email protected]>
Signed-off-by: Giovanni Vella <[email protected]>
@johnvan7
johnvan7 force-pushed the feat/pkce-challenge-support branch from 09dea1c to 39299d7 Compare October 25, 2024 13:10
@nabokihms

Copy link
Copy Markdown
Member

@johnvan7 could you please investigate the issue with tests and the lint?

Signed-off-by: Giovanni Vella <[email protected]>
@johnvan7
johnvan7 force-pushed the feat/pkce-challenge-support branch from b5d3b67 to 432c432 Compare October 28, 2024 09:16
@johnvan7

Copy link
Copy Markdown
Contributor Author

@nabokihms could you please restart workflows?
It should be fixed

@nabokihms

Copy link
Copy Markdown
Member

@sagikazarmark could you please take a look? There is an important change to the rock solid interface. Are you OK with this?

@johnvan7
johnvan7 marked this pull request as draft December 23, 2024 08:32
@johnvan7
johnvan7 marked this pull request as ready for review December 23, 2024 08:32
@krumware

Copy link
Copy Markdown

Would be great to have this

@mAhmpuere

Copy link
Copy Markdown

please approve, this would solve problems!

@rbmoore

rbmoore commented Nov 24, 2025

Copy link
Copy Markdown

@nabokihms @sagikazarmark this PR would greatly help my team. Could it please be approved and merged?

@cardoe

cardoe commented Dec 9, 2025

Copy link
Copy Markdown
Contributor

I've created a purely rebased version of this PR at https://github.com/cardoe/dex/tree/feat/pkce-challenge-support but then I noticed that:

  • one commit adds a LRU and the next one removes it
  • one commit is empty to just trigger CI
  • the last two commits are fixes to make prior ones pass tests

So I've made a branch https://github.com/cardoe/dex/tree/feat/pkce-challenge-support-squashed which cleans up history. @johnvan7 you're welcome to use either of these. I'll work with the maintainers to get this merged by testing it locally here.

cardoe added a commit to cardoe/dex that referenced this pull request Dec 9, 2025
This is using my rebased squashed version.
@cardoe

cardoe commented Dec 9, 2025

Copy link
Copy Markdown
Contributor

To further this along, I've pulled the squashed branch into a build that I made at https://github.com/cardoe/dex/releases/tag/v2.44.90 You can grab the container to test with at ghcr.io/cardoe/dex:v2.44.90 and report back on this PR.

@johnvan7

Copy link
Copy Markdown
Contributor Author

Hi @cardoe, I've tested ghcr.io/cardoe/dex:v2.44.90 with a connector that requires the PKCE flow and it works as expected!

@cardoe

cardoe commented Dec 10, 2025

Copy link
Copy Markdown
Contributor

Hi @cardoe, I've tested ghcr.io/cardoe/dex:v2.44.90 with a connector that requires the PKCE flow and it works as expected!

Thanks for confirming. Took me a bit to test as well. I can confirm it works.

@KihyeokK

Copy link
Copy Markdown

Would really appreciate it if this PR can get reviewed soon 🙏

@manawasp

manawasp commented Dec 19, 2025 •

Copy link
Copy Markdown

Same here for what I have tested it works great!

(Thanks for it 🙏)

@nabokihms

Copy link
Copy Markdown
Member

@sagikazarmark this feature still seems important, and the interface change looks like the right one. Could you please come back to the review one more time?

About the interface change, I remember discussing it here #2040
Personally I can imagine connectors passing the data to auth request after login to use it while handling the callback.

@nabokihms

Copy link
Copy Markdown
Member

@sagikazarmark, not the best options, but with this, we can preserve the interface. The only problem is that we will lose all compiler help (and probably IDE support as well):

diff --git a/connector/connector.go b/connector/connector.go
index d812390f..ec8c3a8a 100644
--- a/connector/connector.go
+++ b/connector/connector.go
@@ -47,6 +47,13 @@ type PasswordConnector interface {
        Login(ctx context.Context, s Scopes, username, password string) (identity Identity, validPassword bool, err error)
 }
 
+type LoginResult struct {
+       // CallbackURL is the URL to redirect the user to after authentication.
+       CallbackURL string
+       // Connector data is stored in the auth request to handle the state before receiving the callback.
+       ConnectorData []byte
+}
+
 // CallbackConnector is an interface implemented by connectors which use an OAuth
 // style redirect flow to determine user information.
 type CallbackConnector interface {
@@ -63,7 +70,7 @@ type CallbackConnector interface {
        // requested if one has already been issues. There's no good general answer
        // for these kind of restrictions, and may require this package to become more
        // aware of the global set of user/connector interactions.
-       LoginURL(s Scopes, callbackURL, state string) (string, error)
+       LoginURL(s Scopes, callbackURL, state string) (any, error)
 
        // Handle the callback to the server and return an identity.
        HandleCallback(s Scopes, r *http.Request) (identity Identity, err error)
diff --git a/server/handlers.go b/server/handlers.go
index 1292b8ee..ea78766d 100644
--- a/server/handlers.go
+++ b/server/handlers.go
@@ -271,12 +271,35 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
                        // Use the auth request ID as the "state" token.
                        //
                        // TODO(ericchiang): Is this appropriate or should we also be using a nonce?
-                       callbackURL, err := conn.LoginURL(scopes, s.absURL("/callback"), authReq.ID)
+                       callbackURL, connectorData := "", []byte("")
+                       res, err := conn.LoginURL(scopes, s.absURL("/callback"), authReq.ID)
                        if err != nil {
                                s.logger.ErrorContext(r.Context(), "connector returned error when creating callback", "connector_id", connID, "err", err)
                                s.renderError(r, w, http.StatusInternalServerError, "Login error.")
                                return
                        }
+                       switch res.(type) {
+                       case string:
+                               callbackURL = res.(string)
+                       case *connector.LoginResult:
+                               val := res.(*connector.LoginResult)
+                               callbackURL, connectorData = val.CallbackURL, val.ConnectorData
+                       default:
+                               s.logger.ErrorContext(r.Context(), fmt.Sprintf("connector returned invalid type: %T", res), "connector_id", connID)
+                               s.renderError(r, w, http.StatusInternalServerError, "Login error.")
+                       }
+                       if len(connectorData) > 0 {
+                               updater := func(a storage.AuthRequest) (storage.AuthRequest, error) {
+                                       a.ConnectorData = connectorData
+                                       return a, nil
+                               }
+                               err := s.storage.UpdateAuthRequest(ctx, authReq.ID, updater)
+                               if err != nil {
+                                       s.logger.ErrorContext(r.Context(), "Failed to set connector data on auth request", "connector_id", connID, "err", err)
+                                       s.renderError(r, w, http.StatusInternalServerError, "Database error.")
+                                       return
+                               }
+                       }
                        http.Redirect(w, r, callbackURL, http.StatusFound)
                case connector.PasswordConnector:
                        loginURL := url.URL{

@nabokihms

Copy link
Copy Markdown
Member

Thinking out of the box. Another way to preserve the interface.

@sagikazarmark could you please pick the one you like the most?

diff --git a/connector/connector.go b/connector/connector.go
index d812390f..11d6f046 100644
--- a/connector/connector.go
+++ b/connector/connector.go
@@ -4,6 +4,7 @@ package connector
 import (
        "context"
        "net/http"
+       "strings"
 )
 
 // Connector is a mechanism for federating login to a remote identity service.
@@ -47,6 +48,27 @@ type PasswordConnector interface {
        Login(ctx context.Context, s Scopes, username, password string) (identity Identity, validPassword bool, err error)
 }
 
+const delimiter = "\x00"
+
+type LoginResult struct {
+       // CallbackURL is the URL to redirect the user to after authentication.
+       CallbackURL string
+       // Connector data is stored in the auth request to handle the state before receiving the callback.
+       ConnectorData []byte
+}
+
+func (r LoginResult) String() string {
+       return r.CallbackURL + delimiter + string(r.ConnectorData)
+}
+
+func LoginResultFromString(s string) LoginResult {
+       parts := strings.SplitN(s, delimiter, 2)
+       if len(parts) != 2 {
+               return LoginResult{CallbackURL: s}
+       }
+       return LoginResult{CallbackURL: parts[0], ConnectorData: []byte(parts[1])}
+}
+
 // CallbackConnector is an interface implemented by connectors which use an OAuth
 // style redirect flow to determine user information.
 type CallbackConnector interface {
diff --git a/server/handlers.go b/server/handlers.go
index 1292b8ee..36f97a57 100644
--- a/server/handlers.go
+++ b/server/handlers.go
@@ -271,13 +271,27 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
                        // Use the auth request ID as the "state" token.
                        //
                        // TODO(ericchiang): Is this appropriate or should we also be using a nonce?
-                       callbackURL, err := conn.LoginURL(scopes, s.absURL("/callback"), authReq.ID)
+                       res, err := conn.LoginURL(scopes, s.absURL("/callback"), authReq.ID)
                        if err != nil {
                                s.logger.ErrorContext(r.Context(), "connector returned error when creating callback", "connector_id", connID, "err", err)
                                s.renderError(r, w, http.StatusInternalServerError, "Login error.")
                                return
                        }
-                       http.Redirect(w, r, callbackURL, http.StatusFound)
+                       loginResult := connector.LoginResultFromString(res)
+                       if len(loginResult.ConnectorData) > 0 {
+                               updater := func(a storage.AuthRequest) (storage.AuthRequest, error) {
+                                       a.ConnectorData = loginResult.ConnectorData
+                                       return a, nil
+                               }
+                               err := s.storage.UpdateAuthRequest(ctx, authReq.ID, updater)
+                               if err != nil {
+                                       s.logger.ErrorContext(r.Context(), "Failed to set connector data on auth request", "connector_id", connID, "err", err)
+                                       s.renderError(r, w, http.StatusInternalServerError, "Database error.")
+                                       return
+                               }
+                       }
+
+                       http.Redirect(w, r, loginResult.CallbackURL, http.StatusFound)
                case connector.PasswordConnector:
                        loginURL := url.URL{
                                Path: s.absPath("/auth", connID, "login"),

@sagikazarmark

Copy link
Copy Markdown
Member

I don't mind an interface change if it's justified. I'd rather change the interface than rely on hacks. :)

In this case, changing it is probably the right thing to do.

@nabokihms nabokihms left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this being said, thank you @johnvan7 for the PR and for all the patience.

Congratulations to all people subscribed to this thread! Today, we are celebrating a new long-awaited feature and the first connector interface change in literally 10 years.

@nabokihms nabokihms added the release-note/new-feature Release note: Exciting New Features label Feb 22, 2026
@nabokihms
nabokihms merged commit 25591ee into dexidp:master Feb 22, 2026
paurosello pushed a commit to giantswarm/dex that referenced this pull request Jul 14, 2026
Cherry-pick of upstream dexidp#4845 (e8aaa98), which is merged to
upstream master but not yet in any release (latest release v2.45.1 is
from before the merge).

Adapts the new test's single HandleCallback call site from the 3-arg
signature (introduced upstream by PKCE PR dexidp#3777, not present in this
fork) back to the 2-arg signature on this branch. Production code
applies unchanged.

Fixes forced re-login after ~8h for GitHub App-backed connectors.

Signed-off-by: Matheus Pimenta <[email protected]>
(cherry picked from commit e8aaa98)

Closes: giantswarm/giantswarm#37164

Co-authored-by: Matheus Pimenta <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement release-note/new-feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.