From 25cdb7b18eb41821d76e99ae98929e2b5d714b96 Mon Sep 17 00:00:00 2001 From: Kailash Nadh Date: Wed, 23 Oct 2024 15:09:05 +0530 Subject: [PATCH] Pull e-mail from userinfo endpoint if OIDC token endpoint doesn't return it. --- internal/auth/auth.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 73572594..8b9a7ab0 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -73,6 +73,7 @@ type Auth struct { cfg Config oauthCfg oauth2.Config verifier *oidc.IDTokenVerifier + provider *oidc.Provider sess *simplesessions.Manager sessStore *postgres.Store cb *Callbacks @@ -92,9 +93,9 @@ func New(cfg Config, db *sql.DB, cb *Callbacks, lo *log.Logger) (*Auth, error) { if cfg.OIDC.Enabled { provider, err := oidc.NewProvider(context.Background(), cfg.OIDC.ProviderURL) if err != nil { + cfg.OIDC.Enabled = false lo.Printf("error initializing OIDC OAuth provider: %v", err) } else { - a.verifier = provider.Verifier(&oidc.Config{ ClientID: cfg.OIDC.ClientID, }) @@ -106,6 +107,7 @@ func New(cfg Config, db *sql.DB, cb *Callbacks, lo *log.Logger) (*Auth, error) { RedirectURL: cfg.OIDC.RedirectURL, Scopes: []string{oidc.ScopeOpenID, "profile", "email"}, } + a.provider = provider } } @@ -202,6 +204,19 @@ func (o *Auth) ExchangeOIDCToken(code, nonce string) (string, OIDCclaim, error) return "", OIDCclaim{}, errors.New("error getting user from OIDC") } + // If claims doesn't have the e-mail, attempt to fetch it from the userinfo endpoint. + if claims.Email == "" { + userInfo, err := o.provider.UserInfo(context.TODO(), oauth2.StaticTokenSource(tk)) + if err != nil { + return "", OIDCclaim{}, errors.New("error fetching user info from OIDC") + } + + // Parse the UserInfo claims into the claims struct + if err := userInfo.Claims(&claims); err != nil { + return "", OIDCclaim{}, errors.New("error parsing user info claims") + } + } + return rawIDTk, claims, nil }