Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Send a PKCE code challenge on the OIDC login flow when the provider supports it. (#3219)

Stephen J. Fuhry60e5e16f04af
diff --git a/cmd/auth.go b/cmd/auth.go
index 18b3ced7..49c278e0 100644
--- a/cmd/auth.go
+++ b/cmd/auth.go
@@ -197,8 +197,35 @@ func (a *App) OIDCLogin(c echo.Context) error {
return echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("globals.messages.internalError"))
}
+ authURL, codeVerifier := a.auth.GetOIDCAuthURL(base64.URLEncoding.EncodeToString(b), nonce.Value)
+
+ if authURL == "" {
+ return echo.NewHTTPError(http.StatusInternalServerError, a.i18n.T("globals.messages.internalError"))
+ }
+
+ // Store the verifier for the callback, or clear a stale cookie if PKCE is disabled.
+ a.setOIDCVerifierCookie(c, codeVerifier)
+
// Redirect to the external OIDC provider.
- return c.Redirect(http.StatusFound, a.auth.GetOIDCAuthURL(base64.URLEncoding.EncodeToString(b), nonce.Value))
+ return c.Redirect(http.StatusFound, authURL)
+}
+
+// setOIDCVerifierCookie stores the PKCE verifier or deletes it if it's empty.
+func (a *App) setOIDCVerifierCookie(c echo.Context, verifier string) {
+ ck := &http.Cookie{
+ Name: "oidc_code_verifier",
+ Value: verifier,
+ HttpOnly: true,
+ Secure: strings.HasPrefix(a.urlCfg.RootURL, "https://"),
+ Path: "/",
+ SameSite: http.SameSiteLaxMode,
+ }
+
+ if verifier == "" {
+ ck.MaxAge = -1
+ }
+
+ c.SetCookie(ck)
}
// OIDCFinish receives the redirect callback from the OIDC provider and completes the handshake.
@@ -209,8 +236,15 @@ func (a *App) OIDCFinish(c echo.Context) error {
return a.renderLoginPage(c, echo.NewHTTPError(http.StatusUnauthorized, a.i18n.T("users.invalidRequest")))
}
+ // Get the PKCE code verifier set on the login request, if any, and clear it as it's single-use.
+ codeVerifier := ""
+ if ck, err := c.Cookie("oidc_code_verifier"); err == nil {
+ codeVerifier = ck.Value
+ a.setOIDCVerifierCookie(c, "")
+ }
+
// Validate the OIDC token.
- oidcToken, claims, err := a.auth.ExchangeOIDCToken(c.Request().URL.Query().Get("code"), nonce.Value)
+ oidcToken, claims, err := a.auth.ExchangeOIDCToken(c.Request().URL.Query().Get("code"), nonce.Value, codeVerifier)
if err != nil {
return a.renderLoginPage(c, err)
}
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
index 6731a513..d4aa5110 100644
--- a/internal/auth/auth.go
+++ b/internal/auth/auth.go
@@ -12,6 +12,7 @@ import (
"fmt"
"log"
"net/http"
+ "slices"
"strings"
"sync"
"time"
@@ -74,6 +75,9 @@ type Auth struct {
sessStore *postgres.Store
cb *Callbacks
log *log.Logger
+
+ // Whether the OIDC provider supports PKCE with the S256 challenge method.
+ pkce bool
}
var sessPruneInterval = time.Hour * 12
@@ -173,6 +177,17 @@ func (o *Auth) initOIDC() error {
}
o.provider = provider
+ // Only use PKCE (RFC 7636) if the provider's metadata advertises it, as providers
+ // that don't support it may reject the extra params.
+ var meta struct {
+ CodeChallengeMethods []string `json:"code_challenge_methods_supported"`
+ }
+ if err := provider.Claims(&meta); err != nil {
+ o.log.Printf("error reading OIDC provider metadata: %v", err)
+ } else {
+ o.pkce = slices.Contains(meta.CodeChallengeMethods, "S256")
+ }
+
return nil
}
@@ -202,38 +217,58 @@ func (o *Auth) getVerifier() (*oidc.IDTokenVerifier, error) {
return o.verifier, nil
}
-// getOAuthConfig returns the OAuth config, initializing it if necessary.
-func (o *Auth) getOAuthConfig() (*oauth2.Config, error) {
+// getOAuthConfig returns the OAuth config and whether the provider supports PKCE,
+// initializing them if necessary.
+func (o *Auth) getOAuthConfig() (*oauth2.Config, bool, error) {
o.Lock()
defer o.Unlock()
if o.oauthCfg.ClientID == "" {
if err := o.initOIDC(); err != nil {
- return nil, err
+ return nil, false, err
}
}
- return &o.oauthCfg, nil
+ return &o.oauthCfg, o.pkce, nil
}
-// GetOIDCAuthURL returns the OIDC provider's auth URL to redirect to.
-func (o *Auth) GetOIDCAuthURL(state, nonce string) string {
- cfg, err := o.getOAuthConfig()
+// GetOIDCAuthURL returns the OIDC provider's auth URL to redirect to and the PKCE code
+// verifier for the subsequent token exchange, empty if the provider doesn't support PKCE.
+func (o *Auth) GetOIDCAuthURL(state, nonce string) (string, string) {
+ cfg, pkce, err := o.getOAuthConfig()
if err != nil {
o.log.Printf("error getting OAuth config: %v", err)
- return ""
+ return "", ""
}
- return cfg.AuthCodeURL(state, oidc.Nonce(nonce))
+
+ opts := []oauth2.AuthCodeOption{oidc.Nonce(nonce)}
+
+ codeVerifier := ""
+ if pkce {
+ codeVerifier = oauth2.GenerateVerifier()
+ opts = append(opts, oauth2.S256ChallengeOption(codeVerifier))
+ }
+
+ return cfg.AuthCodeURL(state, opts...), codeVerifier
}
-// ExchangeOIDCToken takes an OIDC authorization code (recieved via redirect from the OIDC provider),
-// validates it, and returns an OIDC token for subsequent auth.
-func (o *Auth) ExchangeOIDCToken(code, nonce string) (string, OIDCclaim, error) {
- cfg, err := o.getOAuthConfig()
+// ExchangeOIDCToken takes an OIDC authorization code (received via redirect from the OIDC provider)
+// and the PKCE code verifier from the auth request, validates it, and returns an OIDC token for
+// subsequent auth.
+func (o *Auth) ExchangeOIDCToken(code, nonce, codeVerifier string) (string, OIDCclaim, error) {
+ cfg, pkce, err := o.getOAuthConfig()
if err != nil {
return "", OIDCclaim{}, echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("error getting OAuth config: %v", err))
}
- tk, err := cfg.Exchange(context.TODO(), code)
+ var opts []oauth2.AuthCodeOption
+ if pkce {
+ if codeVerifier == "" {
+ return "", OIDCclaim{}, echo.NewHTTPError(http.StatusUnauthorized, "PKCE code verifier missing")
+ }
+ opts = append(opts, oauth2.VerifierOption(codeVerifier))
+ }
+
+ tk, err := cfg.Exchange(context.TODO(), code, opts...)
if err != nil {
return "", OIDCclaim{}, echo.NewHTTPError(http.StatusUnauthorized, fmt.Sprintf("error exchanging token: %v", err))
}