Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/auth/extauth/oidc_login.go

raw symbols SCIP
1 // Copyright 2026 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 // This file implements OIDC Authorization Code flow for obtaining ID tokens
6 // as part of Enterprise Managed Authorization (SEP-990).
7 // See https://openid.net/specs/openid-connect-core-1_0.html
8
9 package extauth
10
11 import (
12 "context"
13 "crypto/rand"
14 "fmt"
15 "net/http"
16 "net/url"
17 "slices"
18 "strings"
19
20 "github.com/modelcontextprotocol/go-sdk/auth"
21 "github.com/modelcontextprotocol/go-sdk/oauthex"
22 "golang.org/x/oauth2"
23 )
24
25 // OIDCLoginConfig configures the OIDC Authorization Code flow for obtaining
26 // an ID Token. This is used with [PerformOIDCLogin] to authenticate users
27 // with an enterprise IdP before calling the Enterprise Managed Authorization flow.
28 type OIDCLoginConfig struct {
29 // IssuerURL is the IdP's issuer URL (e.g., "https://acme.okta.com").
30 // REQUIRED.
31 IssuerURL string
32 // Credentials contains the MCP Client's credentials registered at the IdP.
33 // The ClientID field is REQUIRED. The ClientSecret field is OPTIONAL
34 // (only required if the client is confidential, not a public client).
35 // REQUIRED (struct itself), but ClientSecret field can be empty.
36 Credentials *oauthex.ClientCredentials
37 // RedirectURL is the OAuth2 redirect URI registered with the IdP.
38 // This must match exactly what was registered with the IdP.
39 // REQUIRED.
40 RedirectURL string
41 // Scopes are the OAuth2/OIDC scopes to request.
42 // "openid" is REQUIRED for OIDC. Common values: ["openid", "profile", "email"]
43 // REQUIRED.
44 Scopes []string
45 // LoginHint is a hint to the IdP about the user's identity.
46 // Some IdPs may require this (e.g., as an email address for routing to SSO providers).
47 // Example: "[email protected]"
48 // OPTIONAL.
49 LoginHint string
50 // HTTPClient is the HTTP client for making requests.
51 // If nil, http.DefaultClient is used.
52 // OPTIONAL.
53 HTTPClient *http.Client
54 }
55
56 // PerformOIDCLogin performs the complete OIDC Authorization Code flow with PKCE
57 // in a single function call. This is the recommended approach for obtaining an
58 // ID Token for use with [EnterpriseHandler].
59 //
60 // Returns an oauth2.Token where:
61 // - Extra("id_token") contains the OpenID Connect ID Token (JWT)
62 // - AccessToken contains the OAuth2 access token (if issued by IdP)
63 // - RefreshToken contains the OAuth2 refresh token (if issued by IdP)
64 // - TokenType is the token type (typically "Bearer")
65 // - Expiry is when the token expires
66 func PerformOIDCLogin(
67 ctx context.Context,
68 config *OIDCLoginConfig,
69 authCodeFetcher auth.AuthorizationCodeFetcher,
70 ) (*oauth2.Token, error) {
71 if authCodeFetcher == nil {
72 return nil, fmt.Errorf("authCodeFetcher is required")
73 }
74
75 authReq, oauth2Config, err := initiateOIDCLogin(ctx, config)
76 if err != nil {
77 return nil, fmt.Errorf("failed to initiate OIDC login: %w", err)
78 }
79
80 authResult, err := authCodeFetcher(ctx, &auth.AuthorizationArgs{URL: authReq.authURL})
81 if err != nil {
82 return nil, fmt.Errorf("failed to fetch authorization code: %w", err)
83 }
84
85 if authResult.State != authReq.state {
86 return nil, fmt.Errorf("state mismatch: expected %q, got %q", authReq.state, authResult.State)
87 }
88
89 tokens, err := completeOIDCLogin(ctx, config, oauth2Config, authResult.Code, authReq.codeVerifier)
90 if err != nil {
91 return nil, fmt.Errorf("failed to complete OIDC login: %w", err)
92 }
93
94 return tokens, nil
95 }
96
97 // oidcAuthorizationRequest holds internal state for OIDC authorization.
98 type oidcAuthorizationRequest struct {
99 authURL string
100 state string
101 codeVerifier string
102 }
103
104 // initiateOIDCLogin initiates an OIDC Authorization Code flow with PKCE.
105 func initiateOIDCLogin(
106 ctx context.Context,
107 config *OIDCLoginConfig,
108 ) (*oidcAuthorizationRequest, *oauth2.Config, error) {
109 if config == nil {
110 return nil, nil, fmt.Errorf("config is required")
111 }
112 if config.IssuerURL == "" {
113 return nil, nil, fmt.Errorf("IssuerURL is required")
114 }
115 if config.Credentials == nil || config.Credentials.ClientID == "" {
116 return nil, nil, fmt.Errorf("Credentials.ClientID is required")
117 }
118 if config.RedirectURL == "" {
119 return nil, nil, fmt.Errorf("RedirectURL is required")
120 }
121 if len(config.Scopes) == 0 {
122 return nil, nil, fmt.Errorf("at least one scope is required (must include 'openid')")
123 }
124
125 if !slices.Contains(config.Scopes, "openid") {
126 return nil, nil, fmt.Errorf("the 'openid' scope is required for OIDC")
127 }
128
129 if err := checkURLScheme(config.IssuerURL); err != nil {
130 return nil, nil, fmt.Errorf("invalid IssuerURL: %w", err)
131 }
132 if err := checkURLScheme(config.RedirectURL); err != nil {
133 return nil, nil, fmt.Errorf("invalid RedirectURL: %w", err)
134 }
135
136 httpClient := config.HTTPClient
137 if httpClient == nil {
138 httpClient = http.DefaultClient
139 }
140 meta, err := auth.GetAuthServerMetadata(ctx, config.IssuerURL, httpClient)
141 if err != nil {
142 return nil, nil, fmt.Errorf("failed to discover OIDC metadata: %w", err)
143 }
144 if meta == nil {
145 return nil, nil, fmt.Errorf("no authorization server metadata found for OIDC issuer: %s", config.IssuerURL)
146 }
147 if meta.AuthorizationEndpoint == "" {
148 return nil, nil, fmt.Errorf("authorization_endpoint not found in OIDC metadata")
149 }
150
151 codeVerifier := oauth2.GenerateVerifier()
152 state := rand.Text()
153
154 oauth2Config := &oauth2.Config{
155 ClientID: config.Credentials.ClientID,
156 RedirectURL: config.RedirectURL,
157 Scopes: config.Scopes,
158 Endpoint: oauth2.Endpoint{
159 AuthURL: meta.AuthorizationEndpoint,
160 TokenURL: meta.TokenEndpoint,
161 },
162 }
163 // Set ClientSecret if ClientSecretAuth is configured
164 if config.Credentials.ClientSecretAuth != nil {
165 oauth2Config.ClientSecret = config.Credentials.ClientSecretAuth.ClientSecret
166 }
167
168 authURLOpts := []oauth2.AuthCodeOption{
169 oauth2.S256ChallengeOption(codeVerifier),
170 }
171 if config.LoginHint != "" {
172 authURLOpts = append(authURLOpts, oauth2.SetAuthURLParam("login_hint", config.LoginHint))
173 }
174 authURL := oauth2Config.AuthCodeURL(state, authURLOpts...)
175
176 return &oidcAuthorizationRequest{
177 authURL: authURL,
178 state: state,
179 codeVerifier: codeVerifier,
180 }, oauth2Config, nil
181 }
182
183 // completeOIDCLogin completes the OIDC Authorization Code flow by exchanging
184 // the authorization code for tokens.
185 func completeOIDCLogin(
186 ctx context.Context,
187 config *OIDCLoginConfig,
188 oauth2Config *oauth2.Config,
189 authCode string,
190 codeVerifier string,
191 ) (*oauth2.Token, error) {
192 if authCode == "" {
193 return nil, fmt.Errorf("authCode is required")
194 }
195 if codeVerifier == "" {
196 return nil, fmt.Errorf("codeVerifier is required")
197 }
198
199 httpClient := config.HTTPClient
200 if httpClient == nil {
201 httpClient = http.DefaultClient
202 }
203 ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, httpClient)
204
205 oauth2Token, err := oauth2Config.Exchange(
206 ctxWithClient,
207 authCode,
208 oauth2.VerifierOption(codeVerifier),
209 )
210 if err != nil {
211 return nil, fmt.Errorf("token exchange failed: %w", err)
212 }
213
214 // Validate that id_token is present in the response
215 idToken, ok := oauth2Token.Extra("id_token").(string)
216 if !ok || idToken == "" {
217 return nil, fmt.Errorf("id_token not found in token response")
218 }
219
220 return oauth2Token, nil
221 }
222
223 // checkURLScheme ensures that its argument is a valid URL with a scheme
224 // that prevents XSS attacks.
225 // See #526.
226 // Note: a copy of this function exists in oauthex/oauth2.go; keep these in sync.
227 func checkURLScheme(u string) error {
228 if u == "" {
229 return nil
230 }
231 uu, err := url.Parse(u)
232 if err != nil {
233 return err
234 }
235 scheme := strings.ToLower(uu.Scheme)
236 if scheme == "javascript" || scheme == "data" || scheme == "vbscript" {
237 return fmt.Errorf("URL has disallowed scheme %q", scheme)
238 }
239 return nil
240 }