apiauth

package
v0.0.85 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 24, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TokenTypeAccessToken  = "urn:ietf:params:oauth:token-type:access_token"
	TokenTypeRefreshToken = "urn:ietf:params:oauth:token-type:refresh_token"
	TokenTypeIDToken      = "urn:ietf:params:oauth:token-type:id_token"
	TokenTypeJWT          = "urn:ietf:params:oauth:token-type:jwt"
	TokenTypeSAML2        = "urn:ietf:params:oauth:token-type:saml2"
)

RFC 8693 §3 token type URIs.

View Source
const ClientAssertionTypeJWTBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"

ClientAssertionTypeJWTBearer is the OAuth assertion-type URN that MUST appear in the `client_assertion_type` form parameter when authenticating via private_key_jwt or client_secret_jwt (RFC 7521 §4.2). Any other value is rejected.

View Source
const JwtBearerGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"

JwtBearerGrantType is the OAuth grant type URI for the JWT Bearer authorization grant defined in RFC 7523 §2.1.

A client trades a signed JWT (typically issued by an upstream IdP about a subject) for an access token. The assertion's `iss` MUST match a trusted issuer in TrustedAssertionIssuers; the JWT signature MUST verify against that issuer's public key; standard claims (aud/exp/nbf/sub) MUST validate.

Distinct from RFC 7523 §2.2 (JWT for *client* authentication via client_assertion + client_assertion_type at the token endpoint), which is tracked separately as the `private_key_jwt` / `client_secret_jwt` token endpoint auth methods.

See: https://www.rfc-editor.org/rfc/rfc7523#section-2.1

View Source
const MaxClientAssertionLifetime = 5 * time.Minute

MaxClientAssertionLifetime caps how far in the future a client assertion's `exp` may be from `iat`. RFC 7523 §3 item 4 leaves the upper bound to the AS; OIDC Core §9 hints "short-lived". 5 minutes is the conventional ceiling matching most major IdPs and bounds the JTIStore memory footprint.

View Source
const TokenExchangeGrantType = "urn:ietf:params:oauth:grant-type:token-exchange"

TokenExchangeGrantType is the OAuth grant type URI for OAuth 2.0 Token Exchange (RFC 8693 §2.1). A client presents a `subject_token` representing the party on whose behalf the request is made and the AS issues a new token (typically narrower in scope or audience).

Common use case: enterprise-managed identity chains. A federated IdP issues a JWT about an employee; the employee's MCP client trades that JWT for an MCP-scoped access token via this grant.

See: https://www.rfc-editor.org/rfc/rfc8693

Variables

This section is empty.

Functions

func GetAuthTypeFromAPIContext

func GetAuthTypeFromAPIContext(ctx context.Context) string

GetAuthTypeFromAPIContext retrieves the auth type ("jwt" or "api_key") from context

func GetAuthorizationDetailsFromContext added in v0.0.76

func GetAuthorizationDetailsFromContext(ctx context.Context) []core.AuthorizationDetail

GetAuthorizationDetailsFromContext retrieves the RFC 9396 authorization_details from context. Returns nil if no authorization details are present (e.g., API key auth or token without RAR).

func GetCustomClaimsFromContext

func GetCustomClaimsFromContext(ctx context.Context) map[string]any

GetCustomClaimsFromContext retrieves the custom (non-standard) JWT claims from context. Returns nil if no custom claims are present (e.g., API key auth or no token).

func GetScopesFromAPIContext

func GetScopesFromAPIContext(ctx context.Context) []string

GetScopesFromAPIContext retrieves the granted scopes from the API middleware context

func GetUserIDFromAPIContext

func GetUserIDFromAPIContext(ctx context.Context) string

GetUserIDFromAPIContext retrieves the user ID from the API middleware context

func MountASMetadata added in v0.0.81

func MountASMetadata(mux *http.ServeMux, meta *ASServerMetadata)

MountASMetadata registers AS metadata at both well-known paths required by the OAuth/OIDC ecosystem:

  • /.well-known/oauth-authorization-server (RFC 8414 §3, MUST)
  • /.well-known/openid-configuration (OIDC Discovery 1.0 §4)

Both paths serve the same handler, so the documents are byte-identical. OAuth-only clients (which know about RFC 8414 but not OIDC Discovery) and OIDC clients (which look up openid-configuration) can both auto-discover the AS without falling back.

Callers that want only one path can register NewASMetadataHandler directly. This helper is the recommended default.

See:

func MountProtectedResource added in v0.0.75

func MountProtectedResource(mux *http.ServeMux, meta *ProtectedResourceMetadata, proxyASMetadata bool, pathPrefix ...string)

MountProtectedResource mounts the PRM endpoint on the given mux and optionally proxies AS metadata at the RFC 8414 well-known path. This ensures that clients which only try RFC 8414 discovery (and don't fall back to OIDC discovery) can find the AS metadata via the resource server.

Spec references:

When proxyASMetadata is true, for each URL in AuthorizationServers:

  • Fetches the AS's OIDC discovery document (with RFC 8414 fallback)
  • Caches and serves it at /.well-known/oauth-authorization-server on the resource server
  • Also serves path-based RFC 8414 (e.g., /.well-known/oauth-authorization-server/realms/foo)

This bridges OIDC-only providers (Keycloak, Auth0) that don't natively serve RFC 8414 metadata.

Usage:

MountProtectedResource(mux, meta, true)
// PRM at: /.well-known/oauth-protected-resource
// AS metadata at: /.well-known/oauth-authorization-server (proxied)

func NewASMetadataHandler added in v0.0.56

func NewASMetadataHandler(meta *ASServerMetadata) http.Handler

NewASMetadataHandler returns an http.Handler that serves Authorization Server metadata JSON. The handler is path-agnostic — register it at whichever well-known path you need, or use MountASMetadata to register at both required paths at once.

The handler:

  • Responds to GET only (405 for other methods)
  • Sets Content-Type: application/json
  • Sets Cache-Control: public, max-age=<CacheMaxAge>
  • Pre-serializes the response (metadata is static)

func NewProtectedResourceHandler added in v0.0.55

func NewProtectedResourceHandler(meta *ProtectedResourceMetadata) http.Handler

NewProtectedResourceHandler returns an http.Handler that serves the Protected Resource Metadata JSON at GET /.well-known/oauth-protected-resource.

The handler:

  • Responds to GET only (405 for other methods)
  • Sets Content-Type: application/json
  • Sets Cache-Control: public, max-age=<CacheMaxAge>
  • Serializes the metadata as JSON with omitempty on optional fields

Types

type APIAuth

type APIAuth struct {
	// Stores
	RefreshTokenStore core.RefreshTokenStore
	APIKeyStore       core.APIKeyStore

	// JWT configuration
	JWTSecretKey  string // Secret key for signing JWTs (HMAC)
	JWTIssuer     string // Issuer claim (e.g., "myapp")
	JWTAudience   string // Audience claim (e.g., "api")
	JWTSigningAlg string // Signing algorithm (defaults to HS256)

	// Asymmetric JWT keys (optional — when set, these take precedence over JWTSecretKey)
	JWTSigningKey any // crypto.PrivateKey (*rsa.PrivateKey or *ecdsa.PrivateKey) for signing
	JWTVerifyKey  any // crypto.PublicKey (*rsa.PublicKey or *ecdsa.PublicKey) for verification

	// Token configuration
	AccessTokenExpiry  time.Duration // Defaults to 15 minutes
	RefreshTokenExpiry time.Duration // Defaults to 7 days

	// Callbacks
	ValidateCredentials core.CredentialsValidator                         // Validates username/password
	GetUserScopes       core.GetUserScopesFunc                            // Returns allowed scopes for a user
	OnLoginSuccess      func(userID string, r *http.Request)              // Optional: for logging/analytics
	OnLoginFailure      func(username string, r *http.Request, err error) // Optional: for logging/analytics

	// CustomClaimsFunc is called during token creation to inject additional claims
	// into the JWT (e.g., client_id, max_rooms for relay-scoped tokens).
	// Standard claims (sub, iss, aud, exp, iat, type, scopes) cannot be overridden.
	// If nil, no custom claims are added (backwards-compatible).
	CustomClaimsFunc func(userID string, scopes []string) (map[string]any, error)

	// ClientKeyStore provides client credential lookup for the client_credentials
	// grant type (RFC 6749 §4.4). When set, the token endpoint accepts
	// grant_type=client_credentials and authenticates clients via KeyStore.
	// When nil, client_credentials requests return unsupported_grant_type.
	ClientKeyStore keys.KeyLookup

	// ClientAuthenticator authenticates clients at the token endpoint
	// (and is also used by the introspection / revocation handlers).
	// When set, all client authentication on the token endpoint
	// (client_secret_basic, client_secret_post, private_key_jwt) goes
	// through this interface — supporting the assertion-based methods
	// is the entire point of plumbing it here. When nil, the token
	// endpoint falls back to the legacy inline lookup against
	// ClientKeyStore (secret-based methods only).
	ClientAuthenticator ClientAuthenticator

	// AcceptedAudiences are the URLs the AS will accept as the `aud`
	// claim of a private_key_jwt / client_secret_jwt client assertion
	// at the token endpoint (OIDC Core §9). Typically the token
	// endpoint URL plus the AS issuer URL. When empty, the URL of the
	// request is used as a fallback (single-host deployments only).
	AcceptedAudiences []string

	// TrustedAssertionIssuers lists upstream IdPs whose JWT assertions
	// the token endpoint will accept for the jwt-bearer grant
	// (RFC 7523 §2.1) and the token-exchange grant with
	// subject_token_type=urn:ietf:params:oauth:token-type:jwt
	// (RFC 8693 §2.1.1). When empty, both grants return
	// unsupported_grant_type.
	//
	// See JwtBearerGrantType, TokenExchangeGrantType, and
	// TrustedAssertionIssuer for details.
	TrustedAssertionIssuers []TrustedAssertionIssuer

	// Rate limiting (optional)
	RateLimiter core.RateLimiter

	// Blacklist enables immediate access token revocation. When set,
	// ValidateAccessToken checks the blacklist after signature verification.
	// Tokens include a jti (JWT ID) claim for blacklist lookup.
	// If nil, tokens are validated by signature + expiry only (stateless).
	Blacklist core.TokenBlacklist
	// contains filtered or unexported fields
}

APIAuth handles API token-based authentication

func (*APIAuth) CreateAccessToken

func (a *APIAuth) CreateAccessToken(userID string, scopes []string, authzDetails []core.AuthorizationDetail) (string, int64, error)

CreateAccessToken creates a signed JWT access token. If CustomClaimsFunc is set, its returned claims are merged into the token (standard claims cannot be overridden). authzDetails is an optional RFC 9396 authorization_details array embedded in the JWT.

func (*APIAuth) HandleAPIKeys

func (a *APIAuth) HandleAPIKeys(w http.ResponseWriter, r *http.Request)

HandleAPIKeys handles API key management (GET=list, POST=create) Requires authentication (userID must be in request context)

func (*APIAuth) HandleListSessions

func (a *APIAuth) HandleListSessions(w http.ResponseWriter, r *http.Request)

HandleListSessions handles GET /api/sessions - lists active sessions for the user Requires authentication (userID must be in request context)

func (*APIAuth) HandleLogout

func (a *APIAuth) HandleLogout(w http.ResponseWriter, r *http.Request)

HandleLogout handles POST /api/logout - revokes a refresh token

func (*APIAuth) HandleLogoutAll

func (a *APIAuth) HandleLogoutAll(w http.ResponseWriter, r *http.Request)

HandleLogoutAll handles POST /api/logout-all - revokes all refresh tokens for the user Requires authentication (userID must be in request context)

func (*APIAuth) HandleRevokeAPIKey

func (a *APIAuth) HandleRevokeAPIKey(w http.ResponseWriter, r *http.Request)

HandleRevokeAPIKey handles DELETE /api/keys/:id - revokes an API key Requires authentication (userID must be in request context)

func (*APIAuth) ServeHTTP

func (a *APIAuth) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles the /api/token endpoint. It accepts both application/x-www-form-urlencoded (RFC 6749 standard) and application/json request bodies.

See: https://www.rfc-editor.org/rfc/rfc6749#section-4.4.2

func (*APIAuth) ValidateAccessToken

func (a *APIAuth) ValidateAccessToken(tokenString string) (userID string, scopes []string, err error)

ValidateAccessToken validates a JWT access token and returns the claims

func (*APIAuth) ValidateAccessTokenFull

func (a *APIAuth) ValidateAccessTokenFull(tokenString string) (userID string, scopes []string, customClaims map[string]any, err error)

ValidateAccessTokenFull validates a JWT access token and returns the standard claims plus any custom claims (non-standard keys) as a separate map.

func (*APIAuth) VerifyTokenFunc

func (a *APIAuth) VerifyTokenFunc() func(tokenString string) (userID string, token any, err error)

VerifyTokenFunc returns a function that can be used as Middleware.VerifyToken. This allows the Middleware to validate Bearer tokens using the APIAuth's JWT configuration.

type APIMiddleware

type APIMiddleware struct {
	// JWT validation (uses same config as APIAuth)
	JWTSecretKey  string
	JWTIssuer     string
	JWTAudience   string
	JWTSigningAlg string

	// KeyStore for multi-tenant JWT validation. When set, the middleware uses
	// GetKeyByKid (for tokens with kid header) or GetKey (for client_id claim).
	// When nil, falls back to JWTSecretKey (single-tenant, backwards-compatible).
	KeyStore keys.KeyLookup

	// API key validation (optional)
	APIKeyStore core.APIKeyStore

	// Token header configuration
	AuthHeader string // Defaults to "Authorization"

	// TokenQueryParam is the query parameter name to check for a token as fallback
	// when the Authorization header is missing (e.g., "token" for ?token=...).
	// Empty string disables query param extraction (default).
	TokenQueryParam string

	// Error handling
	OnAuthError func(w http.ResponseWriter, r *http.Request, err error)

	// Blacklist enables immediate access token revocation. When set,
	// validateJWT checks the blacklist after signature verification.
	// If nil, no revocation check (stateless validation only).
	Blacklist core.TokenBlacklist

	// Introspection enables token validation via a remote introspection
	// endpoint (RFC 7662) as an alternative to local JWT/JWKS validation.
	// When set, tokens that fail local validation are sent to the
	// introspection endpoint. When local validation is not configured
	// (no JWTSecretKey, no KeyStore), introspection is the only validation path.
	// If nil, only local validation is used.
	Introspection *IntrospectionValidator

	// Validator is the transport-independent token validator (Phase 2).
	// When set, validateJWT delegates to it instead of using inline logic.
	// When nil, a validator is lazily built from the existing fields
	// (JWTSecretKey, KeyStore, Blacklist, etc.) on first use.
	Validator TokenValidator
	// contains filtered or unexported fields
}

APIMiddleware provides middleware for validating API tokens

func (*APIMiddleware) Optional

func (m *APIMiddleware) Optional(next http.Handler) http.Handler

Optional middleware allows requests without auth but sets user info if present

func (*APIMiddleware) RequireAuthorizationDetails added in v0.0.76

func (m *APIMiddleware) RequireAuthorizationDetails(requiredTypes ...string) func(http.Handler) http.Handler

RequireAuthorizationDetails middleware ensures the token contains authorization_details matching all required types. For each required type, there must be at least one authorization_details entry with that type.

See: https://www.rfc-editor.org/rfc/rfc9396

func (*APIMiddleware) RequireScopes

func (m *APIMiddleware) RequireScopes(requiredScopes ...string) func(http.Handler) http.Handler

RequireScopes middleware ensures the authenticated user has all required scopes

func (*APIMiddleware) ValidateToken

func (m *APIMiddleware) ValidateToken(next http.Handler) http.Handler

ValidateToken middleware validates Bearer tokens (JWT or API key) and sets user info in context

type ASMetadataProxy added in v0.0.75

type ASMetadataProxy struct {
	// contains filtered or unexported fields
}

ASMetadataProxy fetches AS metadata from an authorization server's OIDC discovery endpoint and serves it at the RFC 8414 well-known path. This bridges the gap for OIDC-only providers (like Keycloak) that don't serve RFC 8414 metadata natively.

Background:

The proxy:

  • Fetches lazily on first request (not at construction time)
  • Caches the response with a configurable TTL (default 1 hour)
  • Tries RFC 8414 first, then OIDC discovery (same fallback as client.DiscoverAS)
  • Serves GET only (405 for other methods)

func NewASMetadataProxy added in v0.0.75

func NewASMetadataProxy(issuerURL string, cacheTTL time.Duration) *ASMetadataProxy

NewASMetadataProxy creates a proxy that fetches AS metadata from the given issuer URL. The proxy tries both RFC 8414 and OIDC discovery paths.

func (*ASMetadataProxy) ServeHTTP added in v0.0.75

func (p *ASMetadataProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ASServerMetadata added in v0.0.56

type ASServerMetadata struct {
	// Required
	Issuer        string `json:"issuer"`
	TokenEndpoint string `json:"token_endpoint"`

	// Recommended
	JWKSURI string `json:"jwks_uri,omitempty"`

	// Optional endpoints
	AuthorizationEndpoint string `json:"authorization_endpoint,omitempty"`
	IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`
	RevocationEndpoint    string `json:"revocation_endpoint,omitempty"`
	RegistrationEndpoint  string `json:"registration_endpoint,omitempty"`
	UserinfoEndpoint      string `json:"userinfo_endpoint,omitempty"`

	// Supported features
	AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"` // RFC 9396
	ScopesSupported                    []string `json:"scopes_supported,omitempty"`

	// ClaimsSupported lists the claim names this AS may include in
	// issued tokens (and, once a userinfo endpoint exists, the userinfo
	// response). OIDC Discovery 1.0 §3 declares this RECOMMENDED; the
	// OpenID Foundation conformance suite emits a warning when the list
	// is absent. Advertise only claims the AS actually emits — listing
	// claims the AS does not produce misleads relying parties.
	//
	// See: OpenID Connect Discovery 1.0 §3
	ClaimsSupported []string `json:"claims_supported,omitempty"`

	ResponseTypesSupported   []string `json:"response_types_supported,omitempty"`
	GrantTypesSupported      []string `json:"grant_types_supported,omitempty"`
	TokenEndpointAuthMethods []string `json:"token_endpoint_auth_methods_supported,omitempty"`

	// TokenEndpointAuthSigningAlgValuesSupported lists the JWT alg
	// values the AS accepts on a private_key_jwt or client_secret_jwt
	// `client_assertion`. Per OIDC Discovery 1.0 §3 / RFC 8414 §2 this
	// list is REQUIRED whenever TokenEndpointAuthMethods includes
	// "private_key_jwt" or "client_secret_jwt"; "none" MUST NOT
	// appear. Typical values: "RS256", "ES256".
	TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`

	CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
	SubjectTypesSupported         []string `json:"subject_types_supported,omitempty"`

	// AuthorizationResponseIssParameterSupported advertises RFC 9207
	// support — when true, the AS includes an `iss` query parameter on
	// every authorization response (both successful redirects with `code`
	// and error redirects). Pointer semantics distinguish absence (omit
	// from JSON) from explicit `false` (advertised as not supported).
	//
	// RFC 9207 §3:
	//   https://www.rfc-editor.org/rfc/rfc9207#section-3
	//
	// Setting this true on an AS that does NOT actually emit `iss` in
	// authorization responses is a spec violation — clients keying off
	// the advertisement will fail to validate.
	AuthorizationResponseIssParameterSupported *bool `json:"authorization_response_iss_parameter_supported,omitempty"`

	// CacheMaxAge controls the Cache-Control max-age in seconds.
	// Defaults to 3600 (1 hour). Not serialized to JSON.
	CacheMaxAge int `json:"-"`
}

ASServerMetadata describes an OAuth 2.0 Authorization Server per RFC 8414 and OpenID Connect Discovery 1.0 §4. RFC 8414 §3 mandates this metadata be served at /.well-known/oauth-authorization-server; OIDC Discovery places the same document at /.well-known/openid-configuration. Use MountASMetadata to register both paths in one call.

This is metadata-only — serving this does NOT make the server a full OIDC provider. It simply advertises what endpoints exist (token, JWKS, introspection, etc.) so standard client libraries can discover them.

See: https://www.rfc-editor.org/rfc/rfc8414#section-2

type AuthHooks added in v0.0.77

type AuthHooks struct {
	// OnLoginSuccess fires after a user successfully authenticates
	// (password grant, auth code exchange).
	OnLoginSuccess func(userID string)

	// OnLoginFailure fires after a failed authentication attempt.
	OnLoginFailure func(username string, err error)

	// OnScopeStepUp fires when additional scopes are requested and granted.
	// from is the original scope set, to is the expanded set.
	OnScopeStepUp func(subject string, from, to []string)
}

AuthHooks fires on authentication events.

type AuthenticateClientRequest added in v0.0.83

type AuthenticateClientRequest struct {
	// ClientID is the OAuth client identifier. For private_key_jwt this
	// may be empty; the authenticator extracts it from the assertion's
	// `iss` / `sub` claims.
	ClientID string

	// ClientSecret is the shared secret for client_secret_basic /
	// client_secret_post. Empty when authenticating via assertion.
	ClientSecret string

	// ClientAssertionType is the OAuth assertion type URN. For
	// private_key_jwt this MUST be
	// "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
	// (RFC 7521 §4.2). Empty when authenticating via secret.
	ClientAssertionType string

	// ClientAssertion is the signed JWT bearing the client's identity
	// (RFC 7523 §2.2 / OIDC Core §9). Validated against the client's
	// registered public key. Empty when authenticating via secret.
	ClientAssertion string

	// Audiences is the set of URLs the AS will accept as the assertion's
	// `aud` claim — typically the token endpoint URL AND the AS issuer
	// URL. Per OIDC Core §9 the audience SHOULD be the token endpoint
	// URL, but real-world clients (Auth0, Keycloak, Authlete) send one
	// or the other; accept both for interop. The assertion's `aud`
	// MUST match at least one entry. Required when ClientAssertion is
	// set.
	Audiences []string
}

AuthenticateClientRequest is the input to ClientAuthenticator.AuthenticateClient.

Callers populate either the secret pair (ClientID + ClientSecret) or the assertion pair (ClientAssertionType + ClientAssertion). When both are populated the implementation prefers the assertion (it is the stronger credential per RFC 6749 §2.3.1).

type AuthenticateClientResponse added in v0.0.83

type AuthenticateClientResponse struct {
	// ClientID is the authenticated client identifier. Equals the
	// request ClientID for the secret path; extracted from the
	// assertion `iss` / `sub` for the assertion path.
	ClientID string

	// Method names the auth method that succeeded — one of
	// "client_secret_basic", "client_secret_post", "private_key_jwt".
	// Transport bindings populate Method on the way in (basic vs post)
	// when they know which channel carried the secret; the assertion
	// path always sets it to "private_key_jwt".
	Method string
}

AuthenticateClientResponse reports the authenticated client and the auth method that succeeded. The method is informational (telemetry, logging) — handlers that only need success/failure can ignore it.

type CheckAuthorizationDetailsRequest added in v0.0.83

type CheckAuthorizationDetailsRequest struct {
	Token         string
	RequiredTypes []string
}

CheckAuthorizationDetailsRequest is the input to TokenValidator.CheckAuthorizationDetails.

type CheckAuthorizationDetailsResponse added in v0.0.83

type CheckAuthorizationDetailsResponse struct{}

CheckAuthorizationDetailsResponse — see CheckScopesResponse rationale.

type CheckScopesRequest added in v0.0.83

type CheckScopesRequest struct {
	Token          string
	RequiredScopes []string
}

CheckScopesRequest is the input to TokenValidator.CheckScopes.

type CheckScopesResponse added in v0.0.83

type CheckScopesResponse struct{}

CheckScopesResponse is intentionally empty — the operation is a pure success/failure signal expressed via the error return. Wrapped struct preserves the convention shape and gives forward-compat headroom.

type ClientAuthenticator added in v0.0.77

type ClientAuthenticator interface {
	// AuthenticateClient verifies the supplied credentials. Returns the
	// authenticated client_id and the auth method used on success.
	AuthenticateClient(ctx context.Context, req *AuthenticateClientRequest) (*AuthenticateClientResponse, error)
}

ClientAuthenticator verifies client credentials. Used by transport bindings to authenticate callers of protected endpoints (token, introspection, revocation, DCR).

Supported authentication methods (RFC 6749 §2.3.1, OIDC Core §9):

  • client_secret_basic / client_secret_post: ClientID + ClientSecret
  • private_key_jwt (RFC 7521 §3 + RFC 7523 §2.2): ClientAssertionType + ClientAssertion. The implementation routes by which fields are set.

func NewClientAuthenticator added in v0.0.77

func NewClientAuthenticator(kl keys.KeyLookup) ClientAuthenticator

NewClientAuthenticator creates a ClientAuthenticator backed by a KeyLookup, with an in-memory JTIStore for assertion replay protection. For multi-node deployments use NewClientAuthenticatorWithJTIStore to wire a distributed JTI store.

func NewClientAuthenticatorWithJTIStore added in v0.0.83

func NewClientAuthenticatorWithJTIStore(kl keys.KeyLookup, jti JTIStore) ClientAuthenticator

NewClientAuthenticatorWithJTIStore is like NewClientAuthenticator but lets callers supply a custom JTIStore (Redis-backed, etc.).

type ClientCredentialsRequest added in v0.0.83

type ClientCredentialsRequest struct {
	ClientID             string
	ClientSecret         string
	Scopes               []string
	AuthorizationDetails []core.AuthorizationDetail
}

ClientCredentialsRequest is the input to TokenIssuer.ClientCredentials.

type ClientCredentialsResponse added in v0.0.83

type ClientCredentialsResponse struct {
	Tokens *core.TokenPair
}

ClientCredentialsResponse wraps the issued token pair. Wrapped (rather than returning *core.TokenPair directly) for symmetry across the interface and forward-compat headroom — same rationale as ClientRegistrationManager response types in 168.

type ClientHooks added in v0.0.77

type ClientHooks struct {
	// OnRegistered fires after a new client is registered (DCR or proprietary).
	// method is "dcr" or "register".
	OnRegistered func(clientID, method string)

	// OnDeleted fires after a client is deleted.
	OnDeleted func(clientID string)

	// OnKeyRotated fires after a client's signing key is rotated.
	OnKeyRotated func(clientID string)
}

ClientHooks fires on client management events.

type CreateAccessTokenRequest added in v0.0.83

type CreateAccessTokenRequest struct {
	Subject              string
	Scopes               []string
	AuthorizationDetails []core.AuthorizationDetail
}

CreateAccessTokenRequest is the input to TokenIssuer.CreateAccessToken.

type CreateAccessTokenResponse added in v0.0.83

type CreateAccessTokenResponse struct {
	Token     string
	ExpiresIn int64
}

CreateAccessTokenResponse is the output of TokenIssuer.CreateAccessToken.

type Hooks added in v0.0.77

type Hooks struct {
	Token    TokenHooks
	Auth     AuthHooks
	Client   ClientHooks
	Security SecurityHooks
}

Hooks provides lifecycle callbacks for OneAuth operations. Grouped by concern — each implementation receives only its relevant group. All callbacks are optional — nil callbacks are no-ops.

Configure all hooks in one place on OneAuth.Hooks. Callers set only what they need:

oa := NewOneAuth(OneAuthConfig{
    Hooks: Hooks{
        Token: TokenHooks{
            OnRevoked: func(token, hint string) { audit.Log("revoked", token) },
        },
    },
})

See: https://github.com/panyam/oneauth/issues/110

type IntrospectRequest added in v0.0.83

type IntrospectRequest struct {
	Token string
}

IntrospectRequest is the input to TokenIntrospector.Introspect.

type IntrospectResponse added in v0.0.83

type IntrospectResponse struct {
	Result *IntrospectionResult
}

IntrospectResponse wraps the RFC 7662 introspection result.

type IntrospectionHandler added in v0.0.56

type IntrospectionHandler struct {
	// Introspector performs the actual token introspection (transport-independent).
	Introspector TokenIntrospector

	// Authenticator verifies the caller's client credentials.
	Authenticator ClientAuthenticator

	// AcceptedAudiences are the URLs the AS will accept as the
	// `aud` claim of a private_key_jwt / client_secret_jwt client
	// assertion (OIDC Core §9). Typically the introspection endpoint
	// URL plus the AS issuer URL. When empty the URL of the request
	// is used as a fallback, which works for single-host deployments
	// but breaks behind proxies that rewrite the path — populate
	// explicitly in production.
	AcceptedAudiences []string
}

IntrospectionHandler implements OAuth 2.0 Token Introspection (RFC 7662). Resource servers POST tokens to this endpoint to check validity, as an alternative to local JWT validation via JWKS.

The handler is a thin HTTP wrapper over TokenIntrospector (core logic) and ClientAuthenticator (caller verification).

See: https://www.rfc-editor.org/rfc/rfc7662

func NewIntrospectionHandler added in v0.0.78

func NewIntrospectionHandler(auth *APIAuth, clientKeyStore keys.KeyLookup) *IntrospectionHandler

NewIntrospectionHandler creates an IntrospectionHandler from an APIAuth and a client KeyLookup. This is the bridge between the old-style APIAuth configuration and the new core interfaces.

func (*IntrospectionHandler) ServeHTTP added in v0.0.56

func (h *IntrospectionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles POST /oauth/introspect per RFC 7662.

type IntrospectionResult added in v0.0.62

type IntrospectionResult struct {
	Active    bool   `json:"active"`
	Sub       string `json:"sub,omitempty"`
	Scope     string `json:"scope,omitempty"`
	ClientID  string `json:"client_id,omitempty"`
	TokenType string `json:"token_type,omitempty"`
	Exp       int64  `json:"exp,omitempty"`
	Iat       int64  `json:"iat,omitempty"`
	Iss       string `json:"iss,omitempty"`
	Jti       string `json:"jti,omitempty"`
	Aud       any    `json:"aud,omitempty"`
}

IntrospectionResult holds the parsed introspection response.

type IntrospectionValidator added in v0.0.62

type IntrospectionValidator struct {
	// IntrospectionURL is the auth server's introspection endpoint.
	// Required.
	IntrospectionURL string

	// ClientID and ClientSecret authenticate this resource server to the
	// introspection endpoint via HTTP Basic auth (client_secret_basic).
	// Required.
	ClientID     string
	ClientSecret string

	// HTTPClient is used for introspection requests. If nil, uses
	// http.DefaultClient.
	HTTPClient *http.Client

	// CacheTTL enables response caching. If > 0, introspection responses
	// are cached for this duration. A revoked token may remain "active"
	// in the cache for up to CacheTTL after revocation.
	// Default: 0 (no caching).
	CacheTTL time.Duration
	// contains filtered or unexported fields
}

IntrospectionValidator validates tokens by calling a remote introspection endpoint (RFC 7662), as an alternative to local JWT validation via JWKS.

Use this when:

  • The resource server can't access the KeyStore or JWKS endpoint
  • Centralized blacklist checking is needed
  • Opaque (non-JWT) tokens need validation

The validator authenticates to the introspection endpoint using client credentials (client_secret_basic).

Optional response caching reduces load on the auth server. Cache entries expire after CacheTTL (default: no cache).

See: https://www.rfc-editor.org/rfc/rfc7662

func (*IntrospectionValidator) Validate added in v0.0.62

func (v *IntrospectionValidator) Validate(token string) (*IntrospectionResult, error)

Validate calls the introspection endpoint to check if a token is active. Returns the introspection result with parsed claims, or an error if the introspection request itself failed (network error, auth failure, etc.).

An inactive token is NOT an error — it returns IntrospectionResult{Active: false}. Only transport/auth failures return errors.

func (*IntrospectionValidator) ValidateForMiddleware added in v0.0.62

func (v *IntrospectionValidator) ValidateForMiddleware(token string) (userID string, scopes []string, authType string, customClaims map[string]any, err error)

ValidateForMiddleware validates a token and returns the fields that APIMiddleware.validateRequest needs: userID, scopes, authType, customClaims. Returns an error if the token is inactive or introspection fails.

type JTIStore added in v0.0.83

type JTIStore interface {
	// SeenWithin reports whether `jti` was already marked seen within
	// the given lifetime. When false is returned the implementation
	// MUST also record `jti` as seen for at least `lifetime`. Single
	// call, atomic check-and-set — callers do not invoke a separate
	// Mark method.
	SeenWithin(jti string, lifetime time.Duration) bool
}

JTIStore tracks JWT IDs (the `jti` claim) of recently-validated client assertions to prevent replay (RFC 7523 §3 item 7, OIDC Core §10.1).

The store has at-most-once semantics: SeenWithin(jti, ttl) returns true if `jti` has been seen within the lifetime, false otherwise. The caller atomically marks `jti` as seen on the false branch.

Implementations must be goroutine-safe.

func NewInMemoryJTIStore added in v0.0.83

func NewInMemoryJTIStore() JTIStore

NewInMemoryJTIStore returns an in-memory JTIStore backed by a map with lazy eviction. Safe default for single-process deployments.

type JWTIssuerConfig added in v0.0.77

type JWTIssuerConfig struct {
	SigningKey          any
	SigningAlg          string
	Issuer              string
	Audience            string
	AccessExpiry        time.Duration
	ClientKeyLookup     keys.KeyLookup            // for client_credentials authentication
	RefreshStore        core.RefreshTokenStore    // for refresh_token grant
	ValidateCredentials core.CredentialsValidator // for password grant
	GetUserScopes       core.GetUserScopesFunc    // for password grant (optional)
	Hooks               TokenHooks
}

JWTIssuerConfig configures a jwtIssuer.

type JWTValidatorConfig added in v0.0.77

type JWTValidatorConfig struct {
	KeyLookup keys.KeyLookup
	Blacklist core.TokenBlacklist
	Issuer    string
	Audience  string
	Hooks     SecurityHooks
}

JWTValidatorConfig configures a jwtValidator.

type OneAuth added in v0.0.77

type OneAuth struct {
	// Core operation interfaces — each has minimal dependencies.
	Issuer        TokenIssuer
	Validator     TokenValidator
	Introspector  TokenIntrospector
	Revoker       TokenRevoker
	Authenticator ClientAuthenticator

	// Shared state — available for transport bindings that need direct access.
	KeyStore     keys.KeyStorage
	Blacklist    core.TokenBlacklist
	RefreshStore core.RefreshTokenStore

	// Hooks — lifecycle callbacks grouped by concern.
	Hooks Hooks
}

OneAuth is the transport-independent core of the authentication system. It composes focused interfaces (Option A — no god object) and wires hooks for lifecycle callbacks.

Use NewOneAuth to create an instance with all dependencies wired. Transport bindings (HTTP handlers, gRPC interceptors, MCP auth) are thin wrappers over these interfaces.

Library usage (no HTTP):

oa := apiauth.NewOneAuth(apiauth.OneAuthConfig{...})
token, _, _ := oa.Issuer.CreateAccessToken("alice", []string{"read"}, nil)
info, _ := oa.Validator.ValidateToken(token)
result, _ := oa.Introspector.Introspect(token)
oa.Revoker.Revoke(token, "access_token")

See: https://github.com/panyam/oneauth/issues/110

func NewOneAuth added in v0.0.77

func NewOneAuth(cfg OneAuthConfig) *OneAuth

NewOneAuth creates a fully wired OneAuth instance. All implementations receive only the interfaces they need.

func (*OneAuth) HTTPMiddleware added in v0.0.78

func (oa *OneAuth) HTTPMiddleware() *APIMiddleware

HTTPMiddleware returns an APIMiddleware wired to the OneAuth TokenValidator. Use this for protecting resource endpoints.

func (*OneAuth) IntrospectionHTTPHandler added in v0.0.78

func (oa *OneAuth) IntrospectionHTTPHandler() *IntrospectionHandler

IntrospectionHTTPHandler returns an http.Handler for POST /oauth/introspect.

func (*OneAuth) RevocationHTTPHandler added in v0.0.78

func (oa *OneAuth) RevocationHTTPHandler() *RevocationHandler

RevocationHTTPHandler returns an http.Handler for POST /oauth/revoke.

type OneAuthConfig added in v0.0.77

type OneAuthConfig struct {
	// Key management
	KeyStore keys.KeyStorage // required — stores client keys

	// Signing configuration
	SigningKey any    // []byte for HS256, *rsa.PrivateKey for RS256, etc.
	SigningAlg string // "HS256", "RS256", "ES256" — default "HS256"

	// JWT configuration
	Issuer       string        // JWT iss claim
	Audience     string        // JWT aud claim (optional)
	AccessExpiry time.Duration // default 15 minutes

	// Token lifecycle
	Blacklist    core.TokenBlacklist    // for access token revocation (optional)
	RefreshStore core.RefreshTokenStore // for refresh token management (optional)

	// Password grant callbacks (optional — only needed if password grant is used)
	ValidateCredentials core.CredentialsValidator // validates username/password
	GetUserScopes       core.GetUserScopesFunc    // returns allowed scopes for a user

	// Hooks — lifecycle callbacks
	Hooks Hooks
}

OneAuthConfig holds the dependencies for creating a OneAuth instance.

type PasswordGrantRequest added in v0.0.78

type PasswordGrantRequest struct {
	Username             string
	Password             string
	Scopes               []string                   // requested (intersected with allowed)
	AuthorizationDetails []core.AuthorizationDetail // RFC 9396
	ClientID             string                     // optional — associated client
}

PasswordGrantRequest holds the inputs for a password grant.

type PasswordGrantResponse added in v0.0.83

type PasswordGrantResponse struct {
	UserID               string
	AccessToken          string
	ExpiresIn            int64
	GrantedScopes        []string
	AuthorizationDetails []core.AuthorizationDetail
}

PasswordGrantResponse holds the output of a successful password grant. The caller uses UserID + GrantedScopes to create a refresh token if needed.

(Renamed from PasswordGrantResult during the 175 convention port; the PasswordGrantResult type alias below preserves the old name for one release as a deprecation bridge.)

type PasswordGrantResult deprecated added in v0.0.78

type PasswordGrantResult = PasswordGrantResponse

PasswordGrantResult is the previous name of PasswordGrantResponse.

Deprecated: use PasswordGrantResponse. Will be removed in a future release.

type ProtectedResourceMetadata added in v0.0.55

type ProtectedResourceMetadata struct {
	// Resource is the resource server's identifier (its base URL).
	// REQUIRED per RFC 9728 §3.
	Resource string `json:"resource"`

	// AuthorizationServers lists the authorization servers that the resource
	// server trusts to issue tokens. REQUIRED per RFC 9728 §3.
	AuthorizationServers []string `json:"authorization_servers"`

	// ScopesSupported lists the OAuth 2.0 scopes that this resource server
	// understands. Optional.
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// TokenFormatsSupported lists the token formats accepted (e.g., "jwt").
	// Optional.
	TokenFormatsSupported []string `json:"token_formats_supported,omitempty"`

	// SigningAlgsSupported lists the JWS signing algorithms the resource server
	// supports for validating tokens (e.g., "RS256", "ES256", "HS256").
	// Optional.
	SigningAlgsSupported []string `json:"resource_signing_alg_values_supported,omitempty"`

	// DocumentationURI points to human-readable documentation for the resource
	// server's API. Optional.
	DocumentationURI string `json:"resource_documentation,omitempty"`

	// IntrospectionEndpoint is the URL of the token introspection endpoint
	// (RFC 7662) that can be used to validate tokens for this resource.
	// Optional — included when the resource server supports introspection.
	IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`

	// CacheMaxAge controls the Cache-Control max-age header in seconds.
	// Defaults to 3600 (1 hour) if zero. Not serialized to JSON.
	CacheMaxAge int `json:"-"`
}

ProtectedResourceMetadata describes an OAuth 2.0 Protected Resource per RFC 9728. Resource servers serve this at GET /.well-known/oauth-protected-resource so clients can auto-discover which authorization servers are trusted, what scopes are supported, what token formats are accepted, and which signing algorithms are used.

Required fields: Resource and AuthorizationServers. All other fields are optional and omitted from JSON when empty.

See: https://www.rfc-editor.org/rfc/rfc9728

type RefreshGrantRequest added in v0.0.83

type RefreshGrantRequest struct {
	RefreshToken string
}

RefreshGrantRequest is the input to TokenIssuer.RefreshGrant.

type RefreshGrantResponse added in v0.0.83

type RefreshGrantResponse struct {
	Tokens *core.TokenPair
}

RefreshGrantResponse wraps the rotated token pair.

type RevocationHandler added in v0.0.77

type RevocationHandler struct {
	// Revoker performs the actual token revocation (transport-independent).
	Revoker TokenRevoker

	// Authenticator verifies the caller's client credentials.
	Authenticator ClientAuthenticator

	// AcceptedAudiences are the URLs the AS will accept as the
	// `aud` claim of a private_key_jwt / client_secret_jwt client
	// assertion (OIDC Core §9). When empty the URL of the request
	// is used as a fallback.
	AcceptedAudiences []string
}

RevocationHandler implements OAuth 2.0 Token Revocation (RFC 7009). It is a thin HTTP wrapper over TokenRevoker (core logic) and ClientAuthenticator (caller verification).

See: https://www.rfc-editor.org/rfc/rfc7009

func NewRevocationHandler added in v0.0.78

func NewRevocationHandler(auth *APIAuth, clientKeyStore keys.KeyLookup) *RevocationHandler

NewRevocationHandler creates a RevocationHandler from an APIAuth and a client KeyLookup. Bridge constructor for existing code.

func (*RevocationHandler) ServeHTTP added in v0.0.77

func (h *RevocationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles POST /oauth/revoke per RFC 7009.

type RevokeRequest added in v0.0.83

type RevokeRequest struct {
	Token         string
	TokenTypeHint string
}

RevokeRequest is the input to TokenRevoker.Revoke.

type RevokeResponse added in v0.0.83

type RevokeResponse struct{}

RevokeResponse — empty (success/failure via error). Wrapped per convention.

type SecurityHooks added in v0.0.77

type SecurityHooks struct {
	// OnTokenRejected fires when a token fails validation.
	// reason describes why (expired, bad signature, revoked, etc.).
	OnTokenRejected func(reason string)

	// OnBlacklistHit fires when a revoked token is presented.
	// This indicates token reuse after revocation — potential theft.
	OnBlacklistHit func(jti string)

	// OnAlgorithmMismatch fires when a token's alg header doesn't match
	// the stored key's algorithm. This is the CVE-2015-9235 attack vector.
	OnAlgorithmMismatch func(expected, got string)
}

SecurityHooks fires on security-relevant events. Use these for alerting, audit logging, and intrusion detection.

type TokenHooks added in v0.0.77

type TokenHooks struct {
	// OnIssued fires after an access token is successfully created.
	// subject is the token's sub claim, grantType is the OAuth grant used.
	OnIssued func(subject, grantType string)

	// OnRefreshed fires after a refresh token is rotated and a new access token issued.
	OnRefreshed func(subject string)

	// OnRevoked fires after a token is successfully revoked.
	// hint is the token_type_hint ("access_token", "refresh_token", or "").
	OnRevoked func(token, hint string)
}

TokenHooks fires on token lifecycle events.

type TokenInfo added in v0.0.77

type TokenInfo struct {
	// UserID is the subject (sub claim) — a user ID or client_id.
	UserID string

	// Scopes are the granted scopes from the token.
	Scopes []string

	// AuthorizationDetails are the RFC 9396 authorization_details from the token.
	// Nil if the token has no authorization_details.
	AuthorizationDetails []core.AuthorizationDetail

	// CustomClaims are non-standard JWT claims (everything not in standardClaims).
	CustomClaims map[string]any

	// AuthType is "jwt" or "api_key".
	AuthType string
}

TokenInfo holds the validated claims extracted from a token. Returned wrapped inside ValidateTokenResponse.

type TokenIntrospector added in v0.0.77

type TokenIntrospector interface {
	// Introspect checks a token's validity and returns its claims.
	// Returns {Active: false} on the wrapped result for any invalid token
	// (never reveals why — RFC 7662 §2.2 confidentiality).
	Introspect(ctx context.Context, req *IntrospectRequest) (*IntrospectResponse, error)
}

TokenIntrospector performs RFC 7662 token introspection.

func NewTokenIntrospector added in v0.0.77

func NewTokenIntrospector(v TokenValidator) TokenIntrospector

NewTokenIntrospector creates a TokenIntrospector backed by a TokenValidator.

type TokenIssuer added in v0.0.77

type TokenIssuer interface {
	// CreateAccessToken mints a JWT with the given subject, scopes, and
	// optional RFC 9396 authorization_details.
	CreateAccessToken(ctx context.Context, req *CreateAccessTokenRequest) (*CreateAccessTokenResponse, error)

	// ClientCredentials performs the full client_credentials grant:
	// authenticates the client, validates scopes/details, and returns a token pair.
	ClientCredentials(ctx context.Context, req *ClientCredentialsRequest) (*ClientCredentialsResponse, error)

	// RefreshGrant rotates a refresh token and returns a new access + refresh
	// token pair. Handles theft detection (revoked token → revoke entire family).
	RefreshGrant(ctx context.Context, req *RefreshGrantRequest) (*RefreshGrantResponse, error)

	// PasswordGrant authenticates a user with username/password and returns
	// an access token. Does NOT create a refresh token — the caller's
	// responsibility (via RefreshTokenStore.CreateRefreshToken), since refresh
	// tokens may carry transport-specific metadata (device info, IP, etc.).
	PasswordGrant(ctx context.Context, req *PasswordGrantRequest) (*PasswordGrantResponse, error)
}

TokenIssuer mints access tokens via the standard OAuth 2.0 grants.

func NewJWTIssuer added in v0.0.77

func NewJWTIssuer(cfg JWTIssuerConfig) TokenIssuer

NewJWTIssuer creates a TokenIssuer that signs JWTs.

type TokenRevoker added in v0.0.77

type TokenRevoker interface {
	// Revoke invalidates a token. The TokenTypeHint ("access_token" or
	// "refresh_token") guides which store to check first; empty hint tries both.
	Revoke(ctx context.Context, req *RevokeRequest) (*RevokeResponse, error)
}

TokenRevoker invalidates tokens per RFC 7009.

func NewTokenRevoker added in v0.0.77

func NewTokenRevoker(cfg TokenRevokerConfig) TokenRevoker

NewTokenRevoker creates a TokenRevoker.

type TokenRevokerConfig added in v0.0.77

type TokenRevokerConfig struct {
	Blacklist    core.TokenBlacklist
	RefreshStore core.RefreshTokenStore
	Hooks        TokenHooks
}

TokenRevokerConfig configures a tokenRevoker.

type TokenValidator added in v0.0.77

type TokenValidator interface {
	// ValidateToken parses and validates a token (signature, expiry, issuer,
	// audience, blacklist) and returns its claims.
	ValidateToken(ctx context.Context, req *ValidateTokenRequest) (*ValidateTokenResponse, error)

	// CheckScopes validates a token and verifies it carries every required scope.
	CheckScopes(ctx context.Context, req *CheckScopesRequest) (*CheckScopesResponse, error)

	// CheckAuthorizationDetails validates a token and verifies it carries
	// authorization_details entries for every required type (RFC 9396).
	CheckAuthorizationDetails(ctx context.Context, req *CheckAuthorizationDetailsRequest) (*CheckAuthorizationDetailsResponse, error)
}

TokenValidator parses tokens, verifies their signatures and standard claims, and checks scope / RFC 9396 authorization_details requirements.

func NewJWTValidator added in v0.0.77

func NewJWTValidator(cfg JWTValidatorConfig) TokenValidator

NewJWTValidator creates a TokenValidator that validates JWTs locally.

type TrustedAssertionIssuer added in v0.0.81

type TrustedAssertionIssuer struct {
	// Issuer is the expected `iss` claim value (e.g.,
	// "https://corp-idp.example.com"). REQUIRED.
	Issuer string

	// PublicKey is a static public key for signature verification.
	// Either this or KeyFunc MUST be set. Suitable for tests and
	// single-key issuers; for production with key rotation use KeyFunc.
	PublicKey crypto.PublicKey

	// KeyFunc resolves a public key from the JWT header (typically
	// looking up `kid` against a cached JWKS). When set it takes
	// precedence over PublicKey. The token argument is the parsed
	// (but not yet signature-verified) JWT.
	KeyFunc func(token *jwt.Token) (crypto.PublicKey, error)

	// Audiences lists acceptable `aud` claim values for assertions
	// signed by this issuer. When empty, defaults to the AS's
	// JWTAudience (or its IssuerURL if no audience is configured).
	// RFC 7523 §3 requires the AS to identify itself by the audience
	// claim — the default makes the token endpoint URL implicit.
	Audiences []string

	// AcceptedAlgorithms restricts the JWT alg values accepted for
	// assertions from this issuer (e.g., {"RS256", "ES256"}). Empty
	// = accept any non-`none` algorithm advertised by the JWT library.
	// Set this in production to lock out alg-confusion attacks.
	AcceptedAlgorithms []string
}

TrustedAssertionIssuer describes an upstream IdP whose JWT assertions the AS will accept for the jwt-bearer grant (RFC 7523 §2.1) and the token-exchange grant with subject_token_type=urn:ietf:params:oauth:token-type:jwt (RFC 8693 §2.1.1).

At least one of PublicKey or KeyFunc must be set so signatures can be verified. KeyFunc takes precedence when both are set; it lets callers resolve keys from a JWKS by `kid` header.

The Issuer field is matched verbatim against the JWT's `iss` claim (case-sensitive, no trailing-slash normalization — match what the upstream IdP actually emits).

type ValidateTokenRequest added in v0.0.83

type ValidateTokenRequest struct {
	Token string
}

ValidateTokenRequest is the input to TokenValidator.ValidateToken.

type ValidateTokenResponse added in v0.0.83

type ValidateTokenResponse struct {
	Info *TokenInfo
}

ValidateTokenResponse wraps the parsed token claims.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL