jwt

package
v2.0.330 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 32 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package jwt provides JSON Web Token (JWT) signing, verification, and parsing capabilities.

This package implements JWT as defined by RFC 7519, with support for:

  • JWT signing and verification using various algorithms (HMAC, RSA, ECDSA, and ML-DSA per RFC 9964)
  • JWT parsing and validation with configurable verification options
  • JWKS (JSON Web Key Set) for key management and distribution, including RFC 9964 AKP keys; RemoteKeySet caches a remote JWKS document for the lifetime its response states and refreshes it in the background

Subpackages: dpop (RFC 9449 proofs), accesstoken (opaque encrypted tokens), oauth2client (identity-provider client registry).

The package provides both high-level APIs for common use cases and lower-level primitives for advanced JWT operations.

Index

Constants

View Source
const (
	// DefaultJWKSRefreshCooldown is the minimum interval between the end of
	// one RemoteKeySet fetch and the start of the next.
	DefaultJWKSRefreshCooldown = 10 * time.Second
	// DefaultJWKSFetchTimeout bounds each RemoteKeySet fetch.
	DefaultJWKSFetchTimeout = 10 * time.Second
	// DefaultJWKSMaxResponseSize is the largest JWKS document, in bytes,
	// that RemoteKeySet accepts.
	DefaultJWKSMaxResponseSize = 1 << 20
	// DefaultJWKSMinCacheTTL is the shortest lifetime RemoteKeySet gives a
	// fetched JWKS document, whatever its response headers state.
	DefaultJWKSMinCacheTTL = 5 * time.Minute
	// DefaultJWKSMaxCacheTTL is the longest lifetime RemoteKeySet gives a
	// fetched JWKS document, and its lifetime when the response states none.
	DefaultJWKSMaxCacheTTL = time.Hour
	// DefaultJWKSStaleIfError is how long RemoteKeySet keeps using expired
	// keys while every refresh fails.
	DefaultJWKSStaleIfError = 24 * time.Hour
)
View Source
const (
	// DefaultNotBefore offset for NotBefore
	DefaultNotBefore = -2 * time.Minute
)

Variables

View Source
var (
	// TimeNowFn to override in unit tests
	TimeNowFn = time.Now

	// DefaultTimeSkew is an interval for allowed time skew
	DefaultTimeSkew = 5 * time.Minute
)
View Source
var (
	// ErrKeyNotFound is returned when a KeySet has no key eligible to verify
	// a token with the requested kid and algorithm.
	ErrKeyNotFound = errors.New("key not found")
	// ErrAmbiguousKey is returned when more than one key is eligible to
	// verify a token with the requested kid and algorithm.
	ErrAmbiguousKey = errors.New("ambiguous key")
)

Functions

func CopyUserInfoClaims

func CopyUserInfoClaims(src, dst MapClaims)

CopyUserInfoClaims from source to destination

func DecodeSegment

func DecodeSegment(seg string) ([]byte, error)

DecodeSegment JWT specific base64url encoding with padding stripped

func EncodeSegment

func EncodeSegment(seg []byte) string

EncodeSegment returns JWT specific base64url encoding with padding stripped

func SetClaimsExpiration

func SetClaimsExpiration(claims MapClaims, expiry time.Duration)

SetClaimsExpiration sets expiration claims

func VerifySignature

func VerifySignature(algo, signingString, signature string, key any) error

VerifySignature returns error if JWT signature is invalid. key is []byte for HS*, *rsa.PublicKey for RS*, *ecdsa.PublicKey of the curve for ES*, and *mldsa.PublicKey of the parameter set for ML-DSA-*.

Types

type AlgorithmKeySet

type AlgorithmKeySet interface {
	KeySet
	// GetKeyForAlgorithm returns the only key eligible to verify a token with
	// the given kid and alg headers. An empty keyID matches every key.
	GetKeyForAlgorithm(ctx context.Context, keyID, alg string) (any, error)
}

AlgorithmKeySet is a KeySet that can also restrict key selection to keys compatible with the token's signing algorithm. The parser uses it when the configured KeySet implements it.

type Audience

type Audience []string

Audience represents the recipients that the token is intended for.

func (Audience) Contains

func (s Audience) Contains(expected string) bool

Contains returns true if audience contains expected value

func (*Audience) UnmarshalJSON

func (s *Audience) UnmarshalJSON(b []byte) error

UnmarshalJSON reads an audience from its JSON representation.

type Claims

type Claims struct {
	Issuer    string       `json:"iss,omitempty"`
	Subject   string       `json:"sub,omitempty"`
	Audience  Audience     `json:"aud,omitempty"`
	Expiry    *NumericDate `json:"exp,omitempty"`
	NotBefore *NumericDate `json:"nbf,omitempty"`
	IssuedAt  *NumericDate `json:"iat,omitempty"`
	ID        string       `json:"jti,omitempty"`

	// DPoP specific claims
	Cnf        *Cnf   `json:"cnf,omitempty"`
	Nonce      string `json:"nonce,omitempty"`
	HTTPMethod string `json:"htm,omitempty"`
	HTTPUri    string `json:"htu,omitempty"`

	// Custom most common claims
	Name          string `json:"name,omitempty"`
	Profile       string `json:"profile,omitempty"`
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"email_verified,omitempty"`
	Phone         string `json:"phone_number,omitempty"`
	PhoneVerified bool   `json:"phone_number_verified,omitempty"`
	// Role in the service
	Role   string `json:"role,omitempty"`
	Tenant string `json:"tenant,omitempty"`
	Org    string `json:"org,omitempty"`
	// map of Org:Role
	Orgs    map[string]string `json:"orgs,omitempty"`
	OrgRole string            `json:"org_role,omitempty"`
	Scope   Audience          `json:"scope,omitempty"`
}

Claims represents public claim values (as specified in RFC 7519).

func (*Claims) Marshal

func (c *Claims) Marshal() string

Marshal returns JSON encoded string

func (*Claims) Valid

func (c *Claims) Valid(cfg *VerifyConfig) error

Valid returns error if the standard claims are invalid

func (*Claims) VerifyAudience

func (c *Claims) VerifyAudience(expected []string) error

VerifyAudience compares the aud claim against expected.

func (*Claims) VerifyExpiresAt

func (c *Claims) VerifyExpiresAt(now time.Time, req bool) error

VerifyExpiresAt returns true issued at is valid.

func (*Claims) VerifyIssuedAt

func (c *Claims) VerifyIssuedAt(now time.Time, req bool) error

VerifyIssuedAt verifies the iat claim.

func (*Claims) VerifyIssuer

func (c *Claims) VerifyIssuer(expected string) error

VerifyIssuer compares the iss claim against expected.

func (*Claims) VerifyNotBefore

func (c *Claims) VerifyNotBefore(now time.Time, req bool) error

VerifyNotBefore verifies the nbf claim.

func (*Claims) VerifySubject

func (c *Claims) VerifySubject(expected string) error

VerifySubject compares the sub claim against expected.

type Cnf

type Cnf struct {
	Jkt string `json:"jkt,omitempty"`
}

Cnf is DPoP specific claim for JWT Key ID

type Key

type Key struct {
	// ID of the key
	ID   string `json:"id" yaml:"id"`
	Seed string `json:"seed" yaml:"seed"`
}

Key for JWT signature

type KeySet

type KeySet interface {
	// GetKey returns the key to verify a token with the given kid header.
	// An empty keyID selects the only signing-eligible key, if there is
	// exactly one.
	GetKey(ctx context.Context, keyID string) (any, error)
}

KeySet is an interface for verifying JWT signatures.

type Keyfunc

type Keyfunc func(*Token) (any, error)

Keyfunc is a callback function to supply the key for verification. The function receives the parsed, but unverified Token. This allows you to use properties in the Header of the token (such as `kid`) to identify which key to use.

type MapClaims

type MapClaims map[string]any

MapClaims provides generic claims on map

func CreateClaims

func CreateClaims(jti, subject, issuer string, audience []string, expiry time.Duration, extraClaims MapClaims) MapClaims

CreateClaims returns claims

func (MapClaims) Add

func (c MapClaims) Add(val ...any) error

Add new claims to the map

func (MapClaims) Bool

func (c MapClaims) Bool(k string) bool

Bool will return the named claim as Bool

func (MapClaims) CNF

func (c MapClaims) CNF() *Cnf

CNF returns DPoP cnf claim

func (MapClaims) Int

func (c MapClaims) Int(k string) int

Int will return the named claim as an int. Values that do not fit in an int, or cannot be parsed, return 0.

func (MapClaims) Int64

func (c MapClaims) Int64(k string) int64

Int64 will return the named claim as an int64. Values that do not fit in an int64, or cannot be parsed, return 0.

func (MapClaims) Marshal

func (c MapClaims) Marshal() string

Marshal returns JSON encoded string

func (MapClaims) NormalizeTimeClaims

func (c MapClaims) NormalizeTimeClaims() error

NormalizeTimeClaims replaces the exp, iat and nbf claims present in c by their Unix seconds, so that a time.Time, a *NumericDate or an RFC 3339 string is serialized as the NumericDate that Valid checks (XPKI-109). A value that Time cannot parse, or a zero time, is an error, and c is then unchanged. Signers call it on a copy of the caller's claims.

func (MapClaims) String

func (c MapClaims) String(k string) string

String will return the named claim as a string, if the underlying type is not a string, it will try and coerce it to a string.

func (MapClaims) Strings

func (c MapClaims) Strings(k string) []string

Strings will return the named claim as a []string

func (MapClaims) StringsMap

func (c MapClaims) StringsMap(k string) map[string]string

StringsMap will return the named claim as a map[string]string,

func (MapClaims) Time

func (c MapClaims) Time(k string) *time.Time

Time will return the named claim as Time pointer. It is nil when the claim is absent, and when it is present but not a time (logged at DEBUG); the Verify methods and Valid reject the latter (XPKI-125).

func (MapClaims) TimeVal

func (c MapClaims) TimeVal(k string) time.Time

TimeVal will return the named claim as Time value

func (MapClaims) To

func (c MapClaims) To(val any) error

To converts the claims to the value pointed to by v.

func (MapClaims) UInt64

func (c MapClaims) UInt64(k string) uint64

UInt64 will return the named claim as an uint64. Negative values, values that do not fit in an uint64, or values that cannot be parsed, return 0.

func (MapClaims) Valid

func (c MapClaims) Valid(cfg *VerifyConfig) error

Valid returns error if the standard claims are invalid

func (MapClaims) VerifyAudience

func (c MapClaims) VerifyAudience(expected []string) error

VerifyAudience compares the aud claim against expected.

func (MapClaims) VerifyExpiresAt

func (c MapClaims) VerifyExpiresAt(now time.Time, req bool) error

VerifyExpiresAt verifies the exp claim. A present exp that is not a time is an error (XPKI-125), a missing one only with req.

func (MapClaims) VerifyIssuedAt

func (c MapClaims) VerifyIssuedAt(now time.Time, req bool) error

VerifyIssuedAt verifies the iat claim. A present iat that is not a time is an error (XPKI-125), a missing one only with req.

func (MapClaims) VerifyIssuer

func (c MapClaims) VerifyIssuer(expected string) error

VerifyIssuer compares the iss claim against expected.

func (MapClaims) VerifyNotBefore

func (c MapClaims) VerifyNotBefore(now time.Time, req bool) error

VerifyNotBefore verifies the nbf claim. A present nbf that is not a time is an error (XPKI-125), a missing one only with req.

func (MapClaims) VerifySubject

func (c MapClaims) VerifySubject(expected string) error

VerifySubject compares the sub claim against expected.

type NumericDate

type NumericDate int64

NumericDate represents date and time as the number of seconds since the epoch, ignoring leap seconds. Non-integer values can be represented in the serialized format (RFC 7519 Section 2); they are accepted on input and truncated to whole seconds, and always serialized as integers. See RFC7519 Section 2: https://tools.ietf.org/html/rfc7519#section-2

func NewNumericDate

func NewNumericDate(t time.Time) *NumericDate

NewNumericDate constructs NumericDate from time.Time value.

func (NumericDate) MarshalJSON

func (n NumericDate) MarshalJSON() ([]byte, error)

MarshalJSON serializes the given NumericDate into its JSON representation.

func (*NumericDate) Time

func (n *NumericDate) Time() time.Time

Time returns time.Time representation of NumericDate.

func (*NumericDate) UnmarshalJSON

func (n *NumericDate) UnmarshalJSON(b []byte) error

UnmarshalJSON reads a date from its JSON representation. Integer and fractional values are accepted, quoted or not; a fractional value is truncated toward zero to whole seconds.

type Option

type Option interface {
	// contains filtered or unexported methods
}

A Option modifies the default behavior of Provider.

func WithHeaders

func WithHeaders(headers map[string]any) Option

WithHeaders adds JOSE headers to signed tokens or overrides the defaults, such as typ. The constructor rejects an alg header that differs from the signing algorithm, and a kid header that would stop the provider from verifying its own tokens: with configured HS256 keys it must be the signing key's ID, and for NewProviderWithSymmetricKey it must be a nonempty string.

type Parser

type Parser interface {
	// ParseToken verifies the token signature and standard claims and returns MapClaims
	ParseToken(ctx context.Context, token string, cfg *VerifyConfig) (MapClaims, error)

	// GetRevocation returns the revocation checker, or nil if none is set
	GetRevocation() Revocation
	// SetRevocation installs a revocation checker consulted by ParseToken
	SetRevocation(Revocation)
}

Parser specifies JWT parser interface

func NewParser

func NewParser(cfg *ParserConfig) (Parser, error)

NewParser returns a Parser that verifies tokens with cfg.JWKeySet, or with the JWKS document at cfg.JWKSURI, fetched by a RemoteKeySet configured by cfg.JWKSClient. Create one Parser per configuration and reuse it, so its key cache is shared.

type ParserConfig

type ParserConfig struct {
	// Issuer specifies issuer claim
	Issuer string `json:"issuer" yaml:"issuer"`
	// JWKSURI is the URL of the JWKS document that NewParser verifies with,
	// through a RemoteKeySet, when JWKeySet is not set.
	JWKSURI string `json:"jwks_uri" yaml:"jwks_uri"`
	// JWKeySet is a static key set; it takes precedence over JWKSURI.
	JWKeySet *jose.JSONWebKeySet `json:"jwks" yaml:"jwks"`
	// JWKSClient tunes the RemoteKeySet that NewParser creates for JWKSURI.
	// Nil keeps every default.
	JWKSClient *RemoteKeySetConfig `json:"jwks_client,omitempty" yaml:"jwks_client,omitempty"`
}

ParserConfig provides JWT parser configuration

func LoadParserConfig

func LoadParserConfig(file string) (*ParserConfig, error)

LoadParserConfig returns parser configuration loaded from a file

type Provider

type Provider interface {
	Signer
	Parser
}

Provider specifies JWT provider interface

func LoadProvider

func LoadProvider(ctx context.Context, cfgfile string, crypto *cryptoprov.Crypto) (Provider, error)

LoadProvider returns new provider from the configuration in cfgfile, see NewProvider.

func MustNewProvider

func MustNewProvider(ctx context.Context, cfg *ProviderConfig, crypto *cryptoprov.Crypto, ops ...Option) Provider

MustNewProvider returns new provider, see NewProvider, and panics when it cannot be created.

func NewProvider

func NewProvider(ctx context.Context, cfg *ProviderConfig, crypto *cryptoprov.Crypto, ops ...Option) (Provider, error)

NewProvider returns new provider that supports, both Signer and Parser. ctx is for the crypto provider that resolves a pkcs11: URI in cfg.PrivateKey (cryptoprov.Crypto.LoadPrivateKey); it is not kept.

func NewProviderFromCryptoSigner

func NewProviderFromCryptoSigner(signer crypto.Signer, ops ...Option) (Provider, error)

NewProviderFromCryptoSigner returns new from Signer

func NewProviderWithSymmetricKey

func NewProviderWithSymmetricKey(key []byte, ops ...Option) (Provider, error)

NewProviderWithSymmetricKey returns a provider that signs HS256 tokens with key and verifies its own tokens.

Tokens carry no kid header unless WithHeaders sets one, which must be a nonempty string. ParseToken accepts only HS256 tokens signed with key that have no kid or that kid; any other kid, including an empty or non-string one, is rejected (XPKI-066, XPKI-104).

type ProviderConfig

type ProviderConfig struct {
	// Issuer specifies issuer claim
	Issuer string `json:"issuer" yaml:"issuer"`
	// KeyID specifies ID of the current key
	KeyID string `json:"kid" yaml:"kid"`
	// Keys specifies list of issuer's keys
	Keys []*Key `json:"keys" yaml:"keys"`

	// PrivateKey is a PEM-encoded key or a pkcs11: URI resolved through cryptoprov;
	// when set, the provider signs with RS*, ES* or ML-DSA-*, by the key,
	// instead of HS256 keys
	PrivateKey string `json:"private_key" yaml:"private_key"`

	// TokenExpiry specifies token expiration period
	TokenExpiry csr.Duration `json:"token_expiry" yaml:"token_expiry"`
}

ProviderConfig provides OAuth2 configuration

func LoadProviderConfig

func LoadProviderConfig(file string) (*ProviderConfig, error)

LoadProviderConfig returns provider configuration loaded from a file

type RemoteKeySet

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

RemoteKeySet is a KeySet implementation that validates JSON web tokens against a jwks_uri endpoint. Key selection follows the StaticKeySet rules for KeySet entries. Create it with NewRemoteKeySet, which describes how keys are cached and refreshed.

func NewRemoteKeySet

func NewRemoteKeySet(ctx context.Context, jwksURL string, opts ...RemoteKeySetOption) *RemoteKeySet

NewRemoteKeySet returns a KeySet that fetches a JWKS document from jwksURL over HTTP. NewParser uses it when ParserConfig.JWKSURI is set.

Keys are fetched on the first lookup and cached for the lifetime that the response states (Cache-Control max-age, else Expires; no-cache and no-store state a lifetime of zero) less the age of the response (the greater of its Age header and the time since its Date), bounded by WithMinCacheTTL and WithMaxCacheTTL, and never shorter than the refresh cooldown. A lookup in the last quarter of that lifetime starts a refresh in the background and still uses the cached keys, so keys added to the document are picked up and removed keys stop being accepted without a lookup waiting for the endpoint. A lookup after the expiry waits for a refresh. Once a refresh in the last quarter or after the expiry has failed, the expired keys stay in use for WithStaleIfError, and every lookup that still uses them starts another background refresh once the cooldown has passed.

A lookup that no usable cached key fits also refreshes, waiting for the result. Concurrent refreshes are coalesced, and a refresh of any kind starts at most once per refresh cooldown. ctx bounds the lifetime of every fetch; each fetch is also bounded by the fetch timeout and response size limit. A RemoteKeySet starts no goroutine when it is not used. Reuse one RemoteKeySet per URL rather than creating new ones.

func (*RemoteKeySet) GetKey

func (r *RemoteKeySet) GetKey(ctx context.Context, keyID string) (any, error)

GetKey returns the public key for the given kid.

func (*RemoteKeySet) GetKeyForAlgorithm

func (r *RemoteKeySet) GetKeyForAlgorithm(ctx context.Context, keyID, alg string) (any, error)

GetKeyForAlgorithm returns the public key for the given kid and alg.

type RemoteKeySetConfig added in v2.0.328

type RemoteKeySetConfig struct {
	// RefreshCooldown is WithRefreshCooldown; "0s" disables throttling.
	RefreshCooldown *csr.Duration `json:"refresh_cooldown,omitempty" yaml:"refresh_cooldown,omitempty"`
	// FetchTimeout is WithFetchTimeout.
	FetchTimeout csr.Duration `json:"fetch_timeout,omitempty" yaml:"fetch_timeout,omitempty"`
	// MaxResponseSize is WithMaxResponseSize, in bytes.
	MaxResponseSize int64 `json:"max_response_size,omitempty" yaml:"max_response_size,omitempty"`
	// MinCacheTTL is WithMinCacheTTL.
	MinCacheTTL csr.Duration `json:"min_cache_ttl,omitempty" yaml:"min_cache_ttl,omitempty"`
	// MaxCacheTTL is WithMaxCacheTTL.
	MaxCacheTTL csr.Duration `json:"max_cache_ttl,omitempty" yaml:"max_cache_ttl,omitempty"`
	// StaleIfError is WithStaleIfError; "0s" fails lookups as soon as the
	// keys expire and a refresh has failed.
	StaleIfError *csr.Duration `json:"stale_if_error,omitempty" yaml:"stale_if_error,omitempty"`
}

RemoteKeySetConfig is the configuration file form of the RemoteKeySetOptions. An absent field keeps the default of its option, and so does zero in a field that is not a pointer; any other value, a negative one included, is passed to the option.

func (*RemoteKeySetConfig) Options added in v2.0.328

func (c *RemoteKeySetConfig) Options() []RemoteKeySetOption

Options returns the RemoteKeySetOptions that c configures, for NewRemoteKeySet. A nil c returns none.

type RemoteKeySetOption

type RemoteKeySetOption func(*RemoteKeySet)

RemoteKeySetOption configures a RemoteKeySet.

func WithFetchTimeout

func WithFetchTimeout(d time.Duration) RemoteKeySetOption

WithFetchTimeout bounds each fetch, including reading the body. Zero or negative keeps DefaultJWKSFetchTimeout.

func WithHTTPClient

func WithHTTPClient(client *http.Client) RemoteKeySetOption

WithHTTPClient sets the client used to fetch the JWKS document. The fetch timeout still applies to each request. A nil client keeps the default.

func WithMaxCacheTTL added in v2.0.328

func WithMaxCacheTTL(d time.Duration) RemoteKeySetOption

WithMaxCacheTTL sets the longest lifetime of a fetched JWKS document, which is also its lifetime when the response states none. Unless the refresh cooldown is longer, it bounds how long a key removed from the document is still accepted while the endpoint answers; a lookup that uses keys kept by WithStaleIfError can add the duration of one fetch. Zero or negative keeps DefaultJWKSMaxCacheTTL.

func WithMaxResponseSize

func WithMaxResponseSize(n int64) RemoteKeySetOption

WithMaxResponseSize sets the largest accepted JWKS document in bytes. Zero or negative keeps DefaultJWKSMaxResponseSize.

func WithMinCacheTTL added in v2.0.328

func WithMinCacheTTL(d time.Duration) RemoteKeySetOption

WithMinCacheTTL sets the shortest lifetime of a fetched JWKS document, so a response with "Cache-Control: no-cache" or a short max-age does not cause a fetch on every lookup. Zero or negative keeps DefaultJWKSMinCacheTTL. A value above the maximum lifetime is lowered to it.

func WithRefreshCooldown

func WithRefreshCooldown(d time.Duration) RemoteKeySetOption

WithRefreshCooldown sets the minimum interval between the end of one fetch and the start of the next; lookups for unknown kids inside that window use the cached keys. Zero or negative disables throttling. The default is DefaultJWKSRefreshCooldown.

func WithStaleIfError added in v2.0.328

func WithStaleIfError(d time.Duration) RemoteKeySetOption

WithStaleIfError sets how long after their expiry the cached keys stay in use once a refresh in the last quarter of their lifetime, or after it, has failed; after that, lookups fail with the fetch error until a refresh succeeds. A fetch that fails earlier, for a kid that is not cached, does not count. Zero or negative fails lookups as soon as the keys expire and a refresh has failed. The default is DefaultJWKSStaleIfError.

type Revocation

type Revocation interface {
	// Validate validates token claims,
	// it can be used to validate token revocation, etc.
	Validate(ctx context.Context, token string, claims MapClaims) error
	// Revoke revokes token
	Revoke(ctx context.Context, token string, claims MapClaims) error
}

Revocation is an optional hook consulted by Parser.ParseToken after a token is verified, and used by callers to revoke tokens.

type Signer

type Signer interface {
	// Sign returns a signed, compact-serialized JWT for the claims. The exp,
	// iat and nbf claims are written as NumericDate whatever their Go type,
	// time.Time included, see MapClaims.NormalizeTimeClaims; one that
	// MapClaims.Time cannot parse is an error. The claims map is not
	// modified. ctx bounds the signature of the key
	// (cryptoprov.SignContext): a KMS request or the wait for a PKCS#11
	// session ends with it.
	Sign(ctx context.Context, claims MapClaims) (string, error)
	// PublicKey is returned for asymmetric signer
	PublicKey() crypto.PublicKey
	// Issuer returns name of the issuer
	Issuer() string
	// TokenExpiry specifies token expiration period
	TokenExpiry() time.Duration
}

Signer specifies JWT signer interface

type SignerInfo

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

SignerInfo represents JWT signer

func NewSignerInfo

func NewSignerInfo(signer crypto.Signer) (*SignerInfo, error)

NewSignerInfo returns the *SignerInfo of signer, which selects the algorithm from the key: RS* by RSA key size, ES* by curve, HS* for a symmetric signer, and for an ML-DSA key the RFC 9964 algorithm of its parameter set, ML-DSA-44, ML-DSA-65 or ML-DSA-87.

type StaticKeySet

type StaticKeySet struct {
	// PublicKeys used to verify the JWT. They have no kid, see StaticKeySet.
	// Supported types are *rsa.PublicKey, *ecdsa.PublicKey and
	// *mldsa.PublicKey; any other entry, or an uninitialized ML-DSA key, makes
	// GetKey fail.
	PublicKeys []crypto.PublicKey
	KeySet     []jose.JSONWebKey
}

StaticKeySet is a verifier that validates JWT against a static set of public keys.

A key is eligible when its JWK "use" is empty or "sig" and, when the token algorithm is known, its type, curve and JWK "alg" fit that algorithm. A token kid selects KeySet entries with that KeyID; when none has it, PublicKeys entries whose RFC 7638 SHA-256 thumbprint (base64url) equals the kid. An empty kid considers every entry of both lists. Exactly one eligible key must remain, otherwise GetKey returns ErrKeyNotFound or ErrAmbiguousKey.

func (*StaticKeySet) GetKey

func (s *StaticKeySet) GetKey(ctx context.Context, keyID string) (any, error)

GetKey returns the public key for the given kid.

func (*StaticKeySet) GetKeyForAlgorithm

func (s *StaticKeySet) GetKeyForAlgorithm(_ context.Context, keyID, alg string) (any, error)

GetKeyForAlgorithm returns the public key for the given kid and alg.

type Token

type Token struct {
	Raw           string         // The raw token.  Populated when you Parse a token
	SigningMethod string         // The signing method used or to be used
	Header        map[string]any // The first segment of the token
	Claims        ValidClaims    // The second segment of the token
	Signature     string         // The third segment of the token.  Populated when you Parse a token
	Valid         bool           // Is the token valid?  Populated when you Parse/Verify a token
}

Token for JWT

type TokenParser

type TokenParser struct {
	ValidMethods         []string // If populated, only these methods will be considered valid
	UseJSONNumber        bool     // Use JSON Number format in JSON decoder
	SkipClaimsValidation bool     // Skip claims validation during token parsing
}

TokenParser config

func (*TokenParser) Parse

func (p *TokenParser) Parse(tokenString string, cfg *VerifyConfig, keyFunc Keyfunc) (*Token, error)

Parse parses and validates JWT, and return a token. keyFunc will receive the parsed token and should return the key for validating. If everything is kosher, err will be nil

func (*TokenParser) ParseUnverified

func (p *TokenParser) ParseUnverified(tokenString string, claims MapClaims) (token *Token, parts []string, err error)

ParseUnverified parses the token but doesn't validate the signature. It's only ever useful in cases where you know the signature is valid (because it has been checked previously in the stack) and you want to extract values from it. WARNING: Don't use this method unless you know what you're doing

func (*TokenParser) ParseWithClaims

func (p *TokenParser) ParseWithClaims(tokenString string, cfg *VerifyConfig, claims MapClaims, keyFunc Keyfunc) (*Token, error)

ParseWithClaims parses token with a specified Claims

type ValidClaims

type ValidClaims interface {
	Valid(cfg *VerifyConfig) error
}

ValidClaims interface for Claims validation

type VerifyConfig

type VerifyConfig struct {
	// ExpectedIssuer validates the iss claim of a JWT matches this value
	ExpectedIssuer string
	// ExpectedSubject validates the sub claim of a JWT matches this value
	ExpectedSubject string
	// ExpectedAudience validates that the aud claim of a JWT contains this value
	ExpectedAudience []string
}

VerifyConfig expresses the possible options for validating a JWT

Directories

Path Synopsis
Package accesstoken wraps a jwt.Provider and a dataprotection.Provider to issue opaque encrypted access tokens of the form "pat.<base64url(AES-GCM (claims))>" while still parsing plain JWTs through the inner provider.
Package accesstoken wraps a jwt.Provider and a dataprotection.Provider to issue opaque encrypted access tokens of the form "pat.<base64url(AES-GCM (claims))>" while still parsing plain JWTs through the inner provider.
Package dpop implements OAuth 2.0 Demonstrating Proof of Possession (RFC 9449): clients build DPoP proof JWTs for HTTP requests with Signer and ForRequest; servers verify them with VerifyRequestClaims or VerifyClaimsContext and bind the resulting key thumbprint to the access token "cnf.jkt" claim.
Package dpop implements OAuth 2.0 Demonstrating Proof of Possession (RFC 9449): clients build DPoP proof JWTs for HTTP requests with Signer and ForRequest; servers verify them with VerifyRequestClaims or VerifyClaimsContext and bind the resulting key thumbprint to the access token "cnf.jkt" claim.
Package oauth2client holds the configuration model and registry for OAuth2 and OpenID Connect identity-provider clients, looked up by provider id, email or email domain, and a helper to build token-endpoint requests.
Package oauth2client holds the configuration model and registry for OAuth2 and OpenID Connect identity-provider clients, looked up by provider id, email or email domain, and a helper to build token-endpoint requests.

Jump to

Keyboard shortcuts

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