apiauth

package
v0.1.26 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultDeviceAuthorizationExpiry is the RFC 8628 §3.4 recommended
	// 15-minute deadline for a user to complete the verification flow.
	DefaultDeviceAuthorizationExpiry = 15 * time.Minute

	// DefaultDeviceAuthorizationInterval is the RFC 8628 §3.5 default
	// polling interval; clients MUST wait at least this long between
	// token requests.
	DefaultDeviceAuthorizationInterval = 5
)

Spec defaults for RFC 8628. Callers tune via APIAuth fields.

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 BCLEventType = "http://schemas.openid.net/event/backchannel-logout"

BCLEventType is the single event-identifier URI defined by OIDC Back-Channel Logout 1.0 §2.4. Every logout_token MUST carry an `events` claim whose only key is this URI; the value is the empty JSON object.

See: https://openid.net/specs/openid-connect-backchannel-1_0.html#LogoutToken

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 DeviceCodeGrantType = "urn:ietf:params:oauth:grant-type:device_code"

DeviceCodeGrantType is the OAuth grant type URI for the RFC 8628 device authorization grant. The device polls the token endpoint with this grant_type and a device_code obtained from /device/authorize.

See: https://www.rfc-editor.org/rfc/rfc8628#section-3.4

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 GetSubjectFromAPIContext added in v0.1.4

func GetSubjectFromAPIContext(ctx context.Context) string

GetSubjectFromAPIContext retrieves the authenticated subject (RFC 7519 `sub` — user ID for human-driven flows, client_id for client_credentials) 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 CredentialsValidator                              // Validates username/password
	GetSubjectScopes    core.GetSubjectScopesFunc                         // Returns allowed scopes for the subject (user ID or client_id)
	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

	// TokenHooks fires on token lifecycle events handled directly by APIAuth
	// (logout / logout-all). The HTTP-facing APIAuth is wired field-by-field
	// rather than via OneAuthConfig; callers who want logout-all to drive
	// the OIDC Back-Channel Logout dispatcher must populate
	// TokenHooks.OnSubjectRevoked here. Leaving it zero keeps HandleLogout /
	// HandleLogoutAll behaviorally unchanged.
	TokenHooks TokenHooks

	// DeviceAuthStore enables the RFC 8628 device authorization grant.
	// When non-nil the token endpoint accepts
	// grant_type=urn:ietf:params:oauth:grant-type:device_code and the
	// caller is expected to mount DeviceAuthorizationHandler at the
	// /device/authorize path. Nil keeps the token endpoint behaviorally
	// identical to its pre-#117 surface.
	DeviceAuthStore core.DeviceAuthorizationStore

	// AppStore lets the token endpoint look up a registered client's
	// `token_endpoint_auth_method` to decide whether confidential-client
	// authentication is required on the device-code redemption path
	// (issue 266).
	//
	// When nil, the device-grant handler accepts the form `client_id`
	// alone for backward compatibility with the v0.1.23 wire protocol.
	//
	// When non-nil, AppStore becomes the source of truth: the device
	// authorization's bound client_id MUST resolve to a registered
	// AppRegistration, otherwise the redemption is rejected with
	// `invalid_client`. The handler does NOT silently downgrade to the
	// unauthenticated path on lookup failure — opting into AppStore is
	// opting into strict enforcement. Production deployments with
	// confidential device clients MUST wire it so a stolen device_code
	// cannot be redeemed without the registered client's credentials.
	AppStore core.AppRegistrationStore

	// TracerProvider opts the /token endpoint into SEP-414 tracing.
	// When set, ServeHTTP extracts an inbound W3C `traceparent` header
	// and emits a single `oneauth.token.issue` span with the parsed
	// grant type as an attribute. Nil keeps the handler on the no-op
	// fast path. The same TracerProvider should usually be passed to
	// IntrospectionHandler, RevocationHandler, JWKSHandler, and the
	// JWKSKeyStore so all spans share one trace.
	TracerProvider trace.TracerProvider
	// contains filtered or unexported fields
}

APIAuth handles API token-based authentication

func (*APIAuth) ApproveDeviceAuthorization added in v0.1.23

func (a *APIAuth) ApproveDeviceAuthorization(r *http.Request, userCode, subject string, grantedScopes []string) error

ApproveDeviceAuthorization is the programmatic approval entry point. The follow-up UI PR wires this behind a localauth-protected HTML form; tests and in-process consumers call it directly.

userCode is normalized case-insensitively. grantedScopes overrides the scope set the device requested (consent UI may narrow the scope); pass nil to keep the original set.

func (*APIAuth) DenyDeviceAuthorization added in v0.1.23

func (a *APIAuth) DenyDeviceAuthorization(r *http.Request, userCode string) error

DenyDeviceAuthorization is the programmatic deny entry point. Mirrors ApproveDeviceAuthorization's signature for the future UI's symmetry.

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) Issuer added in v0.1.8

func (a *APIAuth) Issuer() TokenIssuer

Issuer returns the TokenIssuer implementation backing APIAuth's token-mint HTTP handlers. Lazily built from APIAuth's configuration on first call; safe for use after all APIAuth fields are populated.

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) Validator added in v0.1.8

func (a *APIAuth) Validator() TokenValidator

Validator returns the TokenValidator implementation backing APIAuth's token-validation paths (middleware, introspection). Lazily built from APIAuth's configuration on first call.

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

	// TracerProvider opts the resource-server validation path into
	// SEP-414 tracing. When set, the lazily-built validator emits
	// `oneauth.signature_verify` spans, and the lookup-by-kid call
	// against KeyStore inherits the same trace context. Nil keeps
	// validation on the no-op fast path.
	TracerProvider trace.TracerProvider
	// 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"`
	DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"` // RFC 8628 §4

	// 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"`

	// BackchannelLogoutSupported advertises OIDC Back-Channel Logout 1.0 §3.1
	// — when true, the AS sends a signed logout_token to a client's registered
	// backchannel_logout_uri at session-revoke time. Pointer semantics: nil
	// omits the field; an explicit `false` advertises non-support to clients.
	// Set this true only when a BCLDispatcher is actually wired; otherwise
	// clients that key off the advertisement will silently miss logouts.
	BackchannelLogoutSupported *bool `json:"backchannel_logout_supported,omitempty"`

	// BackchannelLogoutSessionSupported advertises OIDC BCL 1.0 §3.1 — when
	// true, logout_tokens issued by this AS include a `sid` claim that the
	// receiver can use to revoke a single OIDC session rather than every
	// session for the subject. Pointer semantics match
	// BackchannelLogoutSupported.
	BackchannelLogoutSessionSupported *bool `json:"backchannel_logout_session_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 AppRegistrationLookup added in v0.1.20

type AppRegistrationLookup interface {
	// GetAppRegistration returns the persisted registration for clientID, or
	// (nil, false) if no such client exists or its registration is being
	// torn down. Returning a clone is recommended so callers cannot mutate
	// store state through the returned pointer.
	GetAppRegistration(ctx context.Context, clientID string) (*core.AppRegistration, bool)
}

AppRegistrationLookup is the narrow read-only slice of admin.AppRegistrar that BCLDispatcher needs. Defined here (rather than importing admin/) to avoid a circular dependency — admin/ already imports apiauth/ transitively via the hooks layer in some configurations.

Implementations: *admin.AppRegistrar satisfies this via RLockApps; tests can inject an in-memory map.

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 BCLDispatcher added in v0.1.20

type BCLDispatcher struct {
	// Issuer mints the signed logout_token. Required.
	Issuer LogoutTokenIssuer

	// Apps resolves a client_id to its registration so we can read
	// backchannel_logout_uri and backchannel_logout_session_required.
	// Required.
	Apps AppRegistrationLookup

	// RefreshStore enumerates a subject's active grants. Required for
	// subject-scoped Dispatch calls; ignored for explicit-client calls.
	RefreshStore core.RefreshTokenStore

	// HTTPClient is used for outbound POSTs. Defaults to an http.Client with
	// a 5-second per-request timeout so a stuck receiver cannot pin a
	// goroutine indefinitely.
	HTTPClient *http.Client

	// Logger receives non-fatal dispatch errors (4xx/5xx from receiver,
	// network failures, signing errors). If nil, log.Default() is used.
	Logger *log.Logger

	// SyncForTest makes Dispatch block until every POST completes. Tests use
	// this to assert the receiver was hit before they read its captured
	// state; production callers should leave it false so revocation latency
	// is not coupled to receiver responsiveness.
	SyncForTest bool

	// AllowPrivateHosts opts in to dialing receiver URIs whose resolved IP
	// is loopback / RFC1918 / link-local / unspecified / multicast. Off by
	// default — the default HTTPClient's dialer rejects such connections so
	// a (mis-configured or malicious) `backchannel_logout_uri` cannot be
	// used to make the AS POST to internal services on its behalf, even if
	// the hostname's DNS answer at dial time differs from registration time
	// (rebinding). Closed-network deployments (AS + RS in the same VPC) can
	// flip this on; admin.AppRegistrar.AllowPrivateBCLHosts is the matching
	// registration-side knob.
	AllowPrivateHosts bool
	// contains filtered or unexported fields
}

BCLDispatcher pushes OIDC Back-Channel Logout 1.0 notifications to every client that registered a backchannel_logout_uri and has an active refresh-token grant for the affected subject.

The dispatcher is intentionally narrow: callers tell it a session ended (Dispatch), it looks up the clients to notify, mints one logout_token per client, and POSTs each token to the registered URI. Dispatch is fire-and- forget by default — a slow or broken receiver MUST NOT stall the revocation path. Set SyncForTest=true to wait for all POSTs before returning (used by e2e tests; not recommended for production wiring).

Retry / backoff: the spec is silent (§3.2 ¶3); this dispatcher does not retry on failure. Follow-ups can wrap HTTPClient with a retry transport.

func (*BCLDispatcher) Dispatch added in v0.1.20

Dispatch resolves the affected client set, mints a logout_token per client, and POSTs each token to its registered backchannel_logout_uri.

Returns nil immediately when no eligible client exists (no clients in the union, or none of them registered a BCL URI). Per-client errors are logged via Logger and otherwise swallowed: BCL is best-effort notification, not transactional with revocation.

func (*BCLDispatcher) Wait added in v0.1.20

func (d *BCLDispatcher) Wait()

Wait blocks until every async POST started by Dispatch has finished. Tests use it as a barrier; production code that wants synchronous behavior should set SyncForTest instead.

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 CreateLogoutTokenRequest added in v0.1.20

type CreateLogoutTokenRequest struct {
	// Audience is the receiving client's client_id. Per §2.4 this becomes the
	// `aud` claim and identifies which client the logout applies to. Required.
	Audience string

	// Subject is the user identifier (RFC 7519 `sub`) whose session ended.
	// Optional iff SID is set; required otherwise.
	Subject string

	// SID is the session identifier (`sid`). When the receiving client
	// registered with backchannel_logout_session_required=true the AS MUST
	// include this; otherwise SHOULD include when known. oneauth maps SID to
	// the refresh-token family ID — the closest analogue to an OIDC session
	// the library tracks today.
	SID string
}

CreateLogoutTokenRequest is the input to LogoutTokenIssuer.CreateLogoutToken.

At least one of Subject and SID MUST be populated. Per OIDC BCL §2.4 a logout_token without both `sub` and `sid` is invalid and MUST be rejected by the receiving client; the constructor enforces this so callers cannot silently mint a token that every conforming RS will reject.

type CreateLogoutTokenResponse added in v0.1.20

type CreateLogoutTokenResponse struct {
	// Token is the serialized JWS. It is ready to POST as the value of the
	// `logout_token` form field per §2.5.
	Token string
}

CreateLogoutTokenResponse wraps the minted logout_token JWT.

type CredentialsValidator added in v0.1.0

type CredentialsValidator = accounts.CredentialsValidator

CredentialsValidator is re-exported from accounts as a single shared function shape so apiauth's password-grant validator field and localauth's host-supplied validator are assignable to each other without conversion.

type CustomClaimsFunc added in v0.1.8

type CustomClaimsFunc func(subject string, scopes []string) (map[string]any, error)

CustomClaimsFunc is called during access-token issuance to inject additional non-standard claims. Returning a claim key that collides with a standard JWT claim (sub, iss, aud, exp, iat, type, scopes, jti, authorization_details) is ignored with a log warning — standard claims are owned by the issuer.

type DeviceAuthorizationHandler added in v0.1.23

type DeviceAuthorizationHandler struct {
	// Store persists the device authorization. Required.
	Store core.DeviceAuthorizationStore

	// VerificationURI is the absolute URL the device displays to the
	// user. RFC 8628 §3.2 makes this REQUIRED on the response. Production
	// deployments point it at the AS's HTML user-code form (a follow-up
	// PR ships this UI); tests can point it anywhere — the field is
	// echoed verbatim.
	VerificationURI string

	// VerificationURICompleteTemplate, when non-empty, is appended with
	// the user_code substituted into "%s" to produce the
	// verification_uri_complete field (RFC 8628 §3.3.1). The convenience
	// URL lets the device generate a QR code that pre-fills the form.
	// Example: "https://auth.example.com/device?user_code=%s".
	VerificationURICompleteTemplate string

	// Expiry overrides the default 15-minute authorization window.
	Expiry time.Duration

	// Interval overrides the default 5-second polling interval.
	Interval int

	// ClientAuthenticator, when non-nil, authenticates the calling client
	// before minting codes. When nil the handler accepts any client_id —
	// suitable for public-client-only deployments and tests, NOT for
	// production with confidential clients.
	ClientAuthenticator ClientAuthenticator
}

DeviceAuthorizationHandler serves POST /device/authorize per RFC 8628 §3.1 / §3.2. The handler validates the client, mints fresh device_code + user_code, persists a pending authorization, and returns the polling parameters the device needs.

The handler authenticates the client via the same ClientAuthenticator the token endpoint uses (when set) so public clients (`token_endpoint_ auth_method=none`) and confidential clients are handled uniformly.

func (*DeviceAuthorizationHandler) ServeHTTP added in v0.1.23

ServeHTTP implements the RFC 8628 §3.1 device authorization request endpoint. Body MUST be application/x-www-form-urlencoded. Form fields:

  • client_id (REQUIRED for public clients; confidential clients also send credentials, picked up by the ClientAuthenticator)
  • scope (OPTIONAL)
  • audience (OPTIONAL, RFC 8707 extension)

On success returns 200 with the JSON shape defined by §3.2.

type DeviceTemplates added in v0.1.26

type DeviceTemplates struct {
	// Form renders the GET /device code entry page. Data: deviceFormData.
	Form *template.Template

	// Consent renders the GET /device/approve consent screen. Data:
	// deviceConsentData.
	Consent *template.Template

	// Done renders the post-decision "return to your device" page.
	// Data: deviceDoneData.
	Done *template.Template
}

DeviceTemplates lets callers override any of the three built-in HTML pages with their own branded versions. Each field is a parsed `*template.Template` whose Execute call receives the data shape described on the corresponding default constant below.

type DeviceVerificationHandler added in v0.1.26

type DeviceVerificationHandler struct {
	// Store enumerates pending device authorizations by user_code.
	// Required.
	Store core.DeviceAuthorizationStore

	// AppStore resolves the client_id bound to a device authorization
	// to its registered metadata so the consent screen can render the
	// human-readable client_name and scope list. Nil renders the raw
	// client_id; never a hard failure.
	AppStore core.AppRegistrationStore

	// Approve transitions a pending authorization to approved and binds
	// the subject. Wire `APIAuth.ApproveDeviceAuthorization` here.
	Approve func(r *http.Request, userCode, subject string, scopes []string) error

	// Deny transitions a pending authorization to denied. Wire
	// `APIAuth.DenyDeviceAuthorization` here.
	Deny func(r *http.Request, userCode string) error

	// SubjectFromRequest returns the authenticated subject ("" if the
	// user is unauthenticated). Wire `httpauth.Middleware.GetLoggedInSubject`.
	SubjectFromRequest func(r *http.Request) string

	// CSRFTokenFromRequest returns the per-request CSRF token to embed
	// in the rendered form. Wire `httpauth.CSRFToken`.
	CSRFTokenFromRequest func(r *http.Request) string

	// LoginRedirectURL is the URL Submit redirects unauthenticated users
	// to. The handler appends a `?next=<consent_url>` query so the user
	// returns to the consent screen after logging in. Empty defaults to
	// `/auth/login`, the convention used elsewhere in the library.
	LoginRedirectURL string

	// LoginNextParam is the query parameter name used to round-trip the
	// post-login return URL. Empty defaults to `next`.
	LoginNextParam string

	// Templates overrides the built-in HTML templates. Set any subset of
	// fields; nil fields fall back to the package defaults.
	Templates *DeviceTemplates
}

DeviceVerificationHandler serves the RFC 8628 §3.3 user-facing verification flow — the four HTML pages that bridge between the device polling at /api/token and the user authorizing on a separate device. Routes:

GET  /device         → Form    — code entry form
POST /device         → Submit  — verifies user_code, redirects to login or consent
GET  /device/approve → Consent — shows client_name + scopes, approve/deny buttons
POST /device/approve → Decide  — calls Approve/Deny + renders "return to device" page

The handler keeps apiauth's no-httpauth-import invariant by taking session + CSRF lookups as plain functions. Callers wire `httpauth.Middleware.GetLoggedInSubject` and `httpauth.CSRFToken` into the corresponding fields and mount each route behind the same middleware that protects their other login pages.

func (*DeviceVerificationHandler) Consent added in v0.1.26

Consent serves GET /device/approve — the consent screen. The user MUST be authenticated; mount behind `httpauth.Middleware.EnsureUser` (or equivalent) so an unauthenticated user is bounced to login.

func (*DeviceVerificationHandler) Decide added in v0.1.26

Decide serves POST /device/approve — the user clicked Approve or Deny. Wrap with `httpauth.CSRFMiddleware.Protect` AND `httpauth.Middleware.EnsureUser`; the handler trusts both have run.

func (*DeviceVerificationHandler) Form added in v0.1.26

Form serves GET /device — the code entry page.

func (*DeviceVerificationHandler) Submit added in v0.1.26

Submit serves POST /device — verifies the submitted user_code and either redirects the user to the login flow (if unauthenticated) or to the consent screen.

CSRF protection is the caller's responsibility — wrap this route with `httpauth.CSRFMiddleware.Protect` so the token is enforced before this method runs.

type DispatchRequest added in v0.1.20

type DispatchRequest struct {
	// Subject is the user identifier whose session ended.
	Subject string

	// SID is the OIDC session ID. oneauth maps this to the refresh-token
	// family ID; pass empty when no family-scoped revoke happened.
	SID string

	// ClientIDs names clients to notify directly. Useful when the trigger is
	// a single-token revoke and the AS already knows the client_id from the
	// token claims.
	ClientIDs []string
}

DispatchRequest is the input to BCLDispatcher.Dispatch.

At least one of Subject and ClientIDs MUST be set:

  • Subject only: enumerate every client with an active grant for that subject via RefreshStore.GetSubjectTokens.
  • ClientIDs only: notify exactly those clients; used for single-token revoke where the affected client is known from the token itself.
  • Both: union (notify the explicit clients plus any others holding active grants for the subject).

type DispatchResponse added in v0.1.20

type DispatchResponse struct{}

DispatchResponse is empty — dispatch errors are logged, not returned, so a failing client cannot block the revocation path. The struct is preserved for forward-compat headroom (e.g., to expose per-client outcomes for telemetry without changing the method signature).

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

	// TracerProvider opts the introspection endpoint into SEP-414
	// tracing. When set, ServeHTTP extracts an inbound `traceparent`
	// header and emits an `oneauth.introspect` span carrying the
	// resulting `token_active` boolean. Nil keeps tracing on the
	// no-op fast path.
	TracerProvider trace.TracerProvider
}

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. The new handler inherits the APIAuth's TracerProvider so spans share one trace across /token and /introspect.

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

	// TracerProvider opts the introspection client into SEP-414
	// tracing. When set, ValidateWithContext emits an
	// `oneauth.introspection_client.request` span around the outbound
	// HTTP call AND injects a W3C `traceparent` header so the
	// upstream introspection endpoint can stitch its `oneauth.introspect`
	// span into the same trace. Nil keeps the path on the no-op fast
	// path with no allocation cost.
	TracerProvider trace.TracerProvider
	// 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 is the context-free convenience form of ValidateWithContext. SEP-414 trace propagation requires a context — callers that have one (any path serving an HTTP request) should prefer ValidateWithContext so the outbound introspection call inherits the inbound trace.

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 is the context-free convenience form of ValidateForMiddlewareWithContext. Prefer the context-bearing variant from any HTTP-serving path so SEP-414 trace propagation works.

func (*IntrospectionValidator) ValidateForMiddlewareWithContext added in v0.1.14

func (v *IntrospectionValidator) ValidateForMiddlewareWithContext(ctx context.Context, token string) (userID string, scopes []string, authType string, customClaims map[string]any, err error)

ValidateForMiddlewareWithContext validates a token via the introspection endpoint and returns the fields APIMiddleware.validateRequest needs: userID, scopes, authType, customClaims. Returns an error if the token is inactive or introspection fails. ctx is forwarded into the outbound HTTP call so trace context propagates to the upstream introspection server (see ValidateWithContext).

func (*IntrospectionValidator) ValidateWithContext added in v0.1.14

func (v *IntrospectionValidator) ValidateWithContext(ctx context.Context, token string) (*IntrospectionResult, error)

ValidateWithContext 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.

When TracerProvider is set, the call emits an `oneauth.introspection_client.request` span and injects a W3C `traceparent` on the outbound HTTP request so the upstream /oauth/introspect endpoint can stitch its own span into the trace.

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 CredentialsValidator      // for password grant
	GetSubjectScopes    core.GetSubjectScopesFunc // for password grant (optional)
	CustomClaims        CustomClaimsFunc          // optional per-token custom-claim injection
	Hooks               TokenHooks
}

JWTIssuerConfig configures a jwtIssuer.

type JWTLogoutTokenIssuerConfig added in v0.1.20

type JWTLogoutTokenIssuerConfig struct {
	// SigningKey is the AS signing key. For HS256 pass []byte; for RS256/ES256
	// pass the private key.
	SigningKey any

	// SigningAlg names the JWS algorithm (e.g. "RS256"). Empty falls back to
	// HS256 when SigningKey is a []byte.
	SigningAlg string

	// Issuer is the AS issuer URL — the value the receiver expects as the
	// `iss` claim and the key under which it looked up the AS JWKS.
	Issuer string

	// TokenTTL bounds the validity window for replay protection. The OIDC BCL
	// spec does not require `exp` but receivers are encouraged to reject
	// stale tokens; we default to 2 minutes — long enough for slow networks,
	// short enough that a leaked token isn't useful for long.
	TokenTTL time.Duration
}

JWTLogoutTokenIssuerConfig configures a jwtLogoutTokenIssuer.

type JWTValidatorConfig added in v0.0.77

type JWTValidatorConfig struct {
	KeyLookup keys.KeyLookup
	// SigningKey is an optional fallback used when KeyLookup is nil or the
	// token's kid / client_id does not resolve through it. For HS256, supply
	// []byte; for RS256/ES256, supply the verification key (*rsa.PublicKey,
	// *ecdsa.PublicKey) directly.
	SigningKey any
	SigningAlg string
	Blacklist  core.TokenBlacklist
	Issuer     string
	Audience   string
	Hooks      SecurityHooks

	// TracerProvider opts the signature-verify hot path into SEP-414
	// tracing. When set, ValidateToken emits an `oneauth.signature_verify`
	// span (attributes: `jwt.alg`, `jwt.kid`). Nil keeps the path on the
	// no-op fast path. Typically populated from APIAuth.TracerProvider
	// so spans nest under `oneauth.token.issue` (issuer) or under the
	// caller's span (resource server).
	TracerProvider trace.TracerProvider
}

JWTValidatorConfig configures a jwtValidator.

type LogoutTokenIssuer added in v0.1.20

type LogoutTokenIssuer interface {
	// CreateLogoutToken mints a signed logout_token. The returned response
	// carries the serialized JWT only; the dispatcher is responsible for
	// transporting it.
	CreateLogoutToken(ctx context.Context, req *CreateLogoutTokenRequest) (*CreateLogoutTokenResponse, error)
}

LogoutTokenIssuer mints signed `logout_token` JWTs per OIDC Back-Channel Logout 1.0 §2.4 for delivery to a client's registered backchannel_logout_uri.

It follows the gRPC-shape convention adopted in 175 — a single method that takes a request struct and returns a wrapped response. Implementations reuse the AS signing key already in use by TokenIssuer so RSes can verify logout_tokens against the same JWKS they use for access tokens.

func NewJWTLogoutTokenIssuer added in v0.1.20

func NewJWTLogoutTokenIssuer(cfg JWTLogoutTokenIssuerConfig) LogoutTokenIssuer

NewJWTLogoutTokenIssuer returns a LogoutTokenIssuer that signs logout_tokens with the supplied key.

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 CredentialsValidator      // validates username/password
	GetSubjectScopes    core.GetSubjectScopesFunc // returns allowed scopes for the subject (user ID or client_id)

	// CustomClaims is called during access-token issuance to inject additional
	// non-standard claims into the JWT. Standard JWT claims (sub, iss, aud,
	// exp, iat, type, scopes, jti, authorization_details) cannot be overridden.
	CustomClaims CustomClaimsFunc

	// 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 {
	Subject              string // RFC 7519 sub — user ID for password grant
	AccessToken          string
	ExpiresIn            int64
	GrantedScopes        []string
	AuthorizationDetails []core.AuthorizationDetail
}

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

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

	// TracerProvider opts the revocation endpoint into SEP-414 tracing.
	// When set, ServeHTTP extracts an inbound `traceparent` header and
	// emits an `oneauth.revoke` span. Nil keeps the handler on the
	// no-op fast path.
	TracerProvider trace.TracerProvider
}

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. The new handler inherits the APIAuth's TracerProvider so spans share one trace across /token and /revoke.

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)

	// OnSubjectRevoked fires when every active grant for a subject has been
	// revoked (logout-all). Subject is the affected user; sid is the OIDC
	// session ID when one is associated with the revocation (empty for
	// subject-wide revokes that are not session-scoped). clientIDs lists
	// every client that held an active grant at revoke time — captured
	// BEFORE the revoke so subscribers (notably the BCL dispatcher) can
	// notify them without having to re-query a store that, post-revoke,
	// returns nothing. Empty when no client identifiers were available.
	OnSubjectRevoked func(subject, sid string, clientIDs []string)

	// OnTokenRevoked fires when a single refresh token (or all tokens in a
	// family) is revoked, after subject + client_id are known. Provides the
	// affected subject, sid (family ID, when known), and clientID. Distinct
	// from OnRevoked so subscribers (notably BCL) get the routing identifiers
	// without having to re-parse the token. clientID is empty when the
	// trigger lacks a known client (e.g., admin-side revoke by jti).
	OnTokenRevoked func(subject, sid, clientID string)
}

TokenHooks fires on token lifecycle events.

type TokenInfo added in v0.0.77

type TokenInfo struct {
	// Subject is the principal the token represents (RFC 7519 sub) — a
	// user ID for human-driven flows or a client_id for
	// client_credentials.
	Subject 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