@@ -11,6 +11,7 @@ import (
1111 "crypto/rand"
1212 "errors"
1313 "fmt"
14+ "io"
1415 "net/http"
1516 "net/url"
1617 "slices"
@@ -20,18 +21,6 @@ import (
2021 "golang.org/x/oauth2"
2122)
2223
23- // ClientSecretAuthConfig is used to configure client authentication using client_secret.
24- // Authentication method will be selected based on the authorization server's supported methods,
25- // according to the following preference order:
26- // 1. client_secret_post
27- // 2. client_secret_basic
28- type ClientSecretAuthConfig struct {
29- // ClientID is the client ID to be used for client authentication.
30- ClientID string
31- // ClientSecret is the client secret to be used for client authentication.
32- ClientSecret string
33- }
34-
3524// ClientIDMetadataDocumentConfig is used to configure the Client ID Metadata Document
3625// based client registration per
3726// https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#client-id-metadata-documents.
@@ -42,14 +31,6 @@ type ClientIDMetadataDocumentConfig struct {
4231 URL string
4332}
4433
45- // PreregisteredClientConfig is used to configure a pre-registered client per
46- // https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#preregistration.
47- // Currently only "client_secret_basic" and "client_secret_post" authentication methods are supported.
48- type PreregisteredClientConfig struct {
49- // ClientSecretAuthConfig is the client_secret based configuration to be used for client authentication.
50- ClientSecretAuthConfig * ClientSecretAuthConfig
51- }
52-
5334// DynamicClientRegistrationConfig is used to configure dynamic client registration per
5435// https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#dynamic-client-registration.
5536type DynamicClientRegistrationConfig struct {
@@ -67,12 +48,18 @@ type AuthorizationResult struct {
6748 State string
6849}
6950
70- // AuthorizationArgs is the input to [AuthorizationCodeHandlerConfig]. AuthorizationCodeFetcher.
51+ // AuthorizationArgs is the input to [AuthorizationCodeFetcher] .
7152type AuthorizationArgs struct {
7253 // Authorization URL to be opened in a browser for the user to start the authorization process.
7354 URL string
7455}
7556
57+ // AuthorizationCodeFetcher is called to initiate the OAuth authorization flow.
58+ // It is responsible for directing the user to the authorization URL (e.g., opening
59+ // in a browser) and returning the authorization code and state once the Authorization
60+ // Server redirects back to the configured RedirectURL.
61+ type AuthorizationCodeFetcher func (ctx context.Context , args * AuthorizationArgs ) (* AuthorizationResult , error )
62+
7663// AuthorizationCodeHandlerConfig is the configuration for [AuthorizationCodeHandler].
7764type AuthorizationCodeHandlerConfig struct {
7865 // Client registration configuration.
@@ -82,7 +69,7 @@ type AuthorizationCodeHandlerConfig struct {
8269 // 3. Dynamic Client Registration
8370 // At least one method must be configured.
8471 ClientIDMetadataDocumentConfig * ClientIDMetadataDocumentConfig
85- PreregisteredClientConfig * PreregisteredClientConfig
72+ PreregisteredClient * oauthex. ClientCredentials
8673 DynamicClientRegistrationConfig * DynamicClientRegistrationConfig
8774
8875 // RedirectURL is a required URL to redirect to after authorization.
@@ -97,10 +84,8 @@ type AuthorizationCodeHandlerConfig struct {
9784 RedirectURL string
9885
9986 // AuthorizationCodeFetcher is a required function called to initiate the authorization flow.
100- // It is responsible for opening the URL in a browser for the user to start the authorization process.
101- // It should return the authorization code and state once the Authorization Server
102- // redirects back to the RedirectURL.
103- AuthorizationCodeFetcher func (ctx context.Context , args * AuthorizationArgs ) (* AuthorizationResult , error )
87+ // See [AuthorizationCodeFetcher] for details.
88+ AuthorizationCodeFetcher AuthorizationCodeFetcher
10489
10590 // Client is an optional HTTP client to use for HTTP requests.
10691 // It is used for the following requests:
@@ -127,8 +112,6 @@ type AuthorizationCodeHandler struct {
127112
128113var _ OAuthHandler = (* AuthorizationCodeHandler )(nil )
129114
130- func (h * AuthorizationCodeHandler ) isOAuthHandler () {}
131-
132115func (h * AuthorizationCodeHandler ) TokenSource (ctx context.Context ) (oauth2.TokenSource , error ) {
133116 return h .tokenSource , nil
134117}
@@ -141,7 +124,7 @@ func NewAuthorizationCodeHandler(config *AuthorizationCodeHandlerConfig) (*Autho
141124 return nil , errors .New ("config must be provided" )
142125 }
143126 if config .ClientIDMetadataDocumentConfig == nil &&
144- config .PreregisteredClientConfig == nil &&
127+ config .PreregisteredClient == nil &&
145128 config .DynamicClientRegistrationConfig == nil {
146129 return nil , errors .New ("at least one client registration configuration must be provided" )
147130 }
@@ -151,13 +134,9 @@ func NewAuthorizationCodeHandler(config *AuthorizationCodeHandlerConfig) (*Autho
151134 if config .ClientIDMetadataDocumentConfig != nil && ! isNonRootHTTPSURL (config .ClientIDMetadataDocumentConfig .URL ) {
152135 return nil , fmt .Errorf ("client ID metadata document URL must be a non-root HTTPS URL" )
153136 }
154- preCfg := config .PreregisteredClientConfig
155- if preCfg != nil {
156- if preCfg .ClientSecretAuthConfig == nil {
157- return nil , errors .New ("ClientSecretAuthConfig is required for pre-registered client" )
158- }
159- if preCfg .ClientSecretAuthConfig .ClientID == "" || preCfg .ClientSecretAuthConfig .ClientSecret == "" {
160- return nil , fmt .Errorf ("pre-registered client ID or secret is empty" )
137+ if config .PreregisteredClient != nil {
138+ if err := config .PreregisteredClient .Validate (); err != nil {
139+ return nil , fmt .Errorf ("invalid PreregisteredClient configuration: %w" , err )
161140 }
162141 }
163142 dCfg := config .DynamicClientRegistrationConfig
@@ -198,6 +177,7 @@ func isNonRootHTTPSURL(u string) bool {
198177// On success, [AuthorizationCodeHandler.TokenSource] will return a token source with the fetched token.
199178func (h * AuthorizationCodeHandler ) Authorize (ctx context.Context , req * http.Request , resp * http.Response ) error {
200179 defer resp .Body .Close ()
180+ defer io .Copy (io .Discard , resp .Body )
201181
202182 wwwChallenges , err := oauthex .ParseWWWAuthenticate (resp .Header [http .CanonicalHeaderKey ("WWW-Authenticate" )])
203183 if err != nil {
@@ -218,9 +198,20 @@ func (h *AuthorizationCodeHandler) Authorize(ctx context.Context, req *http.Requ
218198 return err
219199 }
220200
221- asm , err := h . getAuthServerMetadata (ctx , prm )
201+ asm , err := GetAuthServerMetadata (ctx , prm . AuthorizationServers [ 0 ], h . config . Client )
222202 if err != nil {
223- return err
203+ return fmt .Errorf ("failed to get authorization server metadata: %w" , err )
204+ }
205+ if asm == nil {
206+ // Fallback to 2025-03-26 spec: predefined endpoints.
207+ // https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#fallbacks-for-servers-without-metadata-discovery
208+ authServerURL := prm .AuthorizationServers [0 ]
209+ asm = & oauthex.AuthServerMeta {
210+ Issuer : authServerURL ,
211+ AuthorizationEndpoint : authServerURL + "/authorize" ,
212+ TokenEndpoint : authServerURL + "/token" ,
213+ RegistrationEndpoint : authServerURL + "/register" ,
214+ }
224215 }
225216
226217 resolvedClientConfig , err := h .handleRegistration (ctx , asm )
@@ -365,70 +356,6 @@ func protectedResourceMetadataURLs(metadataURL, resourceURL string) []prmURL {
365356 return urls
366357}
367358
368- // getAuthServerMetadata returns the authorization server metadata.
369- // The provided Protected Resource Metadata must not be nil and must contain
370- // at least one authorization server.
371- // It returns an error if the metadata request fails with non-4xx HTTP status code
372- // or the fetched metadata fails security checks.
373- // If no metadata was found, it returns a minimal set of endpoints
374- // as a fallback to 2025-03-26 spec.
375- func (h * AuthorizationCodeHandler ) getAuthServerMetadata (ctx context.Context , prm * oauthex.ProtectedResourceMetadata ) (* oauthex.AuthServerMeta , error ) {
376- authServerURL := prm .AuthorizationServers [0 ]
377- for _ , u := range authorizationServerMetadataURLs (authServerURL ) {
378- asm , err := oauthex .GetAuthServerMeta (ctx , u , authServerURL , h .config .Client )
379- if err != nil {
380- return nil , fmt .Errorf ("failed to get authorization server metadata: %w" , err )
381- }
382- if asm != nil {
383- return asm , nil
384- }
385- }
386-
387- // Fallback to 2025-03-26 spec: predefined endpoints.
388- // https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#fallbacks-for-servers-without-metadata-discovery
389- asm := & oauthex.AuthServerMeta {
390- Issuer : authServerURL ,
391- AuthorizationEndpoint : authServerURL + "/authorize" ,
392- TokenEndpoint : authServerURL + "/token" ,
393- RegistrationEndpoint : authServerURL + "/register" ,
394- }
395- return asm , nil
396- }
397-
398- // authorizationServerMetadataURLs returns a list of URLs to try when looking for
399- // authorization server metadata as mandated by the MCP specification:
400- // https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#authorization-server-metadata-discovery.
401- func authorizationServerMetadataURLs (issuerURL string ) []string {
402- var urls []string
403-
404- baseURL , err := url .Parse (issuerURL )
405- if err != nil {
406- return nil
407- }
408-
409- if baseURL .Path == "" {
410- // "OAuth 2.0 Authorization Server Metadata".
411- baseURL .Path = "/.well-known/oauth-authorization-server"
412- urls = append (urls , baseURL .String ())
413- // "OpenID Connect Discovery 1.0".
414- baseURL .Path = "/.well-known/openid-configuration"
415- urls = append (urls , baseURL .String ())
416- return urls
417- }
418-
419- originalPath := baseURL .Path
420- // "OAuth 2.0 Authorization Server Metadata with path insertion".
421- baseURL .Path = "/.well-known/oauth-authorization-server/" + strings .TrimLeft (originalPath , "/" )
422- urls = append (urls , baseURL .String ())
423- // "OpenID Connect Discovery 1.0 with path insertion".
424- baseURL .Path = "/.well-known/openid-configuration/" + strings .TrimLeft (originalPath , "/" )
425- urls = append (urls , baseURL .String ())
426- // "OpenID Connect Discovery 1.0 with path appending".
427- baseURL .Path = "/" + strings .Trim (originalPath , "/" ) + "/.well-known/openid-configuration"
428- urls = append (urls , baseURL .String ())
429- return urls
430- }
431-
432359type registrationType int
433360
434361const (
@@ -491,13 +418,17 @@ func (h *AuthorizationCodeHandler) handleRegistration(ctx context.Context, asm *
491418 }, nil
492419 }
493420 // 2. Attempt to use pre-registered client configuration.
494- pCfg := h .config .PreregisteredClientConfig
495- if pCfg != nil {
421+ preCfg := h .config .PreregisteredClient
422+ if preCfg != nil {
496423 authStyle := selectTokenAuthMethod (asm .TokenEndpointAuthMethodsSupported )
424+ clientSecret := ""
425+ if preCfg .ClientSecretAuth != nil {
426+ clientSecret = preCfg .ClientSecretAuth .ClientSecret
427+ }
497428 return & resolvedClientConfig {
498429 registrationType : registrationTypePreregistered ,
499- clientID : pCfg . ClientSecretAuthConfig .ClientID ,
500- clientSecret : pCfg . ClientSecretAuthConfig . ClientSecret ,
430+ clientID : preCfg .ClientID ,
431+ clientSecret : clientSecret ,
501432 authStyle : authStyle ,
502433 }, nil
503434 }
0 commit comments