Documentation
¶
Index ¶
- Variables
- func GetAuthServerMetadata(ctx context.Context, issuerURL string, httpClient *http.Client) (*oauthex.AuthServerMeta, error)
- func ProtectedResourceMetadataHandler(metadata *oauthex.ProtectedResourceMetadata) http.Handler
- func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler
- type AuthorizationArgs
- type AuthorizationCodeFetcher
- type AuthorizationCodeHandler
- type AuthorizationCodeHandlerConfig
- type AuthorizationResult
- type ClientIDMetadataDocumentConfig
- type DynamicClientRegistrationConfig
- type OAuthHandler
- type RequireBearerTokenOptions
- type TokenInfo
- type TokenVerifier
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidToken = errors.New("invalid token")
The error that a TokenVerifier should return if the token cannot be verified.
var ErrOAuth = errors.New("oauth error")
The error that a TokenVerifier should return for OAuth-specific protocol errors.
Functions ¶
func GetAuthServerMetadata ¶ added in v1.5.0
func GetAuthServerMetadata(ctx context.Context, issuerURL string, httpClient *http.Client) (*oauthex.AuthServerMeta, error)
GetAuthServerMetadata fetches authorization server metadata for the given issuer URL. It tries standard well-known endpoints (OAuth 2.0 and OIDC) and returns the first successful result.
Returns (nil, nil) when no metadata endpoints respond (404s), allowing callers to implement fallback logic. Returns an error for any non-client error (network failures, invalid JSON, etc.).
func ProtectedResourceMetadataHandler ¶ added in v1.2.0
func ProtectedResourceMetadataHandler(metadata *oauthex.ProtectedResourceMetadata) http.Handler
ProtectedResourceMetadataHandler returns an http.Handler that serves OAuth 2.0 protected resource metadata (RFC 9728) with CORS support.
This handler allows cross-origin requests from any origin (Access-Control-Allow-Origin: *) because OAuth metadata is public information intended for client discovery (RFC 9728 §3.1). The metadata contains only non-sensitive configuration data about authorization servers and supported scopes.
No validation of metadata fields is performed; ensure metadata accuracy at configuration time.
For more sophisticated CORS policies or to restrict origins, wrap this handler with a CORS middleware like github.com/rs/cors or github.com/jub0bs/cors.
func RequireBearerToken ¶
func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler
RequireBearerToken returns a piece of middleware that verifies a bearer token using the verifier. If verification succeeds, the TokenInfo is added to the request's context and the request proceeds. If verification fails, the request fails with a 401 Unauthenticated, and the WWW-Authenticate header is populated to enable protected resource metadata.
Types ¶
type AuthorizationArgs ¶ added in v1.5.0
type AuthorizationArgs struct {
// Authorization URL to be opened in a browser for the user to start the authorization process.
URL string
}
AuthorizationArgs is the input to AuthorizationCodeFetcher.
type AuthorizationCodeFetcher ¶ added in v1.5.0
type AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error)
AuthorizationCodeFetcher is called to initiate the OAuth authorization flow. It is responsible for directing the user to the authorization URL (e.g., opening in a browser) and returning the authorization code and state once the Authorization Server redirects back to the configured RedirectURL.
type AuthorizationCodeHandler ¶ added in v1.5.0
type AuthorizationCodeHandler struct {
// contains filtered or unexported fields
}
AuthorizationCodeHandler is an implementation of OAuthHandler that uses the authorization code flow to obtain access tokens.
func NewAuthorizationCodeHandler ¶ added in v1.5.0
func NewAuthorizationCodeHandler(config *AuthorizationCodeHandlerConfig) (*AuthorizationCodeHandler, error)
NewAuthorizationCodeHandler creates a new AuthorizationCodeHandler. It performs validation of the configuration and returns an error if it is invalid. The passed config is consumed by the handler and should not be modified after.
func (*AuthorizationCodeHandler) Authorize ¶ added in v1.5.0
func (h *AuthorizationCodeHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error
Authorize performs the authorization flow. It is designed to perform the whole Authorization Code Grant flow. On success, AuthorizationCodeHandler.TokenSource will return a token source with the fetched token.
func (*AuthorizationCodeHandler) TokenSource ¶ added in v1.5.0
func (h *AuthorizationCodeHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error)
type AuthorizationCodeHandlerConfig ¶ added in v1.5.0
type AuthorizationCodeHandlerConfig struct {
// Client registration configuration.
// It is attempted in the following order:
// 1. Client ID Metadata Document
// 2. Preregistration
// 3. Dynamic Client Registration
// At least one method must be configured.
ClientIDMetadataDocumentConfig *ClientIDMetadataDocumentConfig
PreregisteredClient *oauthex.ClientCredentials
DynamicClientRegistrationConfig *DynamicClientRegistrationConfig
// RedirectURL is a required URL to redirect to after authorization.
// The caller is responsible for handling the redirect out of band.
//
// If Dynamic Client Registration is used:
// - this field is permitted to be empty, in which case it will be set
// to the first redirect URI from
// DynamicClientRegistrationConfig.Metadata.RedirectURIs.
// - if the field is not empty, it must be one of the redirect URIs in
// DynamicClientRegistrationConfig.Metadata.RedirectURIs.
RedirectURL string
// AuthorizationCodeFetcher is a required function called to initiate the authorization flow.
// See [AuthorizationCodeFetcher] for details.
AuthorizationCodeFetcher AuthorizationCodeFetcher
// Client is an optional HTTP client to use for HTTP requests.
// It is used for the following requests:
// - Fetching Protected Resource Metadata
// - Fetching Authorization Server Metadata
// - Registering a client dynamically
// - Exchanging an authorization code for an access token
// - Refreshing an access token
// Custom clients can include additional security configurations,
// such as SSRF protections, see
// https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices#server-side-request-forgery-ssrf
// If not provided, http.DefaultClient will be used.
Client *http.Client
}
AuthorizationCodeHandlerConfig is the configuration for AuthorizationCodeHandler.
type AuthorizationResult ¶ added in v1.5.0
type AuthorizationResult struct {
// Code is the authorization code obtained from the authorization server.
Code string
// State string returned by the authorization server.
State string
}
AuthorizationResult is the result of an authorization flow. It is returned by AuthorizationCodeHandler.AuthorizationCodeFetcher implementations.
type ClientIDMetadataDocumentConfig ¶ added in v1.5.0
type ClientIDMetadataDocumentConfig struct {
// URL is the client identifier URL as per
// https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#section-3.
URL string
}
ClientIDMetadataDocumentConfig is used to configure the Client ID Metadata Document based client registration per https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#client-id-metadata-documents. See https://client.dev/ for more information.
type DynamicClientRegistrationConfig ¶ added in v1.5.0
type DynamicClientRegistrationConfig struct {
// Metadata to be used in dynamic client registration request as per
// https://datatracker.ietf.org/doc/html/rfc7591#section-2.
Metadata *oauthex.ClientRegistrationMetadata
}
DynamicClientRegistrationConfig is used to configure dynamic client registration per https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#dynamic-client-registration.
type OAuthHandler ¶ added in v1.4.0
type OAuthHandler interface {
// TokenSource returns a token source to be used for outgoing requests.
// Returned token source might be nil. In that case, the transport will not
// add any authorization headers to the request.
TokenSource(context.Context) (oauth2.TokenSource, error)
// Authorize is called when an HTTP request results in an error that may
// be addressed by the authorization flow (currently 401 Unauthorized and 403 Forbidden).
// It is responsible for performing the OAuth flow to obtain an access token.
// The arguments are the request that failed and the response that was received for it.
// The headers of the request are available, but the body will have already been consumed
// when Authorize is called.
// If the returned error is nil, TokenSource is expected to return a non-nil token source.
// After a successful call to Authorize, the HTTP request will be retried by the transport.
// The function is responsible for closing the response body.
Authorize(context.Context, *http.Request, *http.Response) error
}
OAuthHandler is an interface for handling OAuth flows.
If a transport wishes to support OAuth 2 authorization, it should support being configured with an OAuthHandler. It should call the handler's TokenSource method whenever it sends an HTTP request to set the Authorization header. If a request fails with a 401 or 403, it should call Authorize, and if that returns nil, it should retry the request. It should not call Authorize after the second failure. See github.com/modelcontextprotocol/go-sdk/mcp.StreamableClientTransport for an example.
type RequireBearerTokenOptions ¶
type RequireBearerTokenOptions struct {
// The URL for the resource server metadata OAuth flow, to be returned as part
// of the WWW-Authenticate header.
ResourceMetadataURL string
// The required scopes.
Scopes []string
}
RequireBearerTokenOptions are options for RequireBearerToken.
type TokenInfo ¶
type TokenInfo struct {
Scopes []string
Expiration time.Time
// UserID is an optional identifier for the authenticated user.
// If set by a TokenVerifier, it can be used by transports to prevent
// session hijacking by ensuring that all requests for a given session
// come from the same user.
UserID string
Extra map[string]any
}
TokenInfo holds information from a bearer token.
type TokenVerifier ¶
A TokenVerifier checks the validity of a bearer token, and extracts information from it. If verification fails, it should return an error that unwraps to ErrInvalidToken. The HTTP request is provided in case verifying the token involves checking it.