Documentation
¶
Overview ¶
Package oauthex implements extensions to OAuth2.
Index ¶
- Constants
- func ExchangeToken(ctx context.Context, tokenEndpoint string, req *TokenExchangeRequest, ...) (*oauth2.Token, error)
- type AuthServerMeta
- type Challenge
- type ClientCredentials
- type ClientRegistrationError
- type ClientRegistrationMetadata
- type ClientRegistrationResponse
- type ClientSecretAuth
- type ProtectedResourceMetadata
- type TokenExchangeRequest
Constants ¶
const ( // TokenTypeIDToken is the URN for OpenID Connect ID Tokens. TokenTypeIDToken = "urn:ietf:params:oauth:token-type:id_token" // TokenTypeSAML2 is the URN for SAML 2.0 assertions. TokenTypeSAML2 = "urn:ietf:params:oauth:token-type:saml2" // TokenTypeIDJAG is the URN for Identity Assertion JWT Authorization Grants. // This is the token type returned by IdP during token exchange for SEP-990. TokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag" // GrantTypeTokenExchange is the grant type for RFC 8693 token exchange. GrantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" )
Token type identifiers defined by RFC 8693 and SEP-990.
Variables ¶
This section is empty.
Functions ¶
func ExchangeToken ¶ added in v1.5.0
func ExchangeToken( ctx context.Context, tokenEndpoint string, req *TokenExchangeRequest, clientCreds *ClientCredentials, httpClient *http.Client, ) (*oauth2.Token, error)
ExchangeToken performs a token exchange request per RFC 8693 for Enterprise Managed Authorization (SEP-990). It exchanges an identity assertion (typically an ID Token) for an Identity Assertion JWT Authorization Grant (ID-JAG) that can be used to obtain an access token from an MCP Server.
The tokenEndpoint parameter should be the IdP's token endpoint (typically obtained from the IdP's authorization server metadata).
Returns an oauth2.Token where:
- Extra("issued_token_type") contains the type of the issued token (e.g., TokenTypeIDJAG)
- AccessToken contains the ID-JAG JWT (despite the name, this is not an OAuth access token)
- TokenType is typically "N_A" for SEP-990
- Extra("scope") may contain the scope if different from the request
- Expiry is when the token expires
Types ¶
type AuthServerMeta ¶ added in v1.5.0
type AuthServerMeta struct {
// Issuer is the REQUIRED URL identifying the authorization server.
Issuer string `json:"issuer"`
// AuthorizationEndpoint is the REQUIRED URL of the server's OAuth 2.0 authorization endpoint.
AuthorizationEndpoint string `json:"authorization_endpoint"`
// TokenEndpoint is the REQUIRED URL of the server's OAuth 2.0 token endpoint.
TokenEndpoint string `json:"token_endpoint"`
// JWKSURI is the REQUIRED URL of the server's JSON Web Key Set [JWK] document.
JWKSURI string `json:"jwks_uri"`
// RegistrationEndpoint is the RECOMMENDED URL of the server's OAuth 2.0 Dynamic Client Registration endpoint.
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
// ScopesSupported is a RECOMMENDED JSON array of strings containing a list of the OAuth 2.0
// "scope" values that this server supports.
ScopesSupported []string `json:"scopes_supported,omitempty"`
// ResponseTypesSupported is a REQUIRED JSON array of strings containing a list of the OAuth 2.0
// "response_type" values that this server supports.
ResponseTypesSupported []string `json:"response_types_supported"`
// ResponseModesSupported is a RECOMMENDED JSON array of strings containing a list of the OAuth 2.0
// "response_mode" values that this server supports.
ResponseModesSupported []string `json:"response_modes_supported,omitempty"`
// GrantTypesSupported is a RECOMMENDED JSON array of strings containing a list of the OAuth 2.0
// grant type values that this server supports.
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
// TokenEndpointAuthMethodsSupported is a RECOMMENDED JSON array of strings containing a list of
// client authentication methods supported by this token endpoint.
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
// TokenEndpointAuthSigningAlgValuesSupported is a RECOMMENDED JSON array of strings containing
// a list of the JWS signing algorithms ("alg" values) supported by the token endpoint for
// the signature on the JWT used to authenticate the client.
TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`
// ServiceDocumentation is a RECOMMENDED URL of a page containing human-readable documentation
// for the service.
ServiceDocumentation string `json:"service_documentation,omitempty"`
// UILocalesSupported is a RECOMMENDED JSON array of strings representing supported
// BCP47 [RFC5646] language tag values for display in the user interface.
UILocalesSupported []string `json:"ui_locales_supported,omitempty"`
// OpPolicyURI is a RECOMMENDED URL that the server provides to the person registering
// the client to read about the server's operator policies.
OpPolicyURI string `json:"op_policy_uri,omitempty"`
// OpTOSURI is a RECOMMENDED URL that the server provides to the person registering the
// client to read about the server's terms of service.
OpTOSURI string `json:"op_tos_uri,omitempty"`
// RevocationEndpoint is a RECOMMENDED URL of the server's OAuth 2.0 revocation endpoint.
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
// RevocationEndpointAuthMethodsSupported is a RECOMMENDED JSON array of strings containing
// a list of client authentication methods supported by this revocation endpoint.
RevocationEndpointAuthMethodsSupported []string `json:"revocation_endpoint_auth_methods_supported,omitempty"`
// RevocationEndpointAuthSigningAlgValuesSupported is a RECOMMENDED JSON array of strings
// containing a list of the JWS signing algorithms ("alg" values) supported by the revocation
// endpoint for the signature on the JWT used to authenticate the client.
RevocationEndpointAuthSigningAlgValuesSupported []string `json:"revocation_endpoint_auth_signing_alg_values_supported,omitempty"`
// IntrospectionEndpoint is a RECOMMENDED URL of the server's OAuth 2.0 introspection endpoint.
IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`
// IntrospectionEndpointAuthMethodsSupported is a RECOMMENDED JSON array of strings containing
// a list of client authentication methods supported by this introspection endpoint.
IntrospectionEndpointAuthMethodsSupported []string `json:"introspection_endpoint_auth_methods_supported,omitempty"`
// IntrospectionEndpointAuthSigningAlgValuesSupported is a RECOMMENDED JSON array of strings
// containing a list of the JWS signing algorithms ("alg" values) supported by the introspection
// endpoint for the signature on the JWT used to authenticate the client.
IntrospectionEndpointAuthSigningAlgValuesSupported []string `json:"introspection_endpoint_auth_signing_alg_values_supported,omitempty"`
// CodeChallengeMethodsSupported is a RECOMMENDED JSON array of strings containing a list of
// PKCE code challenge methods supported by this authorization server.
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
// ClientIDMetadataDocumentSupported is a boolean indicating whether the authorization server
// supports client ID metadata documents.
ClientIDMetadataDocumentSupported bool `json:"client_id_metadata_document_supported,omitempty"`
}
AuthServerMeta represents the metadata for an OAuth 2.0 authorization server, as defined in RFC 8414.
Not supported: - signed metadata
Note: URL fields in this struct are validated by validateAuthServerMetaURLs to prevent XSS attacks. If you add a new URL field, you must also add it to that function.
func GetAuthServerMeta ¶ added in v1.5.0
func GetAuthServerMeta(ctx context.Context, metadataURL, issuer string, c *http.Client) (*AuthServerMeta, error)
GetAuthServerMeta issues a GET request to retrieve authorization server metadata from an OAuth authorization server with the given metadataURL.
It follows RFC 8414:
- The metadataURL must use HTTPS or be a local address.
- The Issuer field is checked against metadataURL.Issuer.
It also verifies that the authorization server supports PKCE and that the URLs in the metadata don't use dangerous schemes.
It returns an error if the request fails with a non-4xx status code or the fetched metadata doesn't pass security validations. It returns nil if the request fails with a 4xx status code.
type Challenge ¶ added in v1.4.0
type Challenge struct {
// Scheme is the authentication scheme (e.g., "Bearer", "Basic").
// It is case-insensitive. A parsed value will always be lower-case.
Scheme string
// Params is a map of authentication parameters.
// Keys are case-insensitive. Parsed keys are always lower-case.
Params map[string]string
}
Challenge represents a single authentication challenge from a WWW-Authenticate header. As per RFC 9110, Section 11.6.1, a challenge consists of a scheme and optional parameters.
func ParseWWWAuthenticate ¶ added in v1.5.0
ParseWWWAuthenticate parses a WWW-Authenticate header string. The header format is defined in RFC 9110, Section 11.6.1, and can contain one or more challenges, separated by commas. It returns a slice of challenges or an error if one of the headers is malformed.
type ClientCredentials ¶ added in v1.5.0
type ClientCredentials struct {
// ClientID is the OAuth2 client identifier.
// REQUIRED for all authentication methods.
ClientID string
// ClientSecretAuth configures client authentication using a client secret.
// This is the most common authentication method for confidential clients.
// OPTIONAL. If not provided, the client is treated as a public client.
ClientSecretAuth *ClientSecretAuth
}
ClientCredentials holds client authentication credentials for OAuth token requests. It supports multiple authentication methods, but only one method should be set at a time. Use the Validate method to ensure proper configuration.
func (*ClientCredentials) Validate ¶ added in v1.5.0
func (c *ClientCredentials) Validate() error
Validate checks that the ClientCredentials are properly configured. It ensures that:
- ClientID is not empty.
- At most one authentication method is configured.
- If ClientSecretAuth is set, ClientSecret is not empty.
type ClientRegistrationError ¶ added in v1.5.0
type ClientRegistrationError struct {
// ErrorCode is the REQUIRED error code if registration failed (RFC 7591, 3.2.2).
ErrorCode string `json:"error"`
// ErrorDescription is an OPTIONAL human-readable error message.
ErrorDescription string `json:"error_description,omitempty"`
}
ClientRegistrationError is the error response from the Authorization Server for a failed registration attempt (RFC 7591, Section 3.2.2).
func (*ClientRegistrationError) Error ¶ added in v1.5.0
func (e *ClientRegistrationError) Error() string
type ClientRegistrationMetadata ¶ added in v1.5.0
type ClientRegistrationMetadata struct {
// RedirectURIs is a REQUIRED JSON array of redirection URI strings for use in
// redirect-based flows (such as the authorization code grant).
RedirectURIs []string `json:"redirect_uris"`
// TokenEndpointAuthMethod is an OPTIONAL string indicator of the requested
// authentication method for the token endpoint.
// If omitted, the default is "client_secret_basic".
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
// GrantTypes is an OPTIONAL JSON array of OAuth 2.0 grant type strings
// that the client will restrict itself to using.
// If omitted, the default is ["authorization_code"].
GrantTypes []string `json:"grant_types,omitempty"`
// ResponseTypes is an OPTIONAL JSON array of OAuth 2.0 response type strings
// that the client will restrict itself to using.
// If omitted, the default is ["code"].
ResponseTypes []string `json:"response_types,omitempty"`
// ClientName is a RECOMMENDED human-readable name of the client to be presented
// to the end-user.
ClientName string `json:"client_name,omitempty"`
// ClientURI is a RECOMMENDED URL of a web page providing information about the client.
ClientURI string `json:"client_uri,omitempty"`
// LogoURI is an OPTIONAL URL of a logo for the client, which may be displayed
// to the end-user.
LogoURI string `json:"logo_uri,omitempty"`
// Scope is an OPTIONAL string containing a space-separated list of scope values
// that the client will restrict itself to using.
Scope string `json:"scope,omitempty"`
// Contacts is an OPTIONAL JSON array of strings representing ways to contact
// people responsible for this client (e.g., email addresses).
Contacts []string `json:"contacts,omitempty"`
// TOSURI is an OPTIONAL URL that the client provides to the end-user
// to read about the client's terms of service.
TOSURI string `json:"tos_uri,omitempty"`
// PolicyURI is an OPTIONAL URL that the client provides to the end-user
// to read about the client's privacy policy.
PolicyURI string `json:"policy_uri,omitempty"`
// JWKSURI is an OPTIONAL URL for the client's JSON Web Key Set [JWK] document.
// This is preferred over the 'jwks' parameter.
JWKSURI string `json:"jwks_uri,omitempty"`
// JWKS is an OPTIONAL client's JSON Web Key Set [JWK] document, passed by value.
// This is an alternative to providing a JWKSURI.
JWKS string `json:"jwks,omitempty"`
// SoftwareID is an OPTIONAL unique identifier string for the client software,
// constant across all instances and versions.
SoftwareID string `json:"software_id,omitempty"`
// SoftwareVersion is an OPTIONAL version identifier string for the client software.
SoftwareVersion string `json:"software_version,omitempty"`
// SoftwareStatement is an OPTIONAL JWT that asserts client metadata values.
// Values in the software statement take precedence over other metadata values.
SoftwareStatement string `json:"software_statement,omitempty"`
}
ClientRegistrationMetadata represents the client metadata fields for the DCR POST request (RFC 7591).
Note: URL fields in this struct are validated by validateClientRegistrationURLs to prevent XSS attacks. If you add a new URL field, you must also add it to that function.
type ClientRegistrationResponse ¶ added in v1.5.0
type ClientRegistrationResponse struct {
// ClientRegistrationMetadata contains all registered client metadata, returned by the
// server on success, potentially with modified or defaulted values.
ClientRegistrationMetadata
// ClientID is the REQUIRED newly issued OAuth 2.0 client identifier.
ClientID string `json:"client_id"`
// ClientSecret is an OPTIONAL client secret string.
ClientSecret string `json:"client_secret,omitempty"`
// ClientIDIssuedAt is an OPTIONAL Unix timestamp when the ClientID was issued.
ClientIDIssuedAt time.Time `json:"client_id_issued_at,omitempty"`
// ClientSecretExpiresAt is the REQUIRED (if client_secret is issued) Unix
// timestamp when the secret expires, or 0 if it never expires.
ClientSecretExpiresAt time.Time `json:"client_secret_expires_at,omitempty"`
}
ClientRegistrationResponse represents the fields returned by the Authorization Server (RFC 7591, Section 3.2.1 and 3.2.2).
func RegisterClient ¶ added in v1.5.0
func RegisterClient(ctx context.Context, registrationEndpoint string, clientMeta *ClientRegistrationMetadata, c *http.Client) (*ClientRegistrationResponse, error)
RegisterClient performs Dynamic Client Registration according to RFC 7591.
func (*ClientRegistrationResponse) MarshalJSON ¶ added in v1.5.0
func (r *ClientRegistrationResponse) MarshalJSON() ([]byte, error)
func (*ClientRegistrationResponse) UnmarshalJSON ¶ added in v1.5.0
func (r *ClientRegistrationResponse) UnmarshalJSON(data []byte) error
type ClientSecretAuth ¶ added in v1.5.0
type ClientSecretAuth struct {
// ClientSecret is the OAuth2 client secret for confidential clients.
// REQUIRED when using ClientSecretAuth.
ClientSecret string
}
ClientSecretAuth holds client secret authentication credentials. This authentication method supports both "client_secret_basic" and "client_secret_post" methods as defined in RFC 6749 Section 2.3.1.
type ProtectedResourceMetadata ¶
type ProtectedResourceMetadata struct {
// Resource (resource) is the protected resource's resource identifier.
// Required.
Resource string `json:"resource"`
// AuthorizationServers (authorization_servers) is an optional slice containing a list of
// OAuth authorization server issuer identifiers (as defined in RFC 8414) that can be
// used with this protected resource.
AuthorizationServers []string `json:"authorization_servers,omitempty"`
// JWKSURI (jwks_uri) is an optional URL of the protected resource's JSON Web Key (JWK) Set
// document. This contains public keys belonging to the protected resource, such as
// signing key(s) that the resource server uses to sign resource responses.
JWKSURI string `json:"jwks_uri,omitempty"`
// ScopesSupported (scopes_supported) is a recommended slice containing a list of scope
// values (as defined in RFC 6749) used in authorization requests to request access
// to this protected resource.
ScopesSupported []string `json:"scopes_supported,omitempty"`
// BearerMethodsSupported (bearer_methods_supported) is an optional slice containing
// a list of the supported methods of sending an OAuth 2.0 bearer token to the
// protected resource. Defined values are "header", "body", and "query".
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
// ResourceSigningAlgValuesSupported (resource_signing_alg_values_supported) is an optional
// slice of JWS signing algorithms (alg values) supported by the protected
// resource for signing resource responses.
ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
// ResourceName (resource_name) is a human-readable name of the protected resource
// intended for display to the end user. It is RECOMMENDED that this field be included.
// This value may be internationalized.
ResourceName string `json:"resource_name,omitempty"`
// ResourceDocumentation (resource_documentation) is an optional URL of a page containing
// human-readable information for developers using the protected resource.
// This value may be internationalized.
ResourceDocumentation string `json:"resource_documentation,omitempty"`
// ResourcePolicyURI (resource_policy_uri) is an optional URL of a page containing
// human-readable policy information on how a client can use the data provided.
// This value may be internationalized.
ResourcePolicyURI string `json:"resource_policy_uri,omitempty"`
// ResourceTOSURI (resource_tos_uri) is an optional URL of a page containing the protected
// resource's human-readable terms of service. This value may be internationalized.
ResourceTOSURI string `json:"resource_tos_uri,omitempty"`
// TLSClientCertificateBoundAccessTokens (tls_client_certificate_bound_access_tokens) is an
// optional boolean indicating support for mutual-TLS client certificate-bound
// access tokens (RFC 8705). Defaults to false if omitted.
TLSClientCertificateBoundAccessTokens bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`
// AuthorizationDetailsTypesSupported (authorization_details_types_supported) is an optional
// slice of 'type' values supported by the resource server for the
// 'authorization_details' parameter (RFC 9396).
AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"`
// DPOPSigningAlgValuesSupported (dpop_signing_alg_values_supported) is an optional
// slice of JWS signing algorithms supported by the resource server for validating
// DPoP proof JWTs (RFC 9449).
DPOPSigningAlgValuesSupported []string `json:"dpop_signing_alg_values_supported,omitempty"`
// DPOPBoundAccessTokensRequired (dpop_bound_access_tokens_required) is an optional boolean
// specifying whether the protected resource always requires the use of DPoP-bound
// access tokens (RFC 9449). Defaults to false if omitted.
DPOPBoundAccessTokensRequired bool `json:"dpop_bound_access_tokens_required,omitempty"`
}
ProtectedResourceMetadata is the metadata for an OAuth 2.0 protected resource, as defined in section 2 of https://www.rfc-editor.org/rfc/rfc9728.html.
The following features are not supported: - additional keys (§2, last sentence) - human-readable metadata (§2.1) - signed metadata (§2.2)
func GetProtectedResourceMetadata ¶ added in v1.5.0
func GetProtectedResourceMetadata(ctx context.Context, metadataURL, resourceURL string, c *http.Client) (_ *ProtectedResourceMetadata, err error)
GetProtectedResourceMetadata issues a GET request to retrieve protected resource metadata from a resource server. The metadataURL is typically a URL with a host:port and possibly a path. The resourceURL is the resource URI the metadataURL is for. The following checks are performed:
- The metadataURL must use HTTPS or be a local address.
- The resource field of the resulting metadata must match the resourceURL.
- The authorization_servers field of the resulting metadata is checked for dangerous URL schemes.
type TokenExchangeRequest ¶ added in v1.5.0
type TokenExchangeRequest struct {
// RequestedTokenType indicates the type of security token being requested.
// For SEP-990, this MUST be TokenTypeIDJAG.
RequestedTokenType string
// Audience is the logical name of the target service where the client
// intends to use the requested token. For SEP-990, this MUST be the
// Issuer URL of the MCP Server's authorization server.
Audience string
// Resource is the physical location or identifier of the target resource.
// For SEP-990, this MUST be the RFC9728 Resource Identifier of the MCP Server.
Resource string
// Scope is a list of space-separated scopes for the requested token.
// This is OPTIONAL per RFC 8693 but commonly used in SEP-990.
Scope []string
// SubjectToken is the security token that represents the identity of the
// party on behalf of whom the request is being made. For SEP-990, this is
// typically an OpenID Connect ID Token.
SubjectToken string
// SubjectTokenType is the type of the security token in SubjectToken.
// For SEP-990 with OIDC, this MUST be TokenTypeIDToken.
SubjectTokenType string
}
TokenExchangeRequest represents a Token Exchange request per RFC 8693. This is used for Enterprise Managed Authorization (SEP-990) where an MCP Client exchanges an ID Token from an enterprise IdP for an ID-JAG that can be used to obtain an access token from an MCP Server's authorization server.