protocol

package
v2.1.1 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// ScopeOpenID is REQUIRED for all OpenID Requests.
	ScopeOpenID = "openid"

	// ScopeProfile requests access to the End-User's default profile Claims
	// (name, family_name, given_name, middle_name, nickname, preferred_username,
	// profile, picture, website, gender, birthdate, zoneinfo, locale, updated_at).
	ScopeProfile = "profile"

	// ScopeEmail requests access to the email and email_verified Claims.
	ScopeEmail = "email"

	// ScopeAddress requests access to the address Claim.
	ScopeAddress = "address"

	// ScopePhone requests access to the phone_number and phone_number_verified Claims.
	ScopePhone = "phone"

	// ScopeOfflineAccess requests that an OAuth 2.0 Refresh Token be issued.
	// OIDC Core 1.0 §11 (Offline Access)
	ScopeOfflineAccess = "offline_access"
)

OIDC Core 1.0 §5.4 — Scope Claims

https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
View Source
const (
	// PromptNone disallows the OP from displaying any authentication or consent UI pages.
	// An error (login_required, interaction_required, ...) is returned if the user
	// is not already authenticated or consent is needed.
	PromptNone = "none"

	// PromptLogin directs the OP to prompt the End-User for reauthentication.
	PromptLogin = "login"

	// PromptConsent directs the OP to prompt the End-User for consent.
	PromptConsent = "consent"

	// PromptSelectAccount directs the OP to prompt the End-User to select a user account.
	PromptSelectAccount = "select_account"
)

OIDC Core 1.0 §3.1.2.1 — Authentication Request (prompt parameter)

https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
View Source
const (

	// InvalidRequest: The request is missing a required parameter, includes an
	// unsupported parameter value (other than grant type), repeats a parameter,
	// includes multiple credentials, uses more than one mechanism for
	// authenticating the client, or is otherwise malformed.
	// RFC 6749 §5.2 (OAuth 2.0)
	InvalidRequest errorType = "invalid_request"

	// InvalidClient: Client authentication failed (e.g., unknown client, no
	// client authentication included, or unsupported authentication method).
	// RFC 6749 §5.2 (OAuth 2.0)
	InvalidClient errorType = "invalid_client"

	// InvalidGrant: The provided authorization grant (e.g., authorization code,
	// resource owner credentials) or refresh token is invalid, expired, revoked,
	// does not match the redirection URI used in the authorization request, or
	// was issued to another client.
	// RFC 6749 §5.2 (OAuth 2.0)
	InvalidGrant errorType = "invalid_grant"

	// UnauthorizedClient: The authenticated client is not authorized to use this
	// authorization grant type.
	// RFC 6749 §5.2 (OAuth 2.0)
	UnauthorizedClient errorType = "unauthorized_client"

	// UnsupportedGrantType: The authorization grant type is not supported by the
	// authorization server.
	// RFC 6749 §5.2 (OAuth 2.0)
	UnsupportedGrantType errorType = "unsupported_grant_type"

	// InvalidScope: The requested scope is invalid, unknown, malformed, or
	// exceeds the scope granted by the resource owner.
	// RFC 6749 §5.2 (OAuth 2.0)
	InvalidScope errorType = "invalid_scope"

	// ServerError: The authorization server encountered an unexpected condition
	// that prevented it from fulfilling the request.
	// RFC 6749 §5.2 (OAuth 2.0)
	ServerError errorType = "server_error"

	// TemporarilyUnavailable: The authorization server is currently unable to
	// handle the request due to a temporary overloading or maintenance of the
	// server. (This error code has no constructor — use the constant directly
	// when building an Error manually.)
	// RFC 6749 §5.2 (OAuth 2.0)
	TemporarilyUnavailable errorType = "temporarily_unavailable"

	// AccessDenied: The resource owner or authorization server denied the
	// request.
	// RFC 6749 §4.1.2.1 (OAuth 2.0) / RFC 8628 §3.5 (Device Auth)
	AccessDenied errorType = "access_denied"

	// UnsupportedResponseType: The authorization server does not support
	// obtaining an authorization code using this method.
	// RFC 6749 §4.1.2.1 (OAuth 2.0)
	UnsupportedResponseType errorType = "unsupported_response_type"

	// InteractionRequired: The Authorization Server requires End-User
	// interaction of some form to proceed.
	// OIDC Core 1.0 §3.1.2.6
	InteractionRequired errorType = "interaction_required"

	// LoginRequired: The Authorization Server requires End-User authentication.
	// OIDC Core 1.0 §3.1.2.6
	LoginRequired errorType = "login_required"

	// AccountSelectionRequired: The End-User is required to select a session at
	// the Authorization Server.
	// OIDC Core 1.0 §3.1.2.6
	AccountSelectionRequired errorType = "account_selection_required"

	// ConsentRequired: The Authorization Server requires End-User consent.
	// OIDC Core 1.0 §3.1.2.6
	ConsentRequired errorType = "consent_required"

	// RegistrationNotSupported: The OP does not support use of the
	// registration parameter.
	// OIDC Core 1.0 §3.1.2.6
	RegistrationNotSupported errorType = "registration_not_supported"

	// RequestNotSupported: The OP does not support use of the request parameter
	// defined in Section 6.
	// OIDC Core 1.0 §6.1
	RequestNotSupported errorType = "request_not_supported"

	// RequestURINotSupported: The OP does not support use of the request_uri
	// parameter defined in Section 6.3.
	// OIDC Core 1.0 §6.3
	RequestURINotSupported errorType = "request_uri_not_supported"

	// InvalidRequestObject: The request object is invalid, malformed,
	// has an invalid signature, or fails validation.
	// RFC 9101 §6.3 / OIDC Core §6.1
	InvalidRequestObject errorType = "invalid_request_object"

	// AuthorizationPending: The authorization request is still pending as the
	// end user hasn't yet completed the user-interaction steps.
	// RFC 8628 §3.5 (OAuth 2.0 Device Authorization Grant)
	AuthorizationPending errorType = "authorization_pending"

	// SlowDown: A variant of authorization_pending. The authorization request
	// is still pending and polling should continue, but the interval MUST be
	// increased by 5 seconds for this and all subsequent requests.
	// RFC 8628 §3.5 (OAuth 2.0 Device Authorization Grant)
	SlowDown errorType = "slow_down"

	// ExpiredToken: The device_code has expired and the device authorization
	// session has concluded.
	// RFC 8628 §3.5 (OAuth 2.0 Device Authorization Grant)
	ExpiredToken errorType = "expired_token"

	// InvalidBindingMessage: The binding_message is invalid or cannot be displayed.
	// CIBA Core 1.0 §7.1
	InvalidBindingMessage errorType = "invalid_binding_message"

	// InvalidTarget: The requested target resource is invalid, unknown, or
	// the audience parameter for the token being exchanged is not accepted.
	// RFC 8693 §2.2.2 (OAuth 2.0 Token Exchange)
	InvalidTarget errorType = "invalid_target"

	// InvalidClientMetadata: The value of one of the client metadata fields
	// is invalid or the server rejects this metadata for other reasons.
	// RFC 7591 §3.2.2
	InvalidClientMetadata errorType = "invalid_client_metadata"
)
View Source
const (
	BearerToken  = "Bearer"
	PrefixBearer = BearerToken + " "

	// BackChannelLogoutEventKey is the event key used in the "events" claim of a Logout Token.
	BackChannelLogoutEventKey = "http://schemas.openid.net/event/backchannel-logout"
)

BearerToken defines the token_type `Bearer`, which is returned in a successful token response.

View Source
const (
	JWEAlgDir          = "dir"            // Direct use of a shared symmetric key (RFC 7518 §4.5)
	JWEAlgRSAOAEP      = "RSA-OAEP"       // RSAES OAEP using default parameters (RFC 7518 §4.3)
	JWEAlgRSAOAEP256   = "RSA-OAEP-256"   // RSAES OAEP using SHA-256 (RFC 7518 §4.3)
	JWEAlgRSAOAEP384   = "RSA-OAEP-384"   // RSAES OAEP using SHA-384
	JWEAlgRSAOAEP512   = "RSA-OAEP-512"   // RSAES OAEP using SHA-512
	JWEAlgECDHES       = "ECDH-ES"        // ECDH-ES (RFC 7518 §4.6)
	JWEAlgECDHESA128KW = "ECDH-ES+A128KW" // ECDH-ES + A128KW (RFC 7518 §4.6)
	JWEAlgECDHESA192KW = "ECDH-ES+A192KW" // ECDH-ES + A192KW (RFC 7518 §4.6)
	JWEAlgECDHESA256KW = "ECDH-ES+A256KW" // ECDH-ES + A256KW (RFC 7518 §4.6)
	JWEAlgA128KW       = "A128KW"         // AES-128 Key Wrap (RFC 7518 §4.4)
	JWEAlgA192KW       = "A192KW"         // AES-192 Key Wrap (RFC 7518 §4.4)
	JWEAlgA256KW       = "A256KW"         // AES-256 Key Wrap (RFC 7518 §4.4)
	JWEAlgA128GCMKW    = "A128GCMKW"      // AES-128-GCM key wrapping (RFC 7518 §4.7)
	JWEAlgA192GCMKW    = "A192GCMKW"      // AES-192-GCM key wrapping (RFC 7518 §4.7)
	JWEAlgA256GCMKW    = "A256GCMKW"      // AES-256-GCM key wrapping (RFC 7518 §4.7)
	JWEAlgSM23         = "SGD_SM2_3"      // SM2 key wrapping per GM/T 0125.3
	JWEAlgSM93         = "SGD_SM9_3"      // SM9 identity-based key wrapping per GM/T 0125.3
)

JWE key wrapping algorithms supported by this package.

View Source
const (
	JWEEncA128CBC_HS256 = "A128CBC-HS256" // AES-128-CBC + HMAC-SHA256 (RFC 7518 §5.2.3)
	JWEEncA192CBC_HS384 = "A192CBC-HS384" // AES-192-CBC + HMAC-SHA384 (RFC 7518 §5.2.4)
	JWEEncA256CBC_HS512 = "A256CBC-HS512" // AES-256-CBC + HMAC-SHA512 (RFC 7518 §5.2.5)
	JWEEncA128GCM       = "A128GCM"       // AES-128-GCM content encryption (RFC 7518 §5.3)
	JWEEncA192GCM       = "A192GCM"       // AES-192-GCM content encryption (RFC 7518 §5.3)
	JWEEncA256GCM       = "A256GCM"       // AES-256-GCM content encryption (RFC 7518 §5.3)
	JWEEncSM4GCM        = "SGD_SM4_GCM"   // SM4-GCM content encryption per GM/T 0125.3
)

JWE content encryption algorithms supported by this package.

View Source
const (
	ClientAssertionTypeJWTAssertion = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
)
View Source
const DiscoveryEndpoint = "/.well-known/openid-configuration"
View Source
const KeyUseSignature = "sig"

KeyUseSignature is the JWK "use" value that indicates a key is intended for digital signatures.

Variables

View Source
var (
	// ErrParse indicates that parsing of the JWT or request failed.
	ErrParse = errors.New("parsing of request failed")

	// ErrIssuerInvalid indicates the token issuer does not match.
	ErrIssuerInvalid = errors.New("issuer does not match")

	// ErrDiscoveryFailed indicates OpenID Provider Configuration Discovery has failed.
	ErrDiscoveryFailed = errors.New("OpenID Provider Configuration Discovery has failed")

	// ErrSubjectMissing indicates the subject claim is missing from the token.
	ErrSubjectMissing = errors.New("subject missing")

	// ErrSubjectInvalid indicates delegation is not allowed:
	// issuer and sub must be identical for non-delegated tokens.
	ErrSubjectInvalid = errors.New("delegation not allowed, issuer and sub must be identical")

	// ErrAudience indicates the audience claim is not valid.
	ErrAudience = errors.New("audience is not valid")

	// ErrAzpMissing indicates azp (authorized party) is not set when the token
	// is valid for multiple audiences.
	ErrAzpMissing = errors.New("authorized party is not set. If Token is valid for multiple audiences, azp must not be empty")

	// ErrAzpInvalid indicates the authorized party is not valid.
	ErrAzpInvalid = errors.New("authorized party is not valid")

	// ErrSignatureMissing indicates the id_token does not contain a signature.
	ErrSignatureMissing = errors.New("id_token does not contain a signature")

	// ErrSignatureMultiple indicates the id_token contains multiple signatures.
	ErrSignatureMultiple = errors.New("id_token contains multiple signatures")

	// ErrSignatureUnsupportedAlg indicates the signature algorithm is not supported.
	ErrSignatureUnsupportedAlg = errors.New("signature algorithm not supported")

	// ErrSignatureInvalidPayload indicates the signature does not match the payload.
	ErrSignatureInvalidPayload = errors.New("signature does not match Payload")

	// ErrSignatureInvalid indicates an invalid signature.
	ErrSignatureInvalid = errors.New("invalid signature")

	// ErrExpired indicates the token has expired (exp claim).
	ErrExpired = errors.New("token has expired")

	// ErrIatMissing indicates the iat (issued-at) claim is missing.
	ErrIatMissing = errors.New("issuedAt of token is missing")

	// ErrIatInFuture indicates the iat claim is in the future.
	ErrIatInFuture = errors.New("issuedAt of token is in the future")

	// ErrIatToOld indicates the iat claim exceeds the maximum age.
	ErrIatToOld = errors.New("issuedAt of token is to old")

	// ErrNbfInFuture indicates the nbf claim is in the future.
	ErrNbfInFuture = errors.New("notBefore of token is in the future")

	// ErrNonceInvalid indicates the nonce claim does not match the expected value.
	ErrNonceInvalid = errors.New("nonce does not match")

	// ErrAcrInvalid indicates the acr (Authentication Context Class Reference)
	// claim does not satisfy the requested level.
	ErrAcrInvalid = errors.New("acr is invalid")

	// ErrAuthTimeNotPresent indicates the auth_time claim is missing from the token.
	ErrAuthTimeNotPresent = errors.New("claim `auth_time` of token is missing")

	// ErrAuthTimeToOld indicates the auth_time claim exceeds the maximum age.
	ErrAuthTimeToOld = errors.New("auth time of token is too old")

	// ErrAtHash indicates the at_hash claim does not correspond to the access token.
	ErrAtHash = errors.New("at_hash does not correspond to access token")

	// ErrKeyMultiple indicates multiple possible keys match for JWT verification.
	ErrKeyMultiple = errors.New("multiple possible keys match")

	// ErrKeyNone indicates no matching key was found for JWT verification.
	ErrKeyNone = errors.New("no possible keys matches")
)
View Source
var (
	ErrInvalidRequest = func() *Error {
		return &Error{ErrorType: InvalidRequest}
	}
	ErrInvalidRequestRedirectURI = func() *Error {
		return &Error{ErrorType: InvalidRequest, redirectDisabled: true}
	}
	ErrInvalidClient = func() *Error {
		return &Error{ErrorType: InvalidClient, httpStatusCode: 401}
	}
	ErrInvalidGrant = func() *Error {
		return &Error{ErrorType: InvalidGrant}
	}
	ErrUnauthorizedClient = func() *Error {
		return &Error{ErrorType: UnauthorizedClient}
	}
	ErrUnsupportedGrantType = func() *Error {
		return &Error{ErrorType: UnsupportedGrantType}
	}
	ErrInvalidScope = func() *Error {
		return &Error{ErrorType: InvalidScope}
	}
	ErrServerError = func() *Error {
		return &Error{ErrorType: ServerError}
	}

	ErrAccessDenied = func() *Error {
		return &Error{
			ErrorType:   AccessDenied,
			Description: "The authorization request was denied.",
		}
	}
	ErrUnsupportedResponseType = func() *Error {
		return &Error{ErrorType: UnsupportedResponseType}
	}

	ErrInteractionRequired = func() *Error {
		return &Error{ErrorType: InteractionRequired}
	}
	ErrLoginRequired = func() *Error {
		return &Error{ErrorType: LoginRequired}
	}
	ErrAccountSelectionRequired = func() *Error {
		return &Error{ErrorType: AccountSelectionRequired}
	}
	ErrConsentRequired = func() *Error {
		return &Error{ErrorType: ConsentRequired}
	}
	ErrRegistrationNotSupported = func() *Error {
		return &Error{ErrorType: RegistrationNotSupported}
	}

	ErrRequestNotSupported = func() *Error {
		return &Error{ErrorType: RequestNotSupported}
	}

	ErrRequestURINotSupported = func() *Error {
		return &Error{ErrorType: RequestURINotSupported}
	}

	ErrInvalidRequestObject = func() *Error {
		return &Error{ErrorType: InvalidRequestObject}
	}

	ErrAuthorizationPending = func() *Error {
		return &Error{
			ErrorType:   AuthorizationPending,
			Description: "The client SHOULD repeat the access token request to the token endpoint, after interval from device authorization response.",
		}
	}
	ErrSlowDown = func() *Error {
		return &Error{
			ErrorType:   SlowDown,
			Description: "Polling should continue, but the interval MUST be increased by 5 seconds for this and all subsequent requests.",
		}
	}
	ErrExpiredDeviceCode = func() *Error {
		return &Error{
			ErrorType:   ExpiredToken,
			Description: "The \"device_code\" has expired.",
		}
	}
	ErrInvalidBindingMessage = func() *Error {
		return &Error{
			ErrorType:   InvalidBindingMessage,
			Description: "The binding_message is invalid or cannot be displayed.",
		}
	}

	ErrInvalidTarget = func() *Error {
		return &Error{
			ErrorType:   InvalidTarget,
			Description: "The requested audience or target is invalid.",
		}
	}

	ErrInvalidClientMetadata = func() *Error {
		return &Error{ErrorType: InvalidClientMetadata}
	}
)
View Source
var ErrInvalidRefreshToken = errors.New("invalid refresh token")
View Source
var ErrNilEndpoint = errors.New("nil endpoint")
View Source
var KnownDiscoveryKeys map[string]bool

KnownDiscoveryKeys contains all JSON field names from DiscoveryConfiguration struct tags. This is auto-generated via reflection and can be used to filter discovery fields.

Functions

func AppendClientIDToAudience

func AppendClientIDToAudience(clientID string, audience []string) []string

AppendClientIDToAudience appends the clientID to the audience if not already present.

func CheckAZPVerifier

func CheckAZPVerifier(claims Claims, azp AZPVerifier) error

CheckAZPVerifier checks azp (authorized party) claim requirements.

If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present. If an azp Claim is present, the Client MAY verify that its client_id is the Claim Value. https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation

func CheckAudience

func CheckAudience(claims Claims, expected string) error

CheckAudience checks that the audience contains the expected value.

func CheckAudienceAny

func CheckAudienceAny(claims Claims, allowed []string) error

CheckAudienceAny checks that the audience contains at least one of the allowed values. For ID Token validation, pass a single client_id. For client_assertion validation, pass both the issuer and token endpoint URL.

func CheckAuthTime

func CheckAuthTime(claims Claims, maxAge time.Duration) error

func CheckAuthorizationContextClassReference

func CheckAuthorizationContextClassReference(claims Claims, acr ACRVerifier) error

func CheckAuthorizedParty

func CheckAuthorizedParty(claims Claims, clientID string) error

CheckAuthorizedParty checks azp (authorized party) claim requirements.

If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present. If an azp Claim is present, the Client MAY verify that its client_id is the Claim Value. https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation

func CheckExpiration

func CheckExpiration(claims Claims, offset time.Duration) error

func CheckIssuedAt

func CheckIssuedAt(claims Claims, maxAgeIAT, offset time.Duration) error

func CheckIssuer

func CheckIssuer(claims Claims, issuer string) error

func CheckNonce

func CheckNonce(claims Claims, nonce string) error

func CheckSignature

func CheckSignature(ctx context.Context, token string, payload []byte, claims ClaimsSignature, supportedSigAlgs []string, set KeySet) error

func CheckSignatureWithKeyStore

func CheckSignatureWithKeyStore(ctx context.Context, token string, payload []byte, claims ClaimsSignature, supportedSigAlgs []string, store KeyStore) error

CheckSignatureWithKeyStore verifies a JWT signature using a KeyStore. It adapts the KeyStore to a KeySet internally and delegates to CheckSignature.

func CheckSubject

func CheckSubject(claims Claims) error

func ClaimHash

func ClaimHash(claim string, sigAlgorithm string) (string, error)

ClaimHash computes the hash of a claim value using the specified signature algorithm.

func ContextWithIssuer

func ContextWithIssuer(ctx context.Context, issuer string) context.Context

func DecryptToken

func DecryptToken(tokenString string) (string, error)

DecryptToken detects whether tokenString is a JWE (5-part compact serialization) or a plain JWS/signed token. If it is a JWE, decryption needs a key which must be provided via context. If no key is available and the token is JWE, an error is returned.

For OP-side decryption (access tokens), use the Crypto interface. For RP-side decryption (ID tokens), pass a Decrypter via the verifier options.

func DecryptTokenJWE

func DecryptTokenJWE(compact string, key interface{}) ([]byte, error)

DecryptTokenJWE decrypts a JWE compact serialization. All algorithms dispatch through the crypto package for unified HSM/KMS support.

func DecryptTokenWithKey

func DecryptTokenWithKey(tokenString string, key []byte) (string, error)

DecryptTokenWithKey is like DecryptToken but uses the provided key for decryption.

func EncryptToken

func EncryptToken(signedToken string, key []byte) (string, error)

EncryptToken wraps a signed JWT (3-part) in JWE "dir" mode using SM4-GCM. This is used by the OP to optionally encrypt ID tokens before returning them. For AES-GCM, use EncryptTokenA256GCM or EncryptTokenA128GCM.

func EncryptTokenA128GCM

func EncryptTokenA128GCM(signedToken string, key []byte) (string, error)

EncryptTokenA128GCM wraps a signed JWT in JWE "dir" mode using AES-128-GCM.

func EncryptTokenA256GCM

func EncryptTokenA256GCM(signedToken string, key []byte) (string, error)

EncryptTokenA256GCM wraps a signed JWT in JWE "dir" mode using AES-256-GCM.

func EncryptTokenJWE

func EncryptTokenJWE(signedToken string, key interface{}, alg, enc string) (string, error)

EncryptTokenJWE encrypts a signed JWT using the specified JWE algorithm. All algorithms dispatch through the crypto package for unified HSM/KMS support.

func EncryptTokenSM2

func EncryptTokenSM2(signedToken string, publicKey interface{}) (string, error)

EncryptTokenSM2 wraps a signed JWT in JWE using SM2 public-key encryption (SGD_SM2_3 key wrapping with SGD_SM4_GCM content encryption) per GM/T 0125.3. The publicKey is the recipient's SM2 public key (typically the RP's SM2 key).

func EncryptTokenSM9

func EncryptTokenSM9(signedToken string, sm9Key SM9EncryptKey) (string, error)

EncryptTokenSM9 wraps a signed JWT in JWE using SM9 identity-based encryption (SGD_SM9_3 key wrapping with SGD_SM4_GCM content encryption) per GM/T 0125.3. sm9Key is an SM9EncryptKey that provides the master public key and UID.

func FindMatchingKey

func FindMatchingKey(keyID, use, expectedAlg string, keys ...jwk.Key) (key jwk.Key, err error)

FindMatchingKey searches the given JSON Web Keys for the requested key ID, usage and alg type.

It returns the key immediately on an exact (id, usage, type) match.

It returns a specific error if none (ErrKeyNone) or multiple (ErrKeyMultiple) match.

func GenerateJWTProfileToken

func GenerateJWTProfileToken(assertion *JWTProfileAssertionClaims) (string, error)

GenerateJWTProfileToken signs and returns a JWT from the given assertion claims.

func GetKeyIDAndAlg

func GetKeyIDAndAlg(jwsMsg *jws.Message) (string, string)

GetKeyIDAndAlg returns the `kid` and `alg` claim from the JWS header.

func HasEssentialClaim

func HasEssentialClaim(claims map[string]*ClaimRequest, name string) bool

HasEssentialClaim checks if a claim is requested as essential in the given claims map.

func IsClaimRequested

func IsClaimRequested(claims map[string]*ClaimRequest, name string) bool

IsClaimRequested checks if a claim is requested (either essential or voluntary) in the claims map.

func IssuerFromContext

func IssuerFromContext(ctx context.Context) string

func JWTProfileCustomClaim

func JWTProfileCustomClaim(key string, value any) func(*JWTProfileAssertionClaims)

JWTProfileCustomClaim adds a custom claim to the JWT Profile assertion.

func JWTProfileDelegatedSubject

func JWTProfileDelegatedSubject(sub string) func(*JWTProfileAssertionClaims)

JWTProfileDelegatedSubject sets the subject of the JWT Profile assertion to a delegated user.

func NewJWTProfileAssertionStringFromFileData

func NewJWTProfileAssertionStringFromFileData(data []byte, audience []string, opts ...AssertionOption) (string, error)

NewJWTProfileAssertionStringFromFileData creates a signed JWT Profile assertion string from JSON key data.

func NewSHACodeChallenge

func NewSHACodeChallenge(code string) string

func ParseToken

func ParseToken(tokenString string, claims any) ([]byte, error)

func VerifyAccessToken

func VerifyAccessToken(ctx context.Context, token string, v *AccessTokenVerifier) (tokenID, subject string, ok bool)

func VerifyAccessTokenGeneric

func VerifyAccessTokenGeneric[C Claims](ctx context.Context, token string, v *AccessTokenVerifier) (claims C, err error)

VerifyAccessTokenGeneric validates the access token and returns typed claims.

func VerifyCodeChallenge

func VerifyCodeChallenge(c *CodeChallenge, codeVerifier string) bool

func VerifyIDTokenHintGeneric

func VerifyIDTokenHintGeneric[C Claims](ctx context.Context, token string, v *IDTokenHintVerifier) (claims C, err error)

VerifyIDTokenHintGeneric validates the ID token hint and returns typed claims.

func VerifyJWTAssertion

func VerifyJWTAssertion(ctx context.Context, assertion string, allowedAudiences []string, keys []jwk.Key, offset time.Duration) error

VerifyJWTAssertion verifies a JWT client assertion per RFC 7523 §2.2 / OIDC Core §9. For private_key_jwt / client_secret_jwt, pass the client's registered public keys. allowedAudiences contains the accepted aud values (typically the issuer and/or token endpoint URL).

func VerifySignature

func VerifySignature(ctx context.Context, jwsMsg *jws.Message, rawToken []byte, key jwk.Key, alg string) ([]byte, error)

func VerifySignatureWithRegistry

func VerifySignatureWithRegistry(ctx context.Context, jwsMsg *jws.Message, rawToken []byte, key jwk.Key, alg string) ([]byte, error)

VerifySignatureWithRegistry verifies a JWS signature by dispatching to the crypto provider registry. If a VerifyProvider is registered for the algorithm, it is used. Otherwise, jwx's built-in verification is used as fallback.

This function is the central dispatch point for all JWS signature verification in the protocol layer. It replaces the previous hard-coded sm2Verifier in registry.go.

Types

type ACRVerifier

type ACRVerifier func(string) error

ACRVerifier specifies the function to be used by the `DefaultVerifier` for validating the acr claim

func DefaultACRVerifier

func DefaultACRVerifier(possibleValues []string) ACRVerifier

DefaultACRVerifier implements `ACRVerifier` returning an error if none of the provided values matches the acr claim

type AZPVerifier

type AZPVerifier func(string) error

AZPVerifier specifies the function to be used by the `DefaultVerifier` for validating the azp claim

func DefaultAZPVerifier

func DefaultAZPVerifier(clientID string) AZPVerifier

DefaultAZPVerifier implements `AZPVerifier` returning an error if the azp claim is set and doesn't match the clientID.

type AccessTokenClaims

type AccessTokenClaims struct {
	TokenClaims
	Scopes SpaceDelimitedArray `json:"scope,omitempty"`
	Claims map[string]any      `json:"-"`
}

AccessTokenClaims extends TokenClaims for OAuth 2.0 Access Tokens per RFC 9068. https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure

func NewAccessTokenClaims

func NewAccessTokenClaims(issuer, subject string, audience []string, expiration time.Time, jwtid, clientID string, skew time.Duration) *AccessTokenClaims

NewAccessTokenClaims creates a new AccessTokenClaims with the given parameters.

func (*AccessTokenClaims) MarshalJSON

func (a *AccessTokenClaims) MarshalJSON() ([]byte, error)

func (*AccessTokenClaims) UnmarshalJSON

func (a *AccessTokenClaims) UnmarshalJSON(data []byte) error

type AccessTokenRequest

type AccessTokenRequest struct {
	GrantType            string               `schema:"grant_type,omitempty"`
	Code                 string               `schema:"code"`
	RedirectURI          string               `schema:"redirect_uri"`
	ClientID             string               `schema:"client_id"`
	ClientSecret         string               `schema:"client_secret,omitempty"`
	CodeVerifier         string               `schema:"code_verifier,omitempty"`
	ClientAssertion      string               `schema:"client_assertion,omitempty"`
	ClientAssertionType  string               `schema:"client_assertion_type,omitempty"`
	Resource             Audience             `schema:"resource"`
	AuthorizationDetails AuthorizationDetails `schema:"authorization_details"`
}

func (*AccessTokenRequest) SetClientID

func (a *AccessTokenRequest) SetClientID(clientID string)

func (*AccessTokenRequest) SetClientSecret

func (a *AccessTokenRequest) SetClientSecret(clientSecret string)

type AccessTokenResponse

type AccessTokenResponse struct {
	AccessToken  string              `json:"access_token,omitempty" schema:"access_token,omitempty"`
	TokenType    string              `json:"token_type,omitempty" schema:"token_type,omitempty"`
	RefreshToken string              `json:"refresh_token,omitempty" schema:"refresh_token,omitempty"`
	ExpiresIn    uint64              `json:"expires_in,omitempty" schema:"expires_in,omitempty"`
	IDToken      string              `json:"id_token,omitempty" schema:"id_token,omitempty"`
	State        string              `json:"state,omitempty" schema:"state,omitempty"`
	Scope        SpaceDelimitedArray `json:"scope,omitempty" schema:"scope,omitempty"`
}

AccessTokenResponse represents a successful OAuth 2.0 token response. https://datatracker.ietf.org/doc/html/rfc6749#section-5.1

type AccessTokenVerifier

type AccessTokenVerifier struct {
	Issuer            string
	KeySet            KeySet
	KeyStore          KeyStore // optional, used for JWKS-based verification
	Offset            time.Duration
	SupportedSignAlgs []string
	MaxAgeIAT         time.Duration
}

func NewAccessTokenVerifier

func NewAccessTokenVerifier(issuer string, keySet KeySet, opts ...AccessTokenVerifierOpt) *AccessTokenVerifier

type AccessTokenVerifierOpt

type AccessTokenVerifierOpt func(*AccessTokenVerifier)

func WithSupportedAccessTokenSigningAlgorithms

func WithSupportedAccessTokenSigningAlgorithms(algs ...string) AccessTokenVerifierOpt

type ActorClaims

type ActorClaims struct {
	Actor   *ActorClaims   `json:"act,omitempty"`
	Issuer  string         `json:"iss,omitempty"`
	Subject string         `json:"sub,omitempty"`
	Claims  map[string]any `json:"-"`
}

ActorClaims provides the `act` claims used for impersonation or delegation Token Exchange.

An actor can be nested in case an obtained token is used as actor token to obtain impersonation or delegation. This allows creating a chain of actors. See [RFC 8693, section 4.1](https://www.rfc-editor.org/rfc/rfc8693#name-act-actor-claim).

func (*ActorClaims) MarshalJSON

func (c *ActorClaims) MarshalJSON() ([]byte, error)

func (*ActorClaims) UnmarshalJSON

func (c *ActorClaims) UnmarshalJSON(data []byte) error

type AssertionOption

type AssertionOption func(*JWTProfileAssertionClaims)

AssertionOption is a functional option for configuring JWTProfileAssertionClaims.

type Audience

type Audience []string

func (*Audience) UnmarshalJSON

func (a *Audience) UnmarshalJSON(text []byte) error

type AuthMethod

type AuthMethod string
const (
	AuthMethodBasic             AuthMethod = "client_secret_basic"
	AuthMethodPost              AuthMethod = "client_secret_post"
	AuthMethodNone              AuthMethod = "none"
	AuthMethodPrivateKeyJWT     AuthMethod = "private_key_jwt"
	AuthMethodTLSClientAuth     AuthMethod = "tls_client_auth"             // RFC 8705 §2
	AuthMethodSelfSignedTLSAuth AuthMethod = "self_signed_tls_client_auth" // RFC 8705 §2
)

type AuthRequest

type AuthRequest struct {
	Scopes       SpaceDelimitedArray `json:"scope" schema:"scope"`
	ResponseType ResponseType        `json:"response_type" schema:"response_type"`
	ClientID     string              `json:"client_id" schema:"client_id"`
	RedirectURI  string              `json:"redirect_uri" schema:"redirect_uri"`

	State string `json:"state" schema:"state"`
	Nonce string `json:"nonce" schema:"nonce"`

	ResponseMode  ResponseMode        `json:"response_mode" schema:"response_mode"`
	Display       Display             `json:"display" schema:"display"`
	Prompt        SpaceDelimitedArray `json:"prompt" schema:"prompt"`
	MaxAge        *uint               `json:"max_age" schema:"max_age"`
	UILocales     Locales             `json:"ui_locales" schema:"ui_locales"`
	ClaimsLocales Locales             `json:"claims_locales" schema:"claims_locales"`
	IDTokenHint   string              `json:"id_token_hint" schema:"id_token_hint"`
	LoginHint     string              `json:"login_hint" schema:"login_hint"`
	ACRValues     SpaceDelimitedArray `json:"acr_values" schema:"acr_values"`

	CodeChallenge       string              `json:"code_challenge" schema:"code_challenge"`
	CodeChallengeMethod CodeChallengeMethod `json:"code_challenge_method" schema:"code_challenge_method"`

	RequestParam string         `json:"request,omitempty" schema:"request"`
	RequestURI   string         `json:"request_uri,omitempty" schema:"request_uri"`
	Claims       *ClaimsRequest `json:"claims" schema:"claims"`

	// DPoP JWK Thumbprint for authorization code binding (RFC 9449 §7.1).
	// When present, the token endpoint must verify the DPoP proof matches this thumbprint.
	DPoPJKT string `json:"dpop_jkt" schema:"dpop_jkt"`

	// Resource Indicators (RFC 8707 §2).
	// One or more resource server URIs that the client is requesting access to.
	// The authorization server SHOULD populate the "aud" claim of the access token
	// with these values when issuing JWT access tokens.
	Resource Audience `json:"resource" schema:"resource"`

	// Rich Authorization Requests (RFC 9396 §2).
	// Structured authorization details that express fine-grained access requirements.
	AuthorizationDetails AuthorizationDetails `json:"authorization_details" schema:"authorization_details"`
}

AuthRequest according to: https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest

func (*AuthRequest) GetRedirectURI

func (a *AuthRequest) GetRedirectURI() string

func (*AuthRequest) GetResponseMode

func (a *AuthRequest) GetResponseMode() ResponseMode

func (*AuthRequest) GetResponseType

func (a *AuthRequest) GetResponseType() ResponseType

func (*AuthRequest) GetState

func (a *AuthRequest) GetState() string

func (*AuthRequest) LogValue

func (a *AuthRequest) LogValue() slog.Value

type AuthenticationMethodsReferences

type AuthenticationMethodsReferences []string

func (*AuthenticationMethodsReferences) UnmarshalJSON

func (a *AuthenticationMethodsReferences) UnmarshalJSON(data []byte) error

type AuthorizationDetail

type AuthorizationDetail struct {
	// REQUIRED. Type of the authorization details (e.g., "payment_initiation").
	Type string `json:"type"`

	// OPTIONAL. Array of strings representing the locations of the resource servers.
	Locations Audience `json:"locations,omitempty"`

	// OPTIONAL. Array of strings representing the actions the client intends to perform.
	Actions []string `json:"actions,omitempty"`

	// OPTIONAL. Array of strings representing the kinds of data being processed.
	DataTypes []string `json:"datatypes,omitempty"`

	// OPTIONAL. Identifier string for a specific resource instance.
	Identifier string `json:"identifier,omitempty"`

	// OPTIONAL. Array of strings representing the privileges conferred on the client.
	Privileges []string `json:"privileges,omitempty"`
}

AuthorizationDetail represents a single authorization detail element. RFC 9396 §2 — Authorization Details Type https://datatracker.ietf.org/doc/html/rfc9396#section-2

type AuthorizationDetails

type AuthorizationDetails []AuthorizationDetail

AuthorizationDetails represents a single element in the authorization_details array. RFC 9396 §2 — Authorization Details https://datatracker.ietf.org/doc/html/rfc9396#section-2

func (*AuthorizationDetails) UnmarshalText

func (ad *AuthorizationDetails) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler so the form decoder can parse the JSON-encoded authorization_details field from OAuth requests.

type BackchannelAuthRequest

type BackchannelAuthRequest struct {
	Scope                   string   `json:"scope"                schema:"scope"`
	ClientNotificationToken string   `json:"client_notification_token,omitempty" schema:"client_notification_token"`
	LoginHintToken          string   `json:"login_hint_token,omitempty"       schema:"login_hint_token"`
	IDTokenHint             string   `json:"id_token_hint,omitempty"          schema:"id_token_hint"`
	LoginHint               string   `json:"login_hint,omitempty"             schema:"login_hint"`
	BindingMessage          string   `json:"binding_message,omitempty"        schema:"binding_message"`
	UserCode                string   `json:"user_code,omitempty"              schema:"user_code"`
	RequestedExpiry         FlexInt  `json:"requested_expiry,omitempty"       schema:"requested_expiry"`
	AcrValues               string   `json:"acr_values,omitempty"             schema:"acr_values"`
	Claims                  string   `json:"claims,omitempty"                 schema:"claims"`
	Resources               Audience `json:"resource,omitempty"               schema:"resource"`
}

BackchannelAuthRequest represents the request parameters for the Backchannel Authentication Endpoint (POST /bc-authorize).

OpenID Connect Client-Initiated Backchannel Authentication Core 1.0 §7 https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#section-7

type BackchannelAuthResponse

type BackchannelAuthResponse struct {
	AuthReqID string `json:"auth_req_id"`
	ExpiresIn int    `json:"expires_in"`
	Interval  int    `json:"interval,omitempty"`
}

BackchannelAuthResponse represents the response from the Backchannel Authentication Endpoint (POST /bc-authorize).

CIBA Core 1.0 §7.1.2 https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#section-7.1.2

func NewBackchannelAuthResponse

func NewBackchannelAuthResponse(authReqID string, expiresIn int, interval int) *BackchannelAuthResponse

NewBackchannelAuthResponse creates a new BackchannelAuthResponse with the given parameters.

type BackchannelTokenRequest

type BackchannelTokenRequest struct {
	GrantType           string `json:"grant_type"            schema:"grant_type"`
	AuthReqID           string `json:"auth_req_id"           schema:"auth_req_id"`
	ClientAssertionType string `json:"client_assertion_type" schema:"client_assertion_type"`
	ClientAssertion     string `json:"client_assertion"      schema:"client_assertion"`
}

BackchannelTokenRequest extends AccessTokenRequest with CIBA-specific fields.

CIBA Core 1.0 §8.1 https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#section-8.1

type Bool

type Bool bool

Bool handles both standard JSON booleans and string representations ("true"/"false"). This is necessary because some OIDC providers (notably AWS Cognito) incorrectly return boolean fields like email_verified and phone_number_verified as strings ("true"/"false") instead of proper JSON booleans, violating the OIDC specification.

Ref: - https://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims - https://docs.aws.amazon.com/cognito/latest/developerguide/userinfo-endpoint.html

func (*Bool) UnmarshalJSON

func (b *Bool) UnmarshalJSON(data []byte) error

UnmarshalJSON handles both standard JSON boolean values and string representations. This is necessary because some OIDC providers (notably AWS Cognito) incorrectly return boolean fields like email_verified and phone_number_verified as strings ("true"/"false") instead of proper JSON booleans, violating the OIDC specification.

The method first attempts standard boolean unmarshaling, and falls back to string parsing if that fails, making it compatible with both compliant and non-compliant providers.

Ref: - https://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims - https://docs.aws.amazon.com/cognito/latest/developerguide/userinfo-endpoint.html

type CIBAAuthRequestInfo

type CIBAAuthRequestInfo struct {
	AuthReqID      string    `json:"auth_req_id"`
	ClientID       string    `json:"client_id"`
	Scope          string    `json:"scope"`
	BindingMessage string    `json:"binding_message,omitempty"`
	UserCode       string    `json:"user_code,omitempty"`
	ExpiresAt      time.Time `json:"expires_at"`
}

CIBAAuthRequestInfo contains information about a pending CIBA request to display on the approval page.

type CIBADeliveryMode

type CIBADeliveryMode string

CIBADeliveryMode defines how the CIBA response is delivered to the client.

CIBA Core 1.0 §5 https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#section-5

const (
	// CIBAModePing: OP notifies the client via an HTTP POST to its
	// client_notification_endpoint when the authentication is complete.
	CIBAModePing CIBADeliveryMode = "ping"

	// CIBAModePoll: client polls the token endpoint to check completion.
	// This is the default if the client does not provide a notification endpoint.
	CIBAModePoll CIBADeliveryMode = "poll"
)

type CIBAPollResponse

type CIBAPollResponse struct {
	Error            string `json:"error"`
	ErrorDescription string `json:"error_description,omitempty"`
}

CIBAPollResponse is returned when the token endpoint receives a poll request but the authentication is not yet complete.

CIBA Core 1.0 §8.2 https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#section-8.2

type CIBARequestObject

type CIBARequestObject struct {
	Issuer    string   `json:"iss"`
	Audience  Audience `json:"aud"`
	ExpiresAt int64    `json:"exp,omitempty"`
	NotBefore int64    `json:"nbf,omitempty"`
	IssuedAt  int64    `json:"iat,omitempty"`
	JTI       string   `json:"jti,omitempty"`
	BackchannelAuthRequest
}

CIBARequestObject represents a signed CIBA authentication request (CIBA Core 1.0 §4). It embeds the standard JWT claims and the CIBA-specific request parameters.

func (*CIBARequestObject) GetIssuer

func (r *CIBARequestObject) GetIssuer() string

func (*CIBARequestObject) SetSignatureAlgorithm

func (*CIBARequestObject) SetSignatureAlgorithm(algorithm string)

type CIBAStatus

type CIBAStatus string

CIBAStatus represents the status of a CIBA authentication request.

const (
	CIBAStatusPending  CIBAStatus = "pending"
	CIBAStatusApproved CIBAStatus = "approved"
	CIBAStatusDenied   CIBAStatus = "denied"
	CIBAStatusConsumed CIBAStatus = "consumed" // Token already issued; auth_req_id cannot be reused.
)

type CertificateProvider

type CertificateProvider interface {
	// CertificateChain returns the DER-encoded X.509 certificate chain for this key.
	// The first element is the end-entity certificate.
	// Returns nil if no certificate is associated with this key.
	CertificateChain() ([][]byte, error)
}

CertificateProvider is an optional extension of Key for X.509 certificate chain support. OP implementations can satisfy this interface to include x5c/x5t/x5u fields in JWKS.

Usage in JWKS endpoint:

if cp, ok := key.(protocol.CertificateProvider); ok {
    certs, err := cp.CertificateChain()
    if err == nil && len(certs) > 0 {
        jwkKey.Set(jwk.X509CertChainKey, certs)
    }
}

type ClaimRequest

type ClaimRequest struct {
	Essential bool  `json:"essential,omitempty"`
	Value     any   `json:"value,omitempty"`
	Values    []any `json:"values,omitempty"`
}

ClaimRequest represents a single claim request specification. OIDC Core 1.0 §5.5 — Individual Claims Request

https://openid.net/specs/openid-connect-core-1_0.html#IndividualClaimsRequest

type Claims

type Claims interface {
	GetIssuer() string
	GetSubject() string
	GetAudience() []string
	GetExpiration() time.Time
	GetIssuedAt() time.Time
	GetNonce() string
	GetAuthenticationContextClassReference() string
	GetAuthTime() time.Time
	GetAuthorizedParty() string
	ClaimsSignature
}

type ClaimsRequest

type ClaimsRequest struct {
	IDToken  map[string]*ClaimRequest `json:"id_token,omitempty"`
	UserInfo map[string]*ClaimRequest `json:"userinfo,omitempty"`
}

OIDC Core 1.0 §5.5 — Claims Request Parameter

https://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter

The claims parameter value is a JSON object with two top-level members:

"id_token" and "userinfo", each being a JSON object mapping claim names
to either null or a ClaimRequest object.

type ClaimsSignature

type ClaimsSignature interface {
	SetSignatureAlgorithm(algorithm string)
}

type ClientAssertionParams

type ClientAssertionParams struct {
	ClientAssertion     string `schema:"client_assertion"`
	ClientAssertionType string `schema:"client_assertion_type"`
}

type ClientCredentialsRequest

type ClientCredentialsRequest struct {
	GrantType            GrantType            `schema:"grant_type,omitempty"`
	Scope                SpaceDelimitedArray  `schema:"scope"`
	ClientID             string               `schema:"client_id"`
	ClientSecret         string               `schema:"client_secret"`
	ClientAssertion      string               `schema:"client_assertion,omitempty"`
	ClientAssertionType  string               `schema:"client_assertion_type,omitempty"`
	Resource             Audience             `schema:"resource"`
	AuthorizationDetails AuthorizationDetails `schema:"authorization_details"`
}

func (*ClientCredentialsRequest) Auth

func (r *ClientCredentialsRequest) Auth(req *http.Request)

type CodeChallenge

type CodeChallenge struct {
	Challenge string
	Method    CodeChallengeMethod
}

type CodeChallengeMethod

type CodeChallengeMethod string
const (
	CodeChallengeMethodPlain CodeChallengeMethod = "plain"
	CodeChallengeMethodS256  CodeChallengeMethod = "S256"
)

type DecodeOption

type DecodeOption func(*decodeConfig)

DecodeOption configures per-decode behavior.

func WithIgnoreUnknownKeys

func WithIgnoreUnknownKeys() DecodeOption

WithIgnoreUnknownKeys returns a DecodeOption that causes the decoder to skip keys that do not match any exported field with a "schema" tag. Use this when the source map may contain fields not in the target struct (e.g., client authentication fields in PAR requests).

type Decoder

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

Decoder decodes url.Values into structs using "schema" struct tags. It replaces the former github.com/zitadel/schema.Decoder dependency.

func NewDecoder

func NewDecoder() *Decoder

NewDecoder returns a Decoder that knows how to decode SpaceDelimitedArray and Locales values from url.Values.

func (*Decoder) Decode

func (d *Decoder) Decode(dst any, src map[string][]string, opts ...DecodeOption) error

Decode decodes src (map[string][]string) into dst (struct pointer). It reads "schema" struct tags for field names. Custom types implementing encoding.TextUnmarshaler are supported.

Options can be passed to override per-decode behavior:

decoder.Decode(authReq, r.Form, protocol.WithIgnoreUnknownKeys())

func (*Decoder) RegisterParser

func (d *Decoder) RegisterParser(rt reflect.Type, parser func(string) (reflect.Value, error))

RegisterParser registers a custom string parser for a specific reflect.Type. It is used by StormEngine plugins to handle non-standard field types.

type DeviceAccessTokenRequest

type DeviceAccessTokenRequest struct {
	GrantType  GrantType `json:"grant_type" schema:"grant_type"`
	DeviceCode string    `json:"device_code" schema:"device_code"`
}

DeviceAccessTokenRequest implements RFC 8628 §3.4 Device Access Token Request.

type DeviceAuthorizationRequest

type DeviceAuthorizationRequest struct {
	Scopes   SpaceDelimitedArray `schema:"scope"`
	ClientID string              `schema:"client_id"`
}

DeviceAuthorizationRequest implements RFC 8628 §3.1 Device Authorization Request.

type DeviceAuthorizationResponse

type DeviceAuthorizationResponse struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
	ExpiresIn               int    `json:"expires_in"`
	Interval                int    `json:"interval,omitempty"`
}

DeviceAuthorizationResponse implements RFC 8628 §3.2 Device Authorization Response.

func (*DeviceAuthorizationResponse) UnmarshalJSON

func (resp *DeviceAuthorizationResponse) UnmarshalJSON(data []byte) error

type DiscoveryConfiguration

type DiscoveryConfiguration struct {
	// REQUIRED. issuer is the URL of the OP, used as iss claim in tokens.
	// OIDC Discovery 1.0 §3.1
	Issuer string `json:"issuer"`

	// REQUIRED. Authorization Endpoint URL (OAuth 2.0 Authorization Endpoint).
	// Used for all interactive login flows.
	// OIDC Discovery 1.0 §3.2
	AuthorizationEndpoint string `json:"authorization_endpoint,omitempty"`

	// REQUIRED. Token Endpoint URL (OAuth 2.0 Token Endpoint).
	// Used by all grant types to obtain tokens.
	// OIDC Discovery 1.0 §3.3
	TokenEndpoint string `json:"token_endpoint,omitempty"`

	// RECOMMENDED. UserInfo Endpoint URL.
	// Returns claims about the authenticated End-User.
	// OIDC Core 1.0 §5.3 / OIDC Discovery 1.0 §3.4
	UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`

	// REQUIRED. JWKS URI containing the OP's public keys for token signature verification.
	// OIDC Discovery 1.0 §3.5 / OIDC Core 1.0 §7.3
	JWKSURI string `json:"jwks_uri,omitempty"`

	// RECOMMENDED. Dynamic Client Registration Endpoint (RFC 7591).
	// OIDC Discovery 1.0 §3.6
	RegistrationEndpoint string `json:"registration_endpoint,omitempty"`

	// End Session Endpoint URL for RP-Initiated Logout.
	// OIDC Session Management §5 / OIDC RP-Initiated Logout §2
	EndSessionEndpoint string `json:"end_session_endpoint,omitempty"`

	// Check Session iframe URL for OP-initiated session state monitoring.
	// OIDC Session Management §4
	CheckSessionIframe string `json:"check_session_iframe,omitempty"`

	// Back-Channel Logout Endpoint URI to receive logout tokens.
	// OIDC Back-Channel Logout §2.5
	BackChannelLogoutEndpoint string `json:"backchannel_logout_endpoint,omitempty"`

	// OPTIONAL. Whether the OP supports session IDs in back-channel logout tokens.
	// OIDC Back-Channel Logout §2.5
	BackChannelLogoutSessionSupported bool `json:"backchannel_logout_session_supported,omitempty"`

	// OPTIONAL. Whether the OP supports back-channel logout.
	// OIDC Back-Channel Logout §2.5
	BackChannelLogoutSupported bool `json:"backchannel_logout_supported,omitempty"`

	// Front-Channel Logout Endpoint URL via user-agent redirect.
	// OIDC Front-Channel Logout §3
	FrontChannelLogoutEndpoint string `json:"frontchannel_logout_endpoint,omitempty"`

	// OPTIONAL. Whether the OP supports session IDs in front-channel logout.
	// OIDC Front-Channel Logout §3
	FrontChannelLogoutSessionSupported bool `json:"frontchannel_logout_session_supported,omitempty"`

	// OPTIONAL. Whether the OP supports front-channel logout.
	// OIDC Front-Channel Logout §3
	FrontChannelLogoutSupported bool `json:"frontchannel_logout_supported,omitempty"`

	// Token Exchange Endpoint URL for cross-domain and delegation token exchange.
	// RFC 8693 §4 (OAuth 2.0 Token Exchange)
	TokenExchangeEndpoint string `json:"token_exchange_endpoint,omitempty"`

	// Device Authorization Endpoint URL for browserless and input-constrained devices.
	// RFC 8628 §4 (OAuth 2.0 Device Authorization Grant)
	DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"`

	// Backchannel Authentication Endpoint URL for Client-Initiated Backchannel Authentication.
	// CIBA Core 1.0 §4 (OpenID Connect Client-Initiated Backchannel Authentication)
	BackchannelAuthenticationEndpoint string `json:"backchannel_authentication_endpoint,omitempty"`

	// Pushed Authorization Request Endpoint URL.
	// RFC 9126 §4 (OAuth 2.0 Pushed Authorization Requests)
	PushedAuthorizationRequestEndpoint string `json:"pushed_authorization_request_endpoint,omitempty"`

	// OPTIONAL. Whether PAR is required before authorization requests.
	// RFC 9126 §4
	RequirePushedAuthorizationRequests bool `json:"require_pushed_authorization_requests,omitempty"`

	// Token Introspection Endpoint URL for metadata about access/refresh tokens.
	// RFC 7662 §2 (OAuth 2.0 Token Introspection)
	IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`

	// Token Revocation Endpoint URL for revoking access/refresh tokens.
	// RFC 7009 §2 (OAuth 2.0 Token Revocation)
	RevocationEndpoint string `json:"revocation_endpoint,omitempty"`

	// RECOMMENDED. List of supported scope values (openid, profile, email, etc.).
	// OIDC Discovery 1.0 §3.7
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// REQUIRED. List of supported response_type values (code, id_token, etc.).
	// OIDC Discovery 1.0 §3.8
	ResponseTypesSupported []string `json:"response_types_supported,omitempty"`

	// OPTIONAL. List of supported response_mode values (query, fragment, form_post).
	// OIDC Discovery 1.0 §3.9
	ResponseModesSupported []string `json:"response_modes_supported,omitempty"`

	// OPTIONAL. List of supported grant_type values.
	// OIDC Discovery 1.0 §3.10
	GrantTypesSupported []string `json:"grant_types_supported,omitempty"`

	// OPTIONAL. List of supported ACR (Authentication Context Class Reference) values.
	// OIDC Discovery 1.0 §3.11
	ACRValuesSupported []string `json:"acr_values_supported,omitempty"`

	// REQUIRED. List of supported subject identifier types (public, pairwise).
	// OIDC Discovery 1.0 §3.12
	SubjectTypesSupported []string `json:"subject_types_supported,omitempty"`

	// REQUIRED. List of supported JWS algorithms for ID Token signing.
	// OIDC Discovery 1.0 §3.13
	IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported JWE algorithms for ID Token encryption.
	// OIDC Discovery 1.0 §3.14
	IDTokenEncryptionAlgValuesSupported []string `json:"id_token_encryption_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported JWE content encryption algorithms for ID Token.
	// OIDC Discovery 1.0 §3.15
	IDTokenEncryptionEncValuesSupported []string `json:"id_token_encryption_enc_values_supported,omitempty"`

	// OPTIONAL. List of supported JWS algorithms for UserInfo JWT signing.
	// OIDC Discovery 1.0 §3.16
	UserinfoSigningAlgValuesSupported []string `json:"userinfo_signing_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported JWE algorithms for UserInfo JWT encryption.
	// OIDC Discovery 1.0 §3.17
	UserinfoEncryptionAlgValuesSupported []string `json:"userinfo_encryption_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported JWE content encryption algorithms for UserInfo JWT.
	// OIDC Discovery 1.0 §3.18
	UserinfoEncryptionEncValuesSupported []string `json:"userinfo_encryption_enc_values_supported,omitempty"`

	// OPTIONAL. List of supported JWS algorithms for Request Object signing.
	// OIDC Discovery 1.0 §3.19
	RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported JWE algorithms for Request Object encryption.
	// OIDC Discovery 1.0 §3.20
	RequestObjectEncryptionAlgValuesSupported []string `json:"request_object_encryption_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported JWE content encryption algorithms for Request Object.
	// OIDC Discovery 1.0 §3.21
	RequestObjectEncryptionEncValuesSupported []string `json:"request_object_encryption_enc_values_supported,omitempty"`

	// OPTIONAL. List of supported client authentication methods at the Token Endpoint.
	// Includes client_secret_post, private_key_jwt, tls_client_auth, etc.
	// OIDC Discovery 1.0 §3.22
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`

	// OPTIONAL. List of supported JWS algorithms for Token Endpoint authentication.
	// OIDC Discovery 1.0 §3.23
	TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported client authentication methods at the Introspection Endpoint.
	// RFC 8414 §2 (OAuth 2.0 Authorization Server Metadata)
	IntrospectionEndpointAuthMethodsSupported []string `json:"introspection_endpoint_auth_methods_supported,omitempty"`

	// OPTIONAL. List of supported JWS algorithms for Introspection Endpoint authentication.
	// RFC 8414 §2 (OAuth 2.0 Authorization Server Metadata)
	IntrospectionEndpointAuthSigningAlgValuesSupported []string `json:"introspection_endpoint_auth_signing_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported client authentication methods at the Revocation Endpoint.
	// RFC 8414 §2 (OAuth 2.0 Authorization Server Metadata)
	RevocationEndpointAuthMethodsSupported []string `json:"revocation_endpoint_auth_methods_supported,omitempty"`

	// OPTIONAL. List of supported JWS algorithms for Revocation Endpoint authentication.
	// RFC 8414 §2 (OAuth 2.0 Authorization Server Metadata)
	RevocationEndpointAuthSigningAlgValuesSupported []string `json:"revocation_endpoint_auth_signing_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported display parameter values (page, popup, touch, wap).
	// OIDC Discovery 1.0 §3.24
	DisplayValuesSupported []string `json:"display_values_supported,omitempty"`

	// OPTIONAL. List of supported claim types (normal, aggregated, distributed).
	// OIDC Discovery 1.0 §3.25
	ClaimTypesSupported []string `json:"claim_types_supported,omitempty"`

	// RECOMMENDED. List of claim names the OP supports for the UserInfo Endpoint.
	// OIDC Discovery 1.0 §3.26
	ClaimsSupported []string `json:"claims_supported,omitempty"`

	// OPTIONAL. Whether the claims request parameter is supported.
	// OIDC Discovery 1.0 §3.27
	ClaimsParameterSupported bool `json:"claims_parameter_supported,omitempty"`

	// OPTIONAL. List of locale codes for claims content.
	// OIDC Discovery 1.0 §3.28
	ClaimsLocalesSupported []string `json:"claims_locales_supported,omitempty"`

	// OPTIONAL. List of locale codes for UI content.
	// OIDC Discovery 1.0 §3.29
	UILocalesSupported []string `json:"ui_locales_supported,omitempty"`

	// OPTIONAL. Whether the request request parameter is supported.
	// OIDC Discovery 1.0 §3.30
	RequestParameterSupported bool `json:"request_parameter_supported,omitempty"`

	// OPTIONAL. Whether the request_uri request parameter is supported.
	// OIDC Discovery 1.0 §3.31
	RequestURIParameterSupported bool `json:"request_uri_parameter_supported,omitempty"`

	// OPTIONAL. Whether request_uri values must be pre-registered (Dynamic Client Registration).
	// OIDC Discovery 1.0 §3.32
	RequireRequestURIRegistration bool `json:"require_request_uri_registration,omitempty"`

	// OPTIONAL. List of supported PKCE code challenge methods (S256, plain).
	// RFC 7636 §4 (Proof Key for Code Exchange)
	CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`

	// OPTIONAL. Whether the OP returns iss in authorization response parameters.
	// RFC 8414 §2 (OAuth 2.0 Authorization Server Metadata)
	AuthorizationResponseISSParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`

	// OPTIONAL. URL of the OP's service documentation for developers.
	// OIDC Discovery 1.0 §3.33
	ServiceDocumentation string `json:"service_documentation,omitempty"`

	// OPTIONAL. URL of the OP's privacy policy.
	// OIDC Discovery 1.0 §3.34
	OPPolicyURI string `json:"op_policy_uri,omitempty"`

	// OPTIONAL. URL of the OP's terms of service.
	// OIDC Discovery 1.0 §3.35
	OPTermsOfServiceURI string `json:"op_tos_uri,omitempty"`

	// OPTIONAL. List of supported JWE key management algorithms.
	// RFC 7516 §4 (JSON Web Encryption)
	JWEAlgValuesSupported []string `json:"jwe_alg_values_supported,omitempty"`

	// OPTIONAL. List of supported JWE content encryption algorithms.
	// RFC 7516 §4 (JSON Web Encryption)
	JWEEncValuesSupported []string `json:"jwe_enc_values_supported,omitempty"`

	// OPTIONAL. Whether the OP supports mutual-TLS client certificate-bound access tokens.
	// RFC 8705 §3.3 (OAuth 2.0 Mutual TLS)
	TLSClientCertificateBoundAccessTokens bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`

	// OPTIONAL. Alternative mTLS-secured endpoint URLs for clients using mutual TLS.
	// RFC 8705 §5 (OAuth 2.0 Mutual TLS)
	MTLSEndpointAliases any `json:"mtls_endpoint_aliases,omitempty"`

	// OPTIONAL. Whether the OP supports Resource Indicators.
	// RFC 8707 §5 (Resource Indicators for OAuth 2.0)
	ResourceIndicatorsSupported bool `json:"resource_indicators_supported,omitempty"`

	// OPTIONAL. List of supported authorization_details type values.
	// RFC 9396 §6 (Rich Authorization Requests)
	AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"`

	// OPTIONAL. List of supported CIBA token delivery modes.
	// CIBA Core 1.0 §4 (Client-Initiated Backchannel Authentication)
	BackchannelTokenDeliveryModesSupported []string `json:"backchannel_token_delivery_modes_supported,omitempty"`

	// OPTIONAL. List of JWS signing algorithms supported for CIBA signed authentication requests.
	// CIBA Core 1.0 §4
	BackchannelAuthenticationRequestSigningAlgValuesSupported []string `json:"backchannel_authentication_request_signing_alg_values_supported,omitempty"`

	// OPTIONAL. List of JWS signing algorithms supported for JARM authorization responses.
	// JWT Secured Authorization Response Mode (JARM) §4
	AuthorizationSigningAlgValuesSupported []string `json:"authorization_signing_alg_values_supported,omitempty"`

	// Extra holds additional discovery fields contributed by plugins that
	// are not part of the standard metadata registry.
	Extra map[string]any `json:"-"`
}

DiscoveryConfiguration is the canonical OpenID Provider metadata structure. Fields are ordered per OIDC Discovery 1.0 §3. The struct IS the spec; field sequence maps to JSON ordering, json tags map to IANA-registered metadata names.

func (*DiscoveryConfiguration) MarshalJSON

func (d *DiscoveryConfiguration) MarshalJSON() ([]byte, error)

func (*DiscoveryConfiguration) UnmarshalJSON

func (d *DiscoveryConfiguration) UnmarshalJSON(data []byte) error

type Display

type Display string
const (
	DisplayPage  Display = "page"
	DisplayPopup Display = "popup"
	DisplayTouch Display = "touch"
	DisplayWAP   Display = "wap"
)

func (*Display) UnmarshalText

func (d *Display) UnmarshalText(text []byte) error

type Encoder

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

Encoder encodes structs into url.Values using "schema" struct tags. It replaces the former github.com/zitadel/schema.Encoder dependency.

func NewEncoder

func NewEncoder() *Encoder

NewEncoder returns an Encoder that knows how to encode SpaceDelimitedArray and Locales values into url.Values.

func (*Encoder) Encode

func (e *Encoder) Encode(src any, dst map[string][]string) error

Encode encodes src (a struct or pointer to struct) into dst. It reads "schema" struct tags for field names. Fields with `schema:",omitempty"` whose zero value is empty will be omitted. Custom types implementing encoding.TextMarshaler are supported.

type EndSessionRequest

type EndSessionRequest struct {
	IdTokenHint           string  `json:"-" schema:"id_token_hint"`
	LogoutHint            string  `json:"-" schema:"logout_hint"`
	ClientID              string  `json:"-" schema:"client_id"`
	PostLogoutRedirectURI string  `json:"-" schema:"post_logout_redirect_uri"`
	State                 string  `json:"-" schema:"state"`
	UILocales             Locales `json:"-" schema:"ui_locales"`
}

OIDC RP-Initiated Logout 1.0 §4 — RP-Initiated Logout Request

https://openid.net/specs/openid-connect-rpinitiated-1_0.html#RPLogout

Parameters (application/x-www-form-urlencoded):

id_token_hint           RECOMMENDED. Previously issued ID Token.
logout_hint             OPTIONAL. Hint to the OP about the End-User.
client_id               OPTIONAL. OAuth 2.0 Client Identifier.
post_logout_redirect_uri OPTIONAL. URI to redirect after logout.
state                   OPTIONAL. Opaque value for state maintenance.
ui_locales              OPTIONAL. End-User's preferred languages (space-separated BCP47 tags).

type Endpoint

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

func NewEndpoint

func NewEndpoint(path string) *Endpoint

func NewEndpointWithURL

func NewEndpointWithURL(path, url string) *Endpoint

func (*Endpoint) Absolute

func (e *Endpoint) Absolute(host string) string

func (*Endpoint) DiscoveryURL

func (e *Endpoint) DiscoveryURL(issuer string) string

DiscoveryURL returns the absolute URL for this endpoint using the given issuer. It is equivalent to e.Absolute(issuer) but provided as a convenience for discovery document contributors.

func (*Endpoint) Relative

func (e *Endpoint) Relative() string

func (*Endpoint) Validate

func (e *Endpoint) Validate() error

type Error

type Error struct {
	Parent       error     `json:"-" schema:"-"`
	ErrorType    errorType `json:"error" schema:"error"`
	Description  string    `json:"error_description,omitempty" schema:"error_description,omitempty"`
	State        string    `json:"state,omitempty" schema:"state,omitempty"`
	SessionState string    `json:"session_state,omitempty" schema:"session_state,omitempty"`
	// contains filtered or unexported fields
}

func DefaultToServerError

func DefaultToServerError(err error, description string) *Error

func ToOAuthError

func ToOAuthError(code string) *Error

ToOAuthError maps an OAuth error code string (e.g. "access_denied") to a protocol.Error. Returns ErrInvalidRequest for unknown codes.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) HTTPStatusCode

func (e *Error) HTTPStatusCode() int

HTTPStatusCode returns the preferred HTTP status code for this error. Returns 0 if no specific status code has been set (caller should use default).

func (*Error) Is

func (e *Error) Is(target error) bool

Is implements errors.Is comparison based on ErrorType and optional metadata.

func (*Error) IsRedirectDisabled

func (e *Error) IsRedirectDisabled() bool

IsRedirectDisabled reports whether this error should be rendered as a direct JSON response rather than a redirect (e.g. when redirect_uri is missing or invalid).

func (*Error) LogLevel

func (e *Error) LogLevel() slog.Level

LogLevel returns the appropriate slog level for this error. ServerError maps to LevelError, AuthorizationPending to LevelInfo, everything else to LevelWarn.

func (*Error) LogValue

func (e *Error) LogValue() slog.Value

LogValue implements slog.LogValuer for structured logging.

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON serialises the error per RFC 6749 §5.2 JSON format.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap enables errors.Is / errors.As traversal.

func (*Error) WithDescription

func (e *Error) WithDescription(desc string, args ...any) *Error

WithDescription sets a human-readable description.

func (*Error) WithHTTPStatusCode

func (e *Error) WithHTTPStatusCode(code int) *Error

WithHTTPStatusCode sets the preferred HTTP status code for this error. This allows errors to carry their own RFC-mandated status code, so that endpoints and WriteError don't need ad-hoc mapping logic.

func (*Error) WithParent

func (e *Error) WithParent(err error) *Error

WithParent chains a parent error for diagnostics.

func (*Error) WithReturnParentToClient

func (e *Error) WithReturnParentToClient(b bool) *Error

WithReturnParentToClient controls whether the parent error message is included in the JSON response body. Use with caution — parent errors may expose sensitive implementation details.

type FlexInt

type FlexInt int

FlexInt is an int that can be unmarshalled from both JSON string and number. CIBA Core 1.0 §7.1.1: requested_expiry may be sent as either a JSON string or a JSON number; the OP must accept either type.

func (*FlexInt) UnmarshalJSON

func (fi *FlexInt) UnmarshalJSON(data []byte) error

type GMJWK

type GMJWK interface {
	// MarshalJSON serializes the GM/T JWK to JSON.
	// The output must be a valid JSON object per GM/T 0125.4-2022.
	MarshalJSON() ([]byte, error)
}

GMJWK represents a GM/T (国密) JSON Web Key for JWKS publication. This is needed because the jwx library does not recognize SM2/SM9 curves, so standard jwk.Key cannot represent these keys.

type GMJWKProvider

type GMJWKProvider interface {
	GMJWK() GMJWK
}

GMJWKProvider is an optional extension of Key for GM/T (国密) keys. OP implementations can satisfy this interface to provide custom JWKS serialization for SM2/SM9 keys that jwx cannot represent as jwk.Key. RP/RS clients never need this — they consume standard JWKS JSON.

JWKS endpoints discover GM/T capability via type assertion:

if gm, ok := key.(protocol.GMJWKProvider); ok && gm.GMJWK() != nil {
    // use GMJWK for serialization
}

type Gender

type Gender string

type GrantType

type GrantType string
const (
	GrantTypeCode              GrantType = "authorization_code"
	GrantTypeRefreshToken      GrantType = "refresh_token"
	GrantTypeClientCredentials GrantType = "client_credentials"
	GrantTypeBearer            GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
	GrantTypeTokenExchange     GrantType = "urn:ietf:params:oauth:grant-type:token-exchange"
	GrantTypeImplicit          GrantType = "implicit"
	GrantTypeDeviceCode        GrantType = "urn:ietf:params:oauth:grant-type:device_code"
	GrantTypeCIBA              GrantType = "urn:openid:params:grant-type:ciba"
)

type IDClaims

type IDClaims interface {
	Claims
	GetSignatureAlgorithm() string
	GetAccessTokenHash() string
}

type IDTokenClaims

type IDTokenClaims struct {
	TokenClaims
	NotBefore       Time   `json:"nbf,omitempty"`
	AccessTokenHash string `json:"at_hash,omitempty"`
	CodeHash        string `json:"c_hash,omitempty"`
	SessionID       string `json:"sid,omitempty"`
	UserInfoProfile
	UserInfoEmail
	UserInfoPhone
	Address *UserInfoAddress `json:"address,omitempty"`
	Claims  map[string]any   `json:"-"`
}

IDTokenClaims extends TokenClaims by further implementing OpenID Connect Core 1.0, sections 3.1.3.6 (Code flow), 3.2.2.10 (implicit), 3.3.2.11 (Hybrid) and 5.1 (UserInfo). https://openid.net/specs/openid-connect-core-1_0.html#toc

func NewIDTokenClaims

func NewIDTokenClaims(issuer, subject string, audience []string, expiration, authTime time.Time, nonce string, acr string, amr []string, clientID string, skew time.Duration) *IDTokenClaims

NewIDTokenClaims creates a new IDTokenClaims with the given parameters.

func VerifyIDTokenHint

func VerifyIDTokenHint(ctx context.Context, token string, v *IDTokenHintVerifier) (*IDTokenClaims, error)

func (*IDTokenClaims) GetAccessTokenHash

func (t *IDTokenClaims) GetAccessTokenHash() string

func (*IDTokenClaims) GetUserInfo

func (t *IDTokenClaims) GetUserInfo() *UserInfo

GetUserInfo extracts a UserInfo response from the IDTokenClaims.

func (*IDTokenClaims) MarshalJSON

func (i *IDTokenClaims) MarshalJSON() ([]byte, error)

func (*IDTokenClaims) SetUserInfo

func (t *IDTokenClaims) SetUserInfo(i *UserInfo)

SetUserInfo populates the IDTokenClaims from a UserInfo response.

func (*IDTokenClaims) UnmarshalJSON

func (i *IDTokenClaims) UnmarshalJSON(data []byte) error

type IDTokenHintExpiredError

type IDTokenHintExpiredError struct {
	Err error
}

func (IDTokenHintExpiredError) Error

func (e IDTokenHintExpiredError) Error() string

func (IDTokenHintExpiredError) Is

func (IDTokenHintExpiredError) Unwrap

func (e IDTokenHintExpiredError) Unwrap() error

type IDTokenHintVerifier

type IDTokenHintVerifier struct {
	Issuer            string
	KeySet            KeySet
	KeyStore          KeyStore // optional, used for JWKS-based verification
	Offset            time.Duration
	MaxAgeIAT         time.Duration
	MaxAge            time.Duration
	SupportedSignAlgs []string
	ACR               ACRVerifier
}

func NewIDTokenHintVerifier

func NewIDTokenHintVerifier(issuer string, keySet KeySet, opts ...IDTokenHintVerifierOpt) *IDTokenHintVerifier

type IDTokenHintVerifierOpt

type IDTokenHintVerifierOpt func(*IDTokenHintVerifier)

func WithSupportedIDTokenHintSigningAlgorithms

func WithSupportedIDTokenHintSigningAlgorithms(algs ...string) IDTokenHintVerifierOpt

type IntrospectionRequest

type IntrospectionRequest struct {
	Token string `schema:"token"`
}

type IntrospectionResponse

type IntrospectionResponse struct {
	Active                          bool                            `json:"active"`
	Scope                           SpaceDelimitedArray             `json:"scope,omitempty"`
	ClientID                        string                          `json:"client_id,omitempty"`
	TokenType                       string                          `json:"token_type,omitempty"`
	Expiration                      Time                            `json:"exp,omitempty"`
	IssuedAt                        Time                            `json:"iat,omitempty"`
	AuthTime                        Time                            `json:"auth_time,omitempty"`
	NotBefore                       Time                            `json:"nbf,omitempty"`
	Subject                         string                          `json:"sub,omitempty"`
	Audience                        Audience                        `json:"aud,omitempty"`
	AuthenticationMethodsReferences AuthenticationMethodsReferences `json:"amr,omitempty"`
	Issuer                          string                          `json:"iss,omitempty"`
	JWTID                           string                          `json:"jti,omitempty"`
	Username                        string                          `json:"username,omitempty"`
	Actor                           *ActorClaims                    `json:"act,omitempty"`
	UserInfoProfile
	UserInfoEmail
	UserInfoPhone

	Address *UserInfoAddress `json:"address,omitempty"`
	Claims  map[string]any   `json:"-"`
}

IntrospectionResponse implements RFC 7662, section 2.2 and OpenID Connect Core 1.0, section 5.1 (UserInfo). https://www.rfc-editor.org/rfc/rfc7662.html#section-2.2. https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims.

func (*IntrospectionResponse) GetAddress

func (i *IntrospectionResponse) GetAddress() *UserInfoAddress

GetAddress is a safe getter that takes care of a possible nil value.

func (*IntrospectionResponse) MarshalJSON

func (i *IntrospectionResponse) MarshalJSON() ([]byte, error)

func (*IntrospectionResponse) SetUserInfo

func (i *IntrospectionResponse) SetUserInfo(u *UserInfo)

SetUserInfo copies all relevant fields from UserInfo into the IntrospectionResponse.

func (*IntrospectionResponse) UnmarshalJSON

func (i *IntrospectionResponse) UnmarshalJSON(data []byte) error

type JWEService

type JWEService interface {
	// Encrypt encrypts plaintext using the specified JWE algorithms.
	// alg is the key wrapping algorithm (e.g. "dir", "SGD_SM2_3", "SGD_SM9_3").
	// enc is the content encryption algorithm (e.g. "A256GCM", "SGD_SM4_GCM").
	// key is the encryption key material; type depends on alg:
	//   - "dir": []byte symmetric key
	//   - "SGD_SM2_3": *ecdsa.PublicKey
	//   - "SGD_SM9_3": SM9EncryptKey
	Encrypt(ctx context.Context, plaintext []byte, key interface{}, alg, enc string) (string, error)

	// Decrypt decrypts a JWE compact serialization.
	// key is the decryption key material; type depends on the JWE header alg.
	Decrypt(ctx context.Context, token string, key interface{}) ([]byte, error)
}

JWEService is the unified entry point for JWE encryption and decryption. Both OP and RP can use it without caring about the underlying implementation.

type JWSService

type JWSService interface {
	JWSSigner
	JWSVerifier
}

JWSService provides both signing and verification capabilities. It is the recommended way for upper layers (op, storm, client) to perform JWS operations.

type JWSSigner

type JWSSigner interface {
	// Sign signs the payload with the key identified by keyID using the specified algorithm.
	// alg is a JWA signature algorithm string, e.g. "RS256", "ES256", "EdDSA", "SGD_SM3_SM2".
	// Returns the compact JWS serialization.
	Sign(ctx context.Context, payload []byte, keyID, alg string) (string, error)
}

JWSSigner is the unified entry point for JWS signing operations. Both OP and RP can use it without caring about the underlying implementation (software gmsm, HSM, KMS, etc.).

type JWSVerifier

type JWSVerifier interface {
	// Verify verifies the JWS token against the provided KeySet and returns the payload.
	Verify(ctx context.Context, token string, keySet KeySet) ([]byte, error)
}

JWSVerifier is the unified entry point for JWS signature verification.

type JWTProfileAssertionClaims

type JWTProfileAssertionClaims struct {
	PrivateKeyID string         `json:"-"`
	PrivateKey   []byte         `json:"-"`
	Issuer       string         `json:"iss"`
	Subject      string         `json:"sub"`
	Audience     Audience       `json:"aud"`
	Expiration   Time           `json:"exp"`
	IssuedAt     Time           `json:"iat"`
	Claims       map[string]any `json:"-"`
}

JWTProfileAssertionClaims implements RFC 7523, section 2.1 for JWT Profile assertions. https://datatracker.ietf.org/doc/html/rfc7523#section-2.1

func NewJWTProfileAssertion

func NewJWTProfileAssertion(userID, keyID string, audience []string, key []byte, opts ...AssertionOption) *JWTProfileAssertionClaims

NewJWTProfileAssertion creates a new JWTProfileAssertionClaims for JWT Profile authentication.

func NewJWTProfileAssertionFromFileData

func NewJWTProfileAssertionFromFileData(data []byte, audience []string, opts ...AssertionOption) (*JWTProfileAssertionClaims, error)

NewJWTProfileAssertionFromFileData creates a JWTProfileAssertionClaims from JSON key data.

func NewJWTProfileAssertionFromKeyJSON

func NewJWTProfileAssertionFromKeyJSON(filename string, audience []string, opts ...AssertionOption) (*JWTProfileAssertionClaims, error)

NewJWTProfileAssertionFromKeyJSON creates a JWTProfileAssertionClaims by reading key data from a file.

func (*JWTProfileAssertionClaims) MarshalJSON

func (j *JWTProfileAssertionClaims) MarshalJSON() ([]byte, error)

func (*JWTProfileAssertionClaims) UnmarshalJSON

func (j *JWTProfileAssertionClaims) UnmarshalJSON(data []byte) error

type JWTProfileGrantRequest

type JWTProfileGrantRequest struct {
	Assertion string              `schema:"assertion"`
	Scope     SpaceDelimitedArray `schema:"scope"`
	GrantType GrantType           `schema:"grant_type"`
}

func NewJWTProfileGrantRequest

func NewJWTProfileGrantRequest(assertion string, scopes ...string) *JWTProfileGrantRequest

type JWTTokenRequest

type JWTTokenRequest struct {
	Issuer    string              `json:"iss"`
	Subject   string              `json:"sub"`
	Scopes    SpaceDelimitedArray `json:"-"`
	Audience  Audience            `json:"aud"`
	IssuedAt  Time                `json:"iat"`
	ExpiresAt Time                `json:"exp"`
	NotBefore Time                `json:"nbf"`
	// contains filtered or unexported fields
}

func (*JWTTokenRequest) GetAudience

func (j *JWTTokenRequest) GetAudience() []string

func (*JWTTokenRequest) GetAuthTime

func (j *JWTTokenRequest) GetAuthTime() time.Time

func (*JWTTokenRequest) GetAuthenticationContextClassReference

func (j *JWTTokenRequest) GetAuthenticationContextClassReference() string

func (*JWTTokenRequest) GetAuthorizedParty

func (j *JWTTokenRequest) GetAuthorizedParty() string

func (*JWTTokenRequest) GetCustomClaim

func (j *JWTTokenRequest) GetCustomClaim(key string) any

func (*JWTTokenRequest) GetExpiration

func (j *JWTTokenRequest) GetExpiration() time.Time

func (*JWTTokenRequest) GetIssuedAt

func (j *JWTTokenRequest) GetIssuedAt() time.Time

func (*JWTTokenRequest) GetIssuer

func (j *JWTTokenRequest) GetIssuer() string

func (*JWTTokenRequest) GetNonce

func (j *JWTTokenRequest) GetNonce() string

func (*JWTTokenRequest) GetNotBefore

func (j *JWTTokenRequest) GetNotBefore() time.Time

func (*JWTTokenRequest) GetScopes

func (j *JWTTokenRequest) GetScopes() []string

func (*JWTTokenRequest) GetSubject

func (j *JWTTokenRequest) GetSubject() string

func (*JWTTokenRequest) MarshalJSON

func (j *JWTTokenRequest) MarshalJSON() ([]byte, error)

func (*JWTTokenRequest) SetSignatureAlgorithm

func (j *JWTTokenRequest) SetSignatureAlgorithm(_ string)

func (*JWTTokenRequest) UnmarshalJSON

func (j *JWTTokenRequest) UnmarshalJSON(data []byte) error

type Key

type Key interface {
	ID() string
	Algorithm() string
	Use() string
	Key() jwk.Key
}

Key represents a single JSON Web Key with metadata.

type KeySet

type KeySet interface {
	// VerifySignature verifies the signature with the given keyset and returns the raw payload
	VerifySignature(ctx context.Context, rawToken []byte) (payload []byte, err error)
}

KeySet represents a set of JSON Web Keys

  • remotely fetch via discovery and jwks_uri -> `remoteKeySet`
  • held by the OP itself in storage -> `openIDKeySet`
  • dynamically aggregated by request for OAuth JWT Profile Assertion -> `jwtProfileKeySet`

type KeyStore

type KeyStore interface {
	KeySet(ctx context.Context) ([]Key, error)
	SignatureAlgorithms(ctx context.Context) ([]string, error)
}

KeyStore provides access to a set of JSON Web Keys and the signature algorithms they support.

type Locale

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

func NewLocale

func NewLocale(tag language.Tag) *Locale

func (*Locale) MarshalJSON

func (l *Locale) MarshalJSON() ([]byte, error)

func (*Locale) String

func (l *Locale) String() string

func (*Locale) Tag

func (l *Locale) Tag() language.Tag

func (*Locale) UnmarshalJSON

func (l *Locale) UnmarshalJSON(data []byte) error

type Locales

type Locales []language.Tag

func ParseLocales

func ParseLocales(tags []string) Locales

func (Locales) MarshalText

func (l Locales) MarshalText() ([]byte, error)

func (Locales) String

func (l Locales) String() string

func (*Locales) UnmarshalJSON

func (l *Locales) UnmarshalJSON(data []byte) error

func (*Locales) UnmarshalText

func (l *Locales) UnmarshalText(text []byte) error

type LogoutTokenClaims

type LogoutTokenClaims struct {
	Issuer     string         `json:"iss,omitempty"`
	Subject    string         `json:"sub,omitempty"`
	Audience   Audience       `json:"aud,omitempty"`
	IssuedAt   Time           `json:"iat,omitempty"`
	Expiration Time           `json:"exp,omitempty"`
	JWTID      string         `json:"jti,omitempty"`
	Events     map[string]any `json:"events,omitempty"`
	SessionID  string         `json:"sid,omitempty"`
	Claims     map[string]any `json:"-"`
}

LogoutTokenClaims implements OpenID Connect Back-Channel Logout 1.0, section 2.4. https://openid.net/specs/openid-connect-backchannel-1_0.html#LogoutToken

func NewLogoutTokenClaims

func NewLogoutTokenClaims(issuer, subject string, audience Audience, expiration time.Time, jwtID, sessionID string, skew time.Duration) *LogoutTokenClaims

NewLogoutTokenClaims creates a new LogoutTokenClaims for back-channel logout.

func (*LogoutTokenClaims) GetAudience

func (c *LogoutTokenClaims) GetAudience() []string

func (*LogoutTokenClaims) GetAuthTime

func (c *LogoutTokenClaims) GetAuthTime() time.Time

func (*LogoutTokenClaims) GetAuthenticationContextClassReference

func (c *LogoutTokenClaims) GetAuthenticationContextClassReference() string

func (*LogoutTokenClaims) GetAuthorizedParty

func (c *LogoutTokenClaims) GetAuthorizedParty() string

func (*LogoutTokenClaims) GetExpiration

func (c *LogoutTokenClaims) GetExpiration() time.Time

func (*LogoutTokenClaims) GetIssuedAt

func (c *LogoutTokenClaims) GetIssuedAt() time.Time

func (*LogoutTokenClaims) GetIssuer

func (c *LogoutTokenClaims) GetIssuer() string

func (*LogoutTokenClaims) GetNonce

func (c *LogoutTokenClaims) GetNonce() string

func (*LogoutTokenClaims) GetSignatureAlgorithm

func (c *LogoutTokenClaims) GetSignatureAlgorithm() string

func (*LogoutTokenClaims) GetSubject

func (c *LogoutTokenClaims) GetSubject() string

func (*LogoutTokenClaims) MarshalJSON

func (i *LogoutTokenClaims) MarshalJSON() ([]byte, error)

func (*LogoutTokenClaims) SetSignatureAlgorithm

func (c *LogoutTokenClaims) SetSignatureAlgorithm(alg string)

func (*LogoutTokenClaims) UnmarshalJSON

func (i *LogoutTokenClaims) UnmarshalJSON(data []byte) error

type MaxAge

type MaxAge *uint

func NewMaxAge

func NewMaxAge(i uint) MaxAge

type PushedAuthRequest

type PushedAuthRequest struct {
	AuthRequest
}

PushedAuthRequest represents the parameters sent to the Pushed Authorization Request endpoint. https://datatracker.ietf.org/doc/html/rfc9126#section-2.1

type PushedAuthResponse

type PushedAuthResponse struct {
	RequestURI string `json:"request_uri"`
	ExpiresIn  int    `json:"expires_in"`
}

PushedAuthResponse is the successful response from the Pushed Authorization Request endpoint. https://datatracker.ietf.org/doc/html/rfc9126#section-2.2

type RefreshTokenRequest

type RefreshTokenRequest struct {
	GrantType           string              `schema:"grant_type,omitempty"`
	RefreshToken        string              `schema:"refresh_token"`
	Scopes              SpaceDelimitedArray `schema:"scope"`
	ClientID            string              `schema:"client_id"`
	ClientSecret        string              `schema:"client_secret"`
	ClientAssertion     string              `schema:"client_assertion"`
	ClientAssertionType string              `schema:"client_assertion_type"`
}

func (*RefreshTokenRequest) SetClientID

func (a *RefreshTokenRequest) SetClientID(clientID string)

func (*RefreshTokenRequest) SetClientSecret

func (a *RefreshTokenRequest) SetClientSecret(clientSecret string)

type RequestObject

type RequestObject struct {
	Issuer    string   `json:"iss"`
	Audience  Audience `json:"aud"`
	ExpiresAt int64    `json:"exp,omitempty"` // expiration time (seconds since epoch)
	NotBefore int64    `json:"nbf,omitempty"` // not-valid-before time
	IssuedAt  int64    `json:"iat,omitempty"` // issued-at time
	AuthRequest
}

RequestObject represents an OIDC Request Object (JWS/JWE encoded AuthRequest). OIDC Core 1.0 §6.1 — Passing a Request Object by Value https://openid.net/specs/openid-connect-core-1_0.html#RequestObject

func (*RequestObject) GetIssuer

func (r *RequestObject) GetIssuer() string

func (*RequestObject) SetSignatureAlgorithm

func (*RequestObject) SetSignatureAlgorithm(algorithm string)

type ResponseMode

type ResponseMode string
const (
	// ResponseModeQuery returns parameters in the query string of the redirect_uri.
	ResponseModeQuery ResponseMode = "query"

	// ResponseModeFragment returns parameters in the fragment of the redirect_uri.
	ResponseModeFragment ResponseMode = "fragment"

	// ResponseModeFormPost returns parameters via auto-submitting a form.
	// OAuth 2.0 Form Post Response Mode §2.1
	ResponseModeFormPost ResponseMode = "form_post"
)

OAuth 2.0 Multiple Response Type Encoding Practice §2.1

https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html
const (
	// ResponseModeQueryJWT returns the authorization response as a JWT in the query string.
	ResponseModeQueryJWT ResponseMode = "query.jwt"

	// ResponseModeFragmentJWT returns the authorization response as a JWT in the fragment.
	ResponseModeFragmentJWT ResponseMode = "fragment.jwt"

	// ResponseModeFormPostJWT returns the authorization response as a JWT via form post.
	ResponseModeFormPostJWT ResponseMode = "form_post.jwt"

	// ResponseModeJWT is the JARM shorthand (RFC 9101 §4.1 / FAPI 2.0).
	// It resolves to query.jwt for code flow, fragment.jwt for implicit/hybrid.
	ResponseModeJWT ResponseMode = "jwt"
)

JARM (JWT Secured Authorization Response Mode) — RFC 9101

https://datatracker.ietf.org/doc/html/rfc9101

type ResponseType

type ResponseType string
const (
	// ResponseTypeCode for the Authorization Code Flow.
	// OAuth 2.0 §4.1.1
	ResponseTypeCode ResponseType = "code"

	// ResponseTypeNone for checking authentication state without issuing tokens.
	// OIDC Core 1.0 §3.2.2.1
	ResponseTypeNone ResponseType = "none"

	// ResponseTypeIDToken for the Implicit Flow returning id and access tokens.
	// OIDC Core 1.0 §3.2.2.4
	ResponseTypeIDToken ResponseType = "id_token token"

	// ResponseTypeIDTokenOnly for the Implicit Flow returning only id token.
	// OIDC Core 1.0 §3.2.2.5
	ResponseTypeIDTokenOnly ResponseType = "id_token"

	// ResponseTypeToken for the Implicit Flow returning only access token.
	// OAuth 2.0 §4.2.1
	ResponseTypeToken ResponseType = "token"

	// Hybrid Flow response types (OIDC Core §3.3).
	// These return both an authorization code and tokens in the fragment.
	ResponseTypeCodeIDToken      ResponseType = "code id_token"
	ResponseTypeCodeToken        ResponseType = "code token"
	ResponseTypeCodeIDTokenToken ResponseType = "code id_token token"
)

OAuth 2.0 §3.1.1 — Response Types OIDC Core 1.0 §3 — Authentication

https://openid.net/specs/openid-connect-core-1_0.html#Authentication

type RevocationRequest

type RevocationRequest struct {
	Token         string `schema:"token"`
	TokenTypeHint string `schema:"token_type_hint,omitempty"`
}

RFC 7009 §2.1 - Token Revocation Request

The client constructs the request by including the following parameters using the "application/x-www-form-urlencoded" format:

token           REQUIRED. The token that the client wants to get revoked.
token_type_hint OPTIONAL. A hint about the type of the token submitted for revocation.

Per RFC 7009 §2.2, the response is always HTTP 200 with an empty body on success, or an error response per RFC 6749 §5.2 on failure.

type SM9EncryptKey

type SM9EncryptKey interface {
	// MarshalBinary returns the SM9 master public key in its canonical byte representation.
	MarshalBinary() ([]byte, error)
	// GetUID returns the user identifier for SM9 identity-based encryption.
	GetUID() []byte
}

SM9EncryptKey is the protocol-layer interface for SM9 encryption keys. It hides the underlying gmsm type from protocol consumers. Implementations are provided by pkg/crypto (gmsm) or HSM adapters.

The canonical implementation is crypto.SM9MasterPublicKey, which wraps *sm9.EncryptMasterPublicKey + UID. HSM/KMS vendors can implement this interface to provide their own SM9 key material.

type SignatureRegistry

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

func NewSignatureRegistry

func NewSignatureRegistry() *SignatureRegistry

func (*SignatureRegistry) Register

func (r *SignatureRegistry) Register(v SignatureVerifier)

func (*SignatureRegistry) Verify

func (r *SignatureRegistry) Verify(ctx context.Context, jwsMsg *jws.Message, rawToken []byte, key jwk.Key, alg string) ([]byte, error)

type SignatureVerifier

type SignatureVerifier interface {
	Algorithm() string
	Verify(jwsMsg *jws.Message, rawToken []byte, key jwk.Key) ([]byte, error)
}

type SigningKey

type SigningKey interface {
	ID() string
	Algorithm() string
	Key() jwk.Key
}

SigningKey represents a key used for signing operations.

type SpaceDelimitedArray

type SpaceDelimitedArray []string

func (SpaceDelimitedArray) MarshalJSON

func (s SpaceDelimitedArray) MarshalJSON() ([]byte, error)

func (SpaceDelimitedArray) MarshalText

func (s SpaceDelimitedArray) MarshalText() ([]byte, error)

func (*SpaceDelimitedArray) Scan

func (s *SpaceDelimitedArray) Scan(src any) error

func (SpaceDelimitedArray) String

func (s SpaceDelimitedArray) String() string

func (*SpaceDelimitedArray) UnmarshalJSON

func (s *SpaceDelimitedArray) UnmarshalJSON(data []byte) error

func (*SpaceDelimitedArray) UnmarshalText

func (s *SpaceDelimitedArray) UnmarshalText(text []byte) error

func (SpaceDelimitedArray) Value

func (s SpaceDelimitedArray) Value() (driver.Value, error)

type Time

type Time int64

func FromTime

func FromTime(tt time.Time) Time

func NowTime

func NowTime() Time

func (Time) AsTime

func (ts Time) AsTime() time.Time

func (*Time) UnmarshalJSON

func (ts *Time) UnmarshalJSON(data []byte) error

type TokenClaims

type TokenClaims struct {
	Issuer                              string                          `json:"iss,omitempty"`
	Subject                             string                          `json:"sub,omitempty"`
	Audience                            Audience                        `json:"aud,omitempty"`
	Expiration                          Time                            `json:"exp,omitempty"`
	IssuedAt                            Time                            `json:"iat,omitempty"`
	AuthTime                            Time                            `json:"auth_time,omitempty"`
	NotBefore                           Time                            `json:"nbf,omitempty"`
	Nonce                               string                          `json:"nonce,omitempty"`
	AuthenticationContextClassReference string                          `json:"acr,omitempty"`
	AuthenticationMethodsReferences     AuthenticationMethodsReferences `json:"amr,omitempty"`
	AuthorizedParty                     string                          `json:"azp,omitempty"`
	ClientID                            string                          `json:"client_id,omitempty"`
	JWTID                               string                          `json:"jti,omitempty"`
	Actor                               *ActorClaims                    `json:"act,omitempty"`

	SignatureAlg string `json:"-"`
}

TokenClaims contains the base Claims used all tokens. It implements OpenID Connect Core 1.0, section 2. https://openid.net/specs/openid-connect-core-1_0.html#IDToken And RFC 9068: JSON Web Token (JWT) Profile for OAuth 2.0 Access Tokens, section 2.2. https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure

TokenClaims implements the Claims interface, and can be used to extend larger claim types by embedding.

func (*TokenClaims) GetAudience

func (c *TokenClaims) GetAudience() []string

func (*TokenClaims) GetAuthTime

func (c *TokenClaims) GetAuthTime() time.Time

func (*TokenClaims) GetAuthenticationContextClassReference

func (c *TokenClaims) GetAuthenticationContextClassReference() string

func (*TokenClaims) GetAuthorizedParty

func (c *TokenClaims) GetAuthorizedParty() string

func (*TokenClaims) GetExpiration

func (c *TokenClaims) GetExpiration() time.Time

func (*TokenClaims) GetIssuedAt

func (c *TokenClaims) GetIssuedAt() time.Time

func (*TokenClaims) GetIssuer

func (c *TokenClaims) GetIssuer() string

func (*TokenClaims) GetNonce

func (c *TokenClaims) GetNonce() string

func (*TokenClaims) GetSignatureAlgorithm

func (c *TokenClaims) GetSignatureAlgorithm() string

func (*TokenClaims) GetSubject

func (c *TokenClaims) GetSubject() string

func (*TokenClaims) SetSignatureAlgorithm

func (c *TokenClaims) SetSignatureAlgorithm(algorithm string)

type TokenExchangeRequest

type TokenExchangeRequest struct {
	GrantType          GrantType           `schema:"grant_type"`
	SubjectToken       string              `schema:"subject_token"`
	SubjectTokenType   TokenType           `schema:"subject_token_type"`
	ActorToken         string              `schema:"actor_token"`
	ActorTokenType     TokenType           `schema:"actor_token_type"`
	Resource           []string            `schema:"resource"`
	Audience           Audience            `schema:"audience"`
	Scopes             SpaceDelimitedArray `schema:"scope"`
	RequestedTokenType TokenType           `schema:"requested_token_type"`
}

type TokenExchangeResponse

type TokenExchangeResponse struct {
	AccessToken     string              `json:"access_token"`
	IssuedTokenType TokenType           `json:"issued_token_type"`
	TokenType       string              `json:"token_type"`
	ExpiresIn       uint64              `json:"expires_in,omitempty"`
	Scopes          SpaceDelimitedArray `json:"scope,omitempty"`
	RefreshToken    string              `json:"refresh_token,omitempty"`
	IDToken         string              `json:"id_token,omitempty"`
}

TokenExchangeResponse represents a token exchange response per RFC 8693. https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.1

type TokenRequestType

type TokenRequestType GrantType

type TokenType

type TokenType string
const (
	AccessTokenType  TokenType = "urn:ietf:params:oauth:token-type:access_token"
	RefreshTokenType TokenType = "urn:ietf:params:oauth:token-type:refresh_token"
	IDTokenType      TokenType = "urn:ietf:params:oauth:token-type:id_token"
	JWTTokenType     TokenType = "urn:ietf:params:oauth:token-type:jwt"
)

func (TokenType) IsSupported

func (t TokenType) IsSupported() bool

type Tokens

type Tokens[C IDClaims] struct {
	*oauth2.Token
	IDTokenClaims C
	IDToken       string
}

Tokens represents an OAuth2 token response that includes OIDC claims.

type UserInfo

type UserInfo struct {
	Subject string `json:"sub,omitempty"`
	UserInfoProfile
	UserInfoEmail
	UserInfoPhone
	Address *UserInfoAddress `json:"address,omitempty"`

	Claims map[string]any `json:"-"`
}

UserInfo implements OpenID Connect Core 1.0, section 5.1. https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims

func (*UserInfo) AppendClaims

func (u *UserInfo) AppendClaims(k string, v any)

func (*UserInfo) FilterByScopes

func (u *UserInfo) FilterByScopes(scopes []string)

FilterByScopes removes standard OIDC claims that are not covered by the granted scopes. Custom claims in the Claims map are always preserved.

This is a convenience method intended to be called by storage implementations inside SetUserinfoFromToken. The UserInfo plugin does NOT call this automatically — if the storage does not filter, all populated claims will be returned in the response.

OIDC Core §5.3.2: The UserInfo Response MUST include the "sub" claim. Other claims are filtered by scope per §5.4:

  • profile: name, given_name, family_name, middle_name, nickname, preferred_username, profile, picture, website, gender, birthdate, zoneinfo, locale, updated_at
  • email: email, email_verified
  • phone: phone_number, phone_number_verified
  • address: address

func (*UserInfo) GetAddress

func (u *UserInfo) GetAddress() *UserInfoAddress

GetAddress is a safe getter that takes care of a possible nil value.

func (*UserInfo) GetSubject

func (u *UserInfo) GetSubject() string

GetSubject implements [rp.SubjectGetter]

func (*UserInfo) MarshalJSON

func (u *UserInfo) MarshalJSON() ([]byte, error)

func (*UserInfo) UnmarshalJSON

func (u *UserInfo) UnmarshalJSON(data []byte) error

type UserInfoAddress

type UserInfoAddress struct {
	Formatted     string `json:"formatted,omitempty"`
	StreetAddress string `json:"street_address,omitempty"`
	Locality      string `json:"locality,omitempty"`
	Region        string `json:"region,omitempty"`
	PostalCode    string `json:"postal_code,omitempty"`
	Country       string `json:"country,omitempty"`
}

type UserInfoEmail

type UserInfoEmail struct {
	Email string `json:"email,omitempty"`

	// EmailVerified MUST NOT use omitempty: OIDC Core §5.4 requires this
	// claim to be present when the email scope is granted, and false is a
	// meaningful value (not "absent").
	EmailVerified Bool `json:"email_verified"`
}

type UserInfoPhone

type UserInfoPhone struct {
	PhoneNumber string `json:"phone_number,omitempty"`

	// PhoneNumberVerified MUST NOT use omitempty: OIDC Core §5.4 requires
	// this claim to be present when the phone scope is granted.
	PhoneNumberVerified Bool `json:"phone_number_verified"`
}

type UserInfoProfile

type UserInfoProfile struct {
	Name              string  `json:"name,omitempty"`
	GivenName         string  `json:"given_name,omitempty"`
	FamilyName        string  `json:"family_name,omitempty"`
	MiddleName        string  `json:"middle_name,omitempty"`
	Nickname          string  `json:"nickname,omitempty"`
	Profile           string  `json:"profile,omitempty"`
	Picture           string  `json:"picture,omitempty"`
	Website           string  `json:"website,omitempty"`
	Gender            Gender  `json:"gender,omitempty"`
	Birthdate         string  `json:"birthdate,omitempty"`
	Zoneinfo          string  `json:"zoneinfo,omitempty"`
	Locale            *Locale `json:"locale,omitempty"`
	UpdatedAt         Time    `json:"updated_at,omitempty"`
	PreferredUsername string  `json:"preferred_username,omitempty"`
}

type UserInfoRequest

type UserInfoRequest struct {
	AccessToken string `schema:"access_token"`
}

type Verifier

type Verifier struct {
	Issuer            string
	MaxAgeIAT         time.Duration
	Offset            time.Duration
	ClientID          string
	SupportedSignAlgs []string
	MaxAge            time.Duration
	ACR               ACRVerifier
	AZP               AZPVerifier
	KeySet            KeySet
	Nonce             func(ctx context.Context) string
	DecryptionKey     []byte
}

Verifier caries configuration for the various token verification functions. Use package specific constructor functions to know which values need to be set.

Directories

Path Synopsis
test
regression
Package regression provides JSON serialization stability tests for OIDC protocol types.
Package regression provides JSON serialization stability tests for OIDC protocol types.

Jump to

Keyboard shortcuts

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