Documentation
¶
Overview ¶
Package jwt is a single-package JWT/JOSE library.
It covers JWS signing and verification (HMAC, RSA-PSS sign / PKCS#1 v1.5 verify, ECDSA, Ed25519), JWE encryption and decryption (RSA-OAEP-256, ECDH-ES(+A256KW), A256KW, dir with AES-GCM), the RFC 7519 claim model, the full RFC 7515 JOSE header, JWK / JWKS handling with pluggable key resolution (KeyProvider, KeySet, KeyFetcher), RFC 7638 thumbprints, OIDC standard and provider claim sets, the RFC 9068 access-token profile, opaque-token utilities, revocation (RevocationStore), per-encoding key material parsers, and a thin RFC 6750 bearer adapter.
Verification is mandatory-allowlist by construction: Parse and every Decrypter reject any algorithm the caller did not permit, and alg:none is never representable. See spec.md for the full design and RFC matrix.
Index ¶
- Constants
- Variables
- func BearerToken(r *http.Request) (string, bool)
- func ClaimsFromContext[C any](ctx context.Context, dst *C) error
- func DecryptClaims[C any](ctx context.Context, compact string, dst *C, dec Decrypter, ...) error
- func DiscoverJWKSURI(ctx context.Context, issuer string, client *http.Client) (string, error)
- func EncryptClaims[C any](claims C, enc Encrypter) (string, error)
- func Equal(storedHash, raw string) bool
- func Hash(raw string) string
- func Middleware(keys KeyProvider, opts ...ParseOption) func(http.Handler) http.Handler
- func Parse[C any](ctx context.Context, token string, dst *C, keys KeyProvider, ...) error
- func ParseEd25519PrivateKeyExpanded(raw []byte) (ed25519.PrivateKey, error)
- func ParseEd25519PrivateKeySeed(seed []byte) (ed25519.PrivateKey, error)
- func ParseEd25519PublicKey(raw []byte) (ed25519.PublicKey, error)
- func ParseInsecure[C any](token string, dst *C) error
- func ParseOpenSSHPrivateKey(raw []byte) (crypto.Signer, error)
- func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
- func ParsePKCS8PrivateKey(der []byte) (crypto.Signer, error)
- func ParsePKIXPublicKey(der []byte) (crypto.PublicKey, error)
- func ParseSEC1ECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
- func Sign[C any](claims C, signer Signer, opts ...SignOption) (string, error)
- func Thumbprint(k Key, hash ...crypto.Hash) (string, error)
- func ThumbprintBytes(kty KeyType, raw []byte, hash ...crypto.Hash) (string, error)
- func ValidateAccessTokenClaims(claims AccessTokenClaims) error
- func WriteChallenge(w http.ResponseWriter, realm string, err error)
- type AccessTokenClaims
- type Address
- type Algorithm
- type Audience
- type Confirmation
- type ContentAlgorithm
- type Decrypter
- func NewA256KWDecrypter(kek []byte, kid ...string) (Decrypter, error)
- func NewDirectDecrypter(cek []byte, kid ...string) (Decrypter, error)
- func NewECDHESDecrypter(priv *ecdsa.PrivateKey, kid ...string) (Decrypter, error)
- func NewRSAOAEP256Decrypter(priv *rsa.PrivateKey, kid ...string) (Decrypter, error)
- type Encrypter
- func NewA256KWEncrypter(kek []byte, content ContentAlgorithm, kid ...string) (Encrypter, error)
- func NewDirectEncrypter(cek []byte, content ContentAlgorithm, kid ...string) (Encrypter, error)
- func NewECDHESEncrypter(pub *ecdsa.PublicKey, alg KeyAlgorithm, content ContentAlgorithm, ...) (Encrypter, error)
- func NewRSAOAEP256Encrypter(pub *rsa.PublicKey, content ContentAlgorithm, kid ...string) (Encrypter, error)
- type EntraClaims
- type EntraIDToken
- type FetcherOption
- type GoogleClaims
- type GoogleIDToken
- type Header
- type Key
- type KeyAlgorithm
- type KeyFetcher
- type KeyProvider
- type KeySet
- type KeyType
- type NumericDate
- type OktaClaims
- type OktaIDToken
- type OpaqueToken
- type ParseOption
- func WithAllowedAlgorithms(algs ...Algorithm) ParseOption
- func WithAudience(aud string) ParseOption
- func WithClock(now func() time.Time) ParseOption
- func WithIssuer(iss string) ParseOption
- func WithLeeway(d time.Duration) ParseOption
- func WithRequiredClaims(names ...string) ParseOption
- func WithRequiredType(typ string) ParseOption
- type ParseOptions
- type RegisteredClaims
- type RevocationReason
- type RevocationStore
- type RotationResult
- type SignOption
- type SignOptions
- type Signer
- func NewECDSASigner(alg Algorithm, key *ecdsa.PrivateKey, kid ...string) (Signer, error)
- func NewEd25519Signer(key ed25519.PrivateKey, kid ...string) (Signer, error)
- func NewHMACSigner(alg Algorithm, key []byte, kid ...string) (Signer, error)
- func NewRSAPSSSigner(alg Algorithm, key *rsa.PrivateKey, kid ...string) (Signer, error)
- type StandardClaims
- type TokenFamily
- type Verifier
- func NewECDSAVerifier(alg Algorithm, key *ecdsa.PublicKey, kid ...string) (Verifier, error)
- func NewEd25519Verifier(key ed25519.PublicKey, kid ...string) (Verifier, error)
- func NewHMACVerifier(alg Algorithm, key []byte, kid ...string) (Verifier, error)
- func NewRSAPKCS1Verifier(alg Algorithm, key *rsa.PublicKey, kid ...string) (Verifier, error)
- func NewRSAPSSVerifier(alg Algorithm, key *rsa.PublicKey, kid ...string) (Verifier, error)
Constants ¶
const AccessTokenType = "at+jwt"
AccessTokenType is the mandatory "typ" header value per RFC 9068 §2.1, intended for use with WithRequiredType.
const DefaultType = "JWT"
DefaultType is the "typ" header value Sign stamps on a token unless WithType overrides it: the RFC 7519 §5.1 recommended media type, also satisfying the explicit-typing guidance of RFC 8725 §3.11. For an RFC 9068 access token pass WithType(AccessTokenType).
Variables ¶
var ( ErrInvalidSignature = internalalg.ErrInvalidSignature ErrExpired = errors.New("jwt: token expired") ErrNotYetValid = errors.New("jwt: token not yet valid") ErrIssuerMismatch = errors.New("jwt: issuer mismatch") ErrAudienceMismatch = errors.New("jwt: audience mismatch") ErrAlgorithmNotAllowed = errors.New("jwt: algorithm not in allowlist") ErrNoAllowedAlgorithms = errors.New("jwt: WithAllowedAlgorithms is required") ErrMissingClaim = errors.New("jwt: required claim missing") ErrMalformedToken = errors.New("jwt: malformed token") ErrTypeMismatch = errors.New("jwt: unexpected \"typ\" header") // Sentinels beyond the §5.1 list, needed by the constructors and the // key-resolution path. ErrWeakKey = internalalg.ErrWeakKey ErrUnsupportedAlgorithm = internalalg.ErrUnsupportedAlgorithm ErrKeyNotFound = errors.New("jwt: no key for kid") ErrKeyTypeMismatch = internalalg.ErrKeyTypeMismatch ErrMalformedKey = internalalg.ErrMalformedKey ErrOctNotServable = errors.New("jwt: oct keys must not be serialized into a JWKS document") )
Sentinel errors. All are comparable with errors.Is (spec §6.3).
var ErrDecryptionFailed = errors.New("jwt: decryption failed")
ErrDecryptionFailed is the single, generic error every decryption failure resolves to: a bad tag, a bad wrapped key, a malformed token or an algorithm mismatch are deliberately indistinguishable (spec §4.7).
var ErrNoClaimsInContext = errors.New("jwt: no verified claims in context")
ErrNoClaimsInContext is returned by ClaimsFromContext when the request did not pass through Middleware.
Functions ¶
func BearerToken ¶
BearerToken extracts the credential from an "Authorization: Bearer <token>" header (RFC 6750 §2.1). The scheme match is case-insensitive; exactly one space separates it from the token, which must be non-empty and contain no whitespace.
func ClaimsFromContext ¶
ClaimsFromContext unmarshals the verified payload that Middleware stored on the request context into dst (a pointer to any claims struct; its type is inferred, so no explicit type argument):
var claims MyClaims
if err := jwt.ClaimsFromContext(r.Context(), &claims); err != nil { ... }
func DecryptClaims ¶
func DecryptClaims[C any](ctx context.Context, compact string, dst *C, dec Decrypter, opts ...ParseOption) error
DecryptClaims is the JWE analogue of Parse: decrypt a compact JWE, validate its registered claims per opts, and unmarshal the plaintext into dst (its type is inferred; no explicit type argument). The AEAD tag is verified before any plaintext is exposed (spec §4.7). Header "typ" checking (WithRequiredType) does not apply here.
func DiscoverJWKSURI ¶
DiscoverJWKSURI resolves a JWKS URI from an issuer's OIDC/OAuth discovery document (<issuer>/.well-known/openid-configuration). If that document cannot be fetched or lacks "jwks_uri", it falls back to the conventional <issuer>/.well-known/jwks.json. A nil client uses http.DefaultClient.
func EncryptClaims ¶
EncryptClaims is the JWE analogue of Sign: JSON-marshal a claims value (any struct that marshals to an object) and encrypt it as a compact JWE.
func Equal ¶
Equal reports whether raw hashes to storedHash, comparing in constant time (crypto/subtle) to avoid leaking the digest through timing.
func Middleware ¶
func Middleware(keys KeyProvider, opts ...ParseOption) func(http.Handler) http.Handler
Middleware verifies the request's bearer token with keys and opts, then stores the verified payload on the request context for ClaimsFromContext to decode. On any failure it writes an RFC 6750 §3 challenge via WriteChallenge and does not call next.
func Parse ¶
func Parse[C any](ctx context.Context, token string, dst *C, keys KeyProvider, opts ...ParseOption) error
Parse decodes a compact JWS, verifies its signature with a key resolved from keys, validates the registered claims per opts, and unmarshals the payload into dst (a pointer to any struct; embed RegisteredClaims to read the registered members). dst's type is inferred, so calls carry no explicit type argument:
var claims MyClaims err := jwt.Parse(ctx, token, &claims, keys, jwt.WithAllowedAlgorithms(jwt.EdDSA))
Registered-claim validation runs regardless of what dst models. WithAllowedAlgorithms is mandatory (RFC 8725 §3.1); Parse returns ErrNoAllowedAlgorithms if no usable algorithm is supplied.
func ParseEd25519PrivateKeyExpanded ¶
func ParseEd25519PrivateKeyExpanded(raw []byte) (ed25519.PrivateKey, error)
ParseEd25519PrivateKeyExpanded parses a raw expanded Ed25519 private key.
func ParseEd25519PrivateKeySeed ¶
func ParseEd25519PrivateKeySeed(seed []byte) (ed25519.PrivateKey, error)
ParseEd25519PrivateKeySeed parses a raw Ed25519 seed.
func ParseEd25519PublicKey ¶
ParseEd25519PublicKey parses a raw Ed25519 public key.
func ParseInsecure ¶
ParseInsecure decodes the payload into dst WITHOUT verifying the signature or checking expiry. Its result MUST NOT drive any authorization decision — read-only inspection only (e.g. looking up a session by an expired token's "jti"). dst's type is inferred; no explicit type argument.
func ParseOpenSSHPrivateKey ¶
ParseOpenSSHPrivateKey parses an unencrypted OpenSSH private key blob.
func ParsePKCS1PrivateKey ¶
func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
ParsePKCS1PrivateKey parses a DER-encoded PKCS#1 RSA private key.
func ParsePKCS8PrivateKey ¶
ParsePKCS8PrivateKey parses a DER-encoded PKCS#8 private key.
func ParsePKIXPublicKey ¶
ParsePKIXPublicKey parses a DER-encoded PKIX public key.
func ParseSEC1ECPrivateKey ¶
func ParseSEC1ECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
ParseSEC1ECPrivateKey parses a DER-encoded SEC1 EC private key.
func Sign ¶
func Sign[C any](claims C, signer Signer, opts ...SignOption) (string, error)
Sign JSON-encodes claims — any value that marshals to a JSON object, most often a struct embedding RegisteredClaims — and produces a compact JWS (RFC 7515 §7.1). The generated header carries "alg", "typ" (DefaultType unless WithType is given), an optional "cty" from WithContentType, and — when the signer has one — "kid".
func Thumbprint ¶
Thumbprint computes the RFC 7638 JWK thumbprint of an already-parsed Key. hash is optional and defaults to SHA-256 (the hash behind the "jkt" confirmation value). The canonical form contains only the type-specific required members, with keys in lexicographic order and no whitespace (RFC 7638 §3).
func ThumbprintBytes ¶
ThumbprintBytes computes an RFC 7638-shaped thumbprint directly from raw key material the caller already holds, without a parsed Key. It supports the unambiguous single-blob key types: "oct" (raw is the secret) and "OKP" (raw is the 32-byte Ed25519 public key). RSA and EC keys have no single canonical byte form — use Thumbprint with a parsed Key for those. hash is optional and defaults to SHA-256.
func ValidateAccessTokenClaims ¶
func ValidateAccessTokenClaims(claims AccessTokenClaims) error
ValidateAccessTokenClaims checks the RFC 9068 §2.2 required-claims profile beyond what Parse already validates: iss, exp, aud, sub, client_id and iat MUST be present. (jti only SHOULD be present, so it is not enforced.)
func WriteChallenge ¶
func WriteChallenge(w http.ResponseWriter, realm string, err error)
WriteChallenge writes a "WWW-Authenticate: Bearer" response header per RFC 6750 §3 and sets the matching status code. A nil err yields a bare challenge (401, no error code) — the "credentials required" case. ErrMalformedToken maps to error="invalid_request" (400); every other verification failure maps to error="invalid_token" (401).
Types ¶
type AccessTokenClaims ¶
type AccessTokenClaims struct {
RegisteredClaims
ClientID string `json:"client_id"`
Scope string `json:"scope,omitempty"`
AuthTime *NumericDate `json:"auth_time,omitempty"`
ACR string `json:"acr,omitempty"`
AMR []string `json:"amr,omitempty"`
Groups []string `json:"groups,omitempty"`
Roles []string `json:"roles,omitempty"`
Entitlements []string `json:"entitlements,omitempty"`
}
AccessTokenClaims models the RFC 9068 JWT profile for OAuth 2.0 access tokens. The RFC 7519 registered claims are embedded and flattened into the same JSON object by encoding/json's normal anonymous-field promotion.
type Address ¶
type Address 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"`
}
Address is the OIDC Core 1.0 §5.1.1 address claim.
type Algorithm ¶
type Algorithm = internalalg.Algorithm
Algorithm identifies a JWA/EdDSA signing algorithm. It is an open string type, not a closed enum: callers may define custom algorithm values.
const ( HS256 Algorithm = internalalg.HS256 HS384 Algorithm = internalalg.HS384 HS512 Algorithm = internalalg.HS512 RS256 Algorithm = internalalg.RS256 RS384 Algorithm = internalalg.RS384 RS512 Algorithm = internalalg.RS512 PS256 Algorithm = internalalg.PS256 PS384 Algorithm = internalalg.PS384 PS512 Algorithm = internalalg.PS512 ES256 Algorithm = internalalg.ES256 ES384 Algorithm = internalalg.ES384 ES512 Algorithm = internalalg.ES512 EdDSA Algorithm = internalalg.EdDSA )
type Audience ¶
type Audience []string
Audience is RFC 7519 §4.1.3's audience claim: transparently (de)serialized from either a bare JSON string or a JSON array of strings.
func (Audience) MarshalJSON ¶
MarshalJSON emits a single-element audience as a bare string and any other length as a JSON array (RFC 7519 §4.1.3).
func (*Audience) UnmarshalJSON ¶
UnmarshalJSON accepts a bare string, a JSON array of strings, or null.
type Confirmation ¶
type Confirmation struct {
JWKThumbprint string `json:"jkt,omitempty"` // RFC 7800 §3.3 + RFC 7638
JWK *Key `json:"jwk,omitempty"` // RFC 7800 §3.2
}
Confirmation is the RFC 7800 §3 "cnf" claim, binding a token to a proof-of-possession key.
type ContentAlgorithm ¶
type ContentAlgorithm string
ContentAlgorithm identifies a JWE content-encryption algorithm (RFC 7518 §5). Only the AES-GCM family is offered (spec §3.1).
const ( A128GCM ContentAlgorithm = "A128GCM" A192GCM ContentAlgorithm = "A192GCM" A256GCM ContentAlgorithm = "A256GCM" )
type Decrypter ¶
type Decrypter interface {
// KeyID is the "kid" this decrypter's key material carries; empty if none.
KeyID() string
// Decrypt authenticates and decrypts compact, returning ErrDecryptionFailed
// on any problem (bad tag, wrong key, malformed token, algorithm mismatch).
Decrypt(ctx context.Context, compact string) (plaintext []byte, err error)
}
Decrypter consumes a compact JWE. It fails closed: the AEAD tag is checked before any plaintext is returned, and every failure yields ErrDecryptionFailed.
func NewA256KWDecrypter ¶
NewA256KWDecrypter unwraps the CEK of a JWE "alg":"A256KW" token.
func NewDirectDecrypter ¶
NewDirectDecrypter decrypts JWE "alg":"dir" tokens with a pre-shared CEK.
func NewECDHESDecrypter ¶
func NewECDHESDecrypter(priv *ecdsa.PrivateKey, kid ...string) (Decrypter, error)
NewECDHESDecrypter decrypts JWE tokens whose "alg" is ECDH-ES or ECDH-ES+A256KW, using an EC private key.
func NewRSAOAEP256Decrypter ¶
func NewRSAOAEP256Decrypter(priv *rsa.PrivateKey, kid ...string) (Decrypter, error)
NewRSAOAEP256Decrypter unwraps the CEK of a JWE "alg":"RSA-OAEP-256" token.
type Encrypter ¶
type Encrypter interface {
// KeyAlgorithm reports the "alg" (key-management) value written to the
// protected header.
KeyAlgorithm() KeyAlgorithm
// ContentAlgorithm reports the "enc" (content-encryption) value.
ContentAlgorithm() ContentAlgorithm
// KeyID is the "kid" written to the header; empty if none.
KeyID() string
// Encrypt returns the compact JWE for plaintext.
Encrypt(plaintext []byte) (compact string, err error)
}
Encrypter produces a compact JWE (RFC 7516 §7.1).
func NewA256KWEncrypter ¶
func NewA256KWEncrypter(kek []byte, content ContentAlgorithm, kid ...string) (Encrypter, error)
NewA256KWEncrypter wraps a fresh CEK under a 256-bit key-encryption key (JWE "alg":"A256KW").
func NewDirectEncrypter ¶
func NewDirectEncrypter(cek []byte, content ContentAlgorithm, kid ...string) (Encrypter, error)
NewDirectEncrypter uses a pre-shared content-encryption key directly (JWE "alg":"dir"). The key length must match content (16/24/32 bytes for A128/A192/A256GCM).
func NewECDHESEncrypter ¶
func NewECDHESEncrypter(pub *ecdsa.PublicKey, alg KeyAlgorithm, content ContentAlgorithm, kid ...string) (Encrypter, error)
NewECDHESEncrypter derives (ECDH-ES) or derives-and-wraps (ECDH-ES+A256KW) the CEK against an EC public key. alg must be ECDHES or ECDHESA256KW.
func NewRSAOAEP256Encrypter ¶
func NewRSAOAEP256Encrypter(pub *rsa.PublicKey, content ContentAlgorithm, kid ...string) (Encrypter, error)
NewRSAOAEP256Encrypter wraps a fresh CEK with RSA-OAEP using SHA-256 (JWE "alg":"RSA-OAEP-256"). Keys below 2048 bits are rejected (spec §4.6).
type EntraClaims ¶
type EntraClaims struct {
TenantID string `json:"tid,omitempty"`
ObjectID string `json:"oid,omitempty"`
UPN string `json:"upn,omitempty"`
Roles []string `json:"roles,omitempty"`
Groups []string `json:"groups,omitempty"`
AppID string `json:"appid,omitempty"`
Version string `json:"ver,omitempty"`
UniqueName string `json:"unique_name,omitempty"`
}
EntraClaims adds Microsoft Entra ID (Azure AD) specific claims. https://learn.microsoft.com/en-us/entra/identity-platform/id-token-claims-reference
type EntraIDToken ¶
type EntraIDToken struct {
RegisteredClaims
StandardClaims
EntraClaims
}
EntraIDToken is the Microsoft Entra ID equivalent of GoogleIDToken.
type FetcherOption ¶
type FetcherOption func(*KeyFetcher)
FetcherOption configures a KeyFetcher.
func WithHTTPClient ¶
func WithHTTPClient(c *http.Client) FetcherOption
WithHTTPClient sets the HTTP client used for JWKS and discovery requests.
func WithMaxResponseBytes ¶
func WithMaxResponseBytes(n int64) FetcherOption
WithMaxResponseBytes caps the JWKS response body size (default 1 MiB).
func WithMinRefreshInterval ¶
func WithMinRefreshInterval(d time.Duration) FetcherOption
WithMinRefreshInterval sets the shortest interval between network fetches triggered by a cache miss (default 1 minute). Refresh bypasses it.
type GoogleClaims ¶
type GoogleClaims struct {
HostedDomain string `json:"hd,omitempty"`
AuthorizedParty string `json:"azp,omitempty"`
AccessTokenHash string `json:"at_hash,omitempty"`
}
GoogleClaims adds Google-specific ID token claims. https://developers.google.com/identity/openid-connect/openid-connect#an-id-tokens-payload
type GoogleIDToken ¶
type GoogleIDToken struct {
RegisteredClaims
StandardClaims
GoogleClaims
}
GoogleIDToken is a ready-made ID-token claims struct for Google: registered + OIDC standard + Google claims, all flattened into one JSON object by struct embedding. Pass it straight to Parse:
var claims jwt.GoogleIDToken err := jwt.Parse(ctx, raw, &claims, keys, opts...) claims.Subject // registered claims.Email // standard claims.HostedDomain // Google
For a provider this library does not model, declare the same shape with your own claim set in place of GoogleClaims.
type Header ¶
type Header struct {
Algorithm Algorithm `json:"alg"`
Type string `json:"typ,omitempty"`
ContentType string `json:"cty,omitempty"`
KeyID string `json:"kid,omitempty"`
JWKSetURL string `json:"jku,omitempty"`
JWK *Key `json:"jwk,omitempty"`
X509URL string `json:"x5u,omitempty"`
X509CertChain []string `json:"x5c,omitempty"`
X509CertSHA1 string `json:"x5t,omitempty"`
X509CertSHA256 string `json:"x5t#S256,omitempty"`
Critical []string `json:"crit,omitempty"`
}
Header is the JOSE header (RFC 7515 §4.1), modeling every registered parameter. jku/x5u/jwk/x5c are parsed and readable but are NEVER automatically dereferenced or trusted to select a verification key (spec §4.8, RFC 8725 §3.9-3.10).
type Key ¶
type Key struct {
Kty KeyType
Kid string
Use string // "sig" | "enc"
Alg string
// contains filtered or unexported fields
}
Key is a single JSON Web Key (RFC 7517 §4). A Key with Kty == KeyTypeOct MUST NOT be serialized into a JWKS document served over HTTP, so MarshalJSON returns ErrOctNotServable for it (spec §5.3).
func FromECDSAPublicKey ¶
FromECDSAPublicKey builds a "sig" JWK from an ECDSA public key. If the point is invalid the coordinate fields are left empty and the failure surfaces later, at PublicKey/Verifier time.
func FromEd25519PublicKey ¶
FromEd25519PublicKey builds a "sig" JWK from an Ed25519 public key.
func FromHMACSecret ¶
FromHMACSecret builds a symmetric (kty "oct") JWK. Such a key cannot be marshaled into a servable JWKS document (see MarshalJSON).
func FromRSAPublicKey ¶
FromRSAPublicKey builds a "sig" JWK from an RSA public key.
func (Key) MarshalJSON ¶
MarshalJSON renders the key as an RFC 7517 JWK object. It returns ErrOctNotServable for symmetric keys so a symmetric secret can never be published in a discoverable keyset by accident.
func (*Key) UnmarshalJSON ¶
UnmarshalJSON parses an RFC 7517 JWK object.
type KeyAlgorithm ¶
type KeyAlgorithm string
KeyAlgorithm identifies a JWE key-management algorithm (RFC 7518 §4). Like Algorithm it is an open string type; the built-in constructors cover only the modern AEAD-friendly set (spec §3.1).
const ( ECDHES KeyAlgorithm = "ECDH-ES" // direct key agreement ECDHESA256KW KeyAlgorithm = "ECDH-ES+A256KW" // key agreement + AES key wrap RSAOAEP256 KeyAlgorithm = "RSA-OAEP-256" // RSA-OAEP with SHA-256 only A256KW KeyAlgorithm = "A256KW" // AES-256 Key Wrap Direct KeyAlgorithm = "dir" // pre-shared symmetric CEK )
type KeyFetcher ¶
type KeyFetcher struct {
// contains filtered or unexported fields
}
KeyFetcher retrieves and caches a remote JWKS document; it satisfies KeyProvider directly, so it plugs in wherever a KeySet would. HTTPS-only, size-capped, and it honours a Cache-Control: max-age hint when present.
func NewKeyFetcher ¶
func NewKeyFetcher(uri string, opts ...FetcherOption) *KeyFetcher
NewKeyFetcher returns a KeyFetcher for the given JWKS URI.
type KeyProvider ¶
type KeyProvider interface {
// Lookup returns the key for kid. The bool is false (with a nil error)
// when no such key exists; a non-nil error signals a backing-store
// failure and aborts Parse.
Lookup(ctx context.Context, kid string) (key Key, found bool, err error)
}
KeyProvider resolves a Key by "kid" (which may be empty, meaning "the only key"). Parse uses it to obtain the verification key for a token. A single fixed key and a full JWKS-backed store satisfy the same interface.
func MapKeyProvider ¶
func MapKeyProvider(byKID map[string]Key) KeyProvider
MapKeyProvider adapts a fixed set of Keys, keyed by kid. As with any KeyProvider, an empty requested kid resolves to the sole key when the map holds exactly one.
func StaticKeyProvider ¶
func StaticKeyProvider(k Key) KeyProvider
StaticKeyProvider adapts a single fixed Key — the common case where an application has exactly one signing key. A non-empty requested kid that does not match the key's own non-empty kid resolves to "not found".
type KeySet ¶
type KeySet struct {
// contains filtered or unexported fields
}
KeySet is a mutable, concurrency-safe KeyProvider (RFC 7517 §5's JWK Set) — the library's built-in in-memory implementation. Insertion order is preserved for serving as a JWKS document.
func ParseKeySet ¶
ParseKeySet parses a JWKS document ({"keys":[ ... ]}) into a ready-to-use KeySet. Unlike many hand-rolled parsers it does not silently drop keys it cannot fully interpret: a malformed member is an error.
func (*KeySet) Lookup ¶
Lookup resolves a key by kid. An empty kid matches a sole key (or a sole key that itself has no kid); it is ambiguous when the set holds several keys, and Lookup then reports not-found rather than guessing.
func (*KeySet) MarshalJSON ¶
MarshalJSON renders the set as an RFC 7517 §5 JWK Set document. It fails if any contained key refuses to marshal (e.g. a symmetric "oct" key, which must never be published — see Key.MarshalJSON).
type NumericDate ¶
NumericDate is RFC 7519 §2's NumericDate (seconds since the Unix epoch), exposed as a time.Time.
func NewNumericDate ¶
func NewNumericDate(t time.Time) *NumericDate
NewNumericDate wraps t as a *NumericDate.
func (NumericDate) MarshalJSON ¶
func (n NumericDate) MarshalJSON() ([]byte, error)
MarshalJSON emits the value as integer seconds since the Unix epoch.
func (*NumericDate) UnmarshalJSON ¶
func (n *NumericDate) UnmarshalJSON(b []byte) error
UnmarshalJSON accepts a JSON number (integer or fractional seconds), the same number quoted as a string, or null.
type OktaClaims ¶
type OktaClaims struct {
Version string `json:"ver,omitempty"`
AuthTime *NumericDate `json:"auth_time,omitempty"`
AMR []string `json:"amr,omitempty"`
IDP string `json:"idp,omitempty"`
Groups []string `json:"groups,omitempty"`
}
OktaClaims adds Okta-specific ID token claims. https://developer.okta.com/docs/reference/api/oidc/#id-token
type OktaIDToken ¶
type OktaIDToken struct {
RegisteredClaims
StandardClaims
OktaClaims
}
OktaIDToken is the Okta equivalent of GoogleIDToken.
type OpaqueToken ¶
OpaqueToken pairs a random or derived raw credential with its at-rest SHA-256 hash. Raw is handed to the client (e.g. in an HttpOnly cookie); only Hash is ever persisted.
func DeriveOpaqueToken ¶
func DeriveOpaqueToken(raw string) OpaqueToken
DeriveOpaqueToken deterministically builds a token from a string the caller already holds, instead of drawing fresh randomness. Raw is the input verbatim; Hash is its SHA-256 hex digest.
func NewOpaqueToken ¶
func NewOpaqueToken() (OpaqueToken, error)
NewOpaqueToken generates a fresh token: 32 bytes of crypto/rand, base64url-encoded, paired with its SHA-256 hex digest.
type ParseOption ¶
type ParseOption interface {
// contains filtered or unexported methods
}
ParseOption configures Parse, DecryptClaims and Middleware. Both the functional options below (WithIssuer, WithAudience, ...) and a ParseOptions struct satisfy it, so a reusable declarative config and per-call overrides combine in a single call — options apply left to right, so a later one wins:
base := jwt.ParseOptions{
AllowedAlgorithms: []jwt.Algorithm{jwt.RS256, jwt.ES256},
Issuer: "https://accounts.google.com",
}
err := jwt.Parse(ctx, tok, &claims, keys, base, jwt.WithAudience(clientID))
func WithAllowedAlgorithms ¶
func WithAllowedAlgorithms(algs ...Algorithm) ParseOption
WithAllowedAlgorithms sets the mandatory algorithm allowlist (RFC 8725 §3.1). "none" and the empty string are never accepted, even if listed.
func WithAudience ¶
func WithAudience(aud string) ParseOption
WithAudience requires aud to be present in the "aud" claim.
func WithClock ¶
func WithClock(now func() time.Time) ParseOption
WithClock overrides the clock used for every time-based check. A nil function is ignored.
func WithIssuer ¶
func WithIssuer(iss string) ParseOption
WithIssuer requires the "iss" claim to equal iss.
func WithLeeway ¶
func WithLeeway(d time.Duration) ParseOption
WithLeeway allows d of clock skew on "exp" and "nbf" checks (default 0).
func WithRequiredClaims ¶
func WithRequiredClaims(names ...string) ParseOption
WithRequiredClaims requires each named claim to be present in the payload.
func WithRequiredType ¶
func WithRequiredType(typ string) ParseOption
WithRequiredType requires the JOSE "typ" header to match typ, ignoring an optional "application/" prefix and case (RFC 8725 §3.11).
type ParseOptions ¶
type ParseOptions struct {
// AllowedAlgorithms is the mandatory algorithm allowlist (RFC 8725 §3.1).
// It is merged with any WithAllowedAlgorithms in the same call.
AllowedAlgorithms []Algorithm
Issuer string // require "iss" to equal this
Audience string // require this to be present in "aud"
RequiredType string // require the JOSE "typ" header to match (RFC 8725 §3.11)
RequiredClaims []string // require each named claim to be present
Leeway time.Duration // clock-skew allowance on "exp"/"nbf" (default 0)
Clock func() time.Time
}
ParseOptions is the reusable, declarative form of the parse configuration. A zero field imposes no constraint (and, for Clock, keeps the default). It carries exactly the same settings as the With* options; mix the two freely.
type RegisteredClaims ¶
type RegisteredClaims struct {
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audience Audience `json:"aud,omitempty"`
ExpiresAt *NumericDate `json:"exp,omitempty"`
NotBefore *NumericDate `json:"nbf,omitempty"`
IssuedAt *NumericDate `json:"iat,omitempty"`
ID string `json:"jti,omitempty"`
Confirmation *Confirmation `json:"cnf,omitempty"`
}
RegisteredClaims holds every generic claim this library targets from the IANA "JSON Web Token Claims" registry: the original seven from RFC 7519 §4.1 plus "cnf" from RFC 7800.
Embed it in your own claims struct so those members flatten into the same JSON object — that struct is what you pass to Sign / EncryptClaims and get back from Parse / DecryptClaims:
type MyClaims struct {
jwt.RegisteredClaims
Scope string `json:"scope,omitempty"`
Role string `json:"role,omitempty"`
}
type RevocationReason ¶
type RevocationReason string
RevocationReason records why an identifier was revoked.
const ( ReasonLogout RevocationReason = "logout" ReasonKeyCompromised RevocationReason = "key_compromised" // identifier is a ThumbprintBytes-derived kid ReasonReuseDetected RevocationReason = "reuse_detected" // identifier is a TokenFamily.ID ReasonAdmin RevocationReason = "admin_revoked" )
type RevocationStore ¶
type RevocationStore interface {
// Revoke marks id as revoked until expiresAt. A zero expiresAt means the
// revocation never expires. The caller decides what id denotes.
Revoke(ctx context.Context, id string, reason RevocationReason, expiresAt time.Time) error
// IsRevoked reports whether id is currently revoked.
IsRevoked(ctx context.Context, id string) (bool, error)
}
RevocationStore abstracts revocation-state storage, generalized over the identifier namespace: the same interface revokes a single token by "jti", an entire signing key by its JWK thumbprint, or a refresh-token session by TokenFamily.ID. The library ships an in-memory implementation sufficient for a single process; real deployments inject a shared store (Redis, a database) so revocation is visible across instances and survives restarts.
func NewMemoryRevocationStore ¶
func NewMemoryRevocationStore() RevocationStore
NewMemoryRevocationStore returns the library's built-in RevocationStore: an in-process, mutex-guarded map with lazy expiry. Documented as single-process-only.
type RotationResult ¶
type RotationResult struct {
Next OpaqueToken
ReuseDetected bool
}
RotationResult is what a storage-backed rotation implementation should return; ReuseDetected signals the caller MUST revoke the entire family.
type SignOption ¶
type SignOption interface {
// contains filtered or unexported methods
}
SignOption customizes the JOSE header Sign emits; it never affects "alg". Both the functional options (WithType, WithContentType) and a SignOptions struct satisfy it and combine in one call, applied left to right:
base := jwt.SignOptions{Type: jwt.AccessTokenType}
tok, _ := jwt.Sign(claims, signer, base, jwt.WithContentType("example"))
func WithContentType ¶
func WithContentType(cty string) SignOption
WithContentType sets the "cty" header parameter (RFC 7515 §4.1.10), used mainly to mark a nested JWT payload.
type SignOptions ¶
SignOptions is the reusable, declarative form of the header settings. A zero Type keeps DefaultType (use WithType("") to omit "typ" entirely); a zero ContentType leaves "cty" unset.
type Signer ¶
type Signer = internalalg.Signer
Signer produces a JWS signature over the ASCII signing input.
func NewECDSASigner ¶
NewECDSASigner returns an ES256/ES384/ES512 Signer.
func NewEd25519Signer ¶
func NewEd25519Signer(key ed25519.PrivateKey, kid ...string) (Signer, error)
NewEd25519Signer returns an EdDSA (Ed25519) Signer.
func NewHMACSigner ¶
NewHMACSigner returns an HS256/HS384/HS512 Signer.
func NewRSAPSSSigner ¶
NewRSAPSSSigner returns a PS256/PS384/PS512 Signer.
type StandardClaims ¶
type StandardClaims 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"`
PreferredUsername string `json:"preferred_username,omitempty"`
Profile string `json:"profile,omitempty"`
Picture string `json:"picture,omitempty"`
Website string `json:"website,omitempty"`
Email string `json:"email,omitempty"`
EmailVerified *bool `json:"email_verified,omitempty"`
Gender string `json:"gender,omitempty"`
Birthdate string `json:"birthdate,omitempty"`
ZoneInfo string `json:"zoneinfo,omitempty"`
Locale string `json:"locale,omitempty"`
PhoneNumber string `json:"phone_number,omitempty"`
PhoneNumberVerified *bool `json:"phone_number_verified,omitempty"`
Address *Address `json:"address,omitempty"`
UpdatedAt *NumericDate `json:"updated_at,omitempty"`
Nonce string `json:"nonce,omitempty"` // OIDC Core §2, replay protection
}
StandardClaims are the OpenID Connect Core 1.0 §5.1 standard claims, common across virtually every OIDC provider. Embed it (alongside RegisteredClaims and a provider claim set) in your own ID-token struct.
type TokenFamily ¶
type TokenFamily struct{ ID string }
TokenFamily identifies a lineage of rotated tokens sharing one logical session, so that presenting an already-rotated-away token can be detected as reuse and the whole family revoked — a common refresh-token-rotation pattern. The library defines the shape; storage is the caller's (see RevocationStore, §5.6).
func NewTokenFamily ¶
func NewTokenFamily() TokenFamily
NewTokenFamily returns a TokenFamily with a fresh random ID.
It neither returns an error nor panics: since Go 1.24 crypto/rand.Read is defined to always succeed, and a catastrophic OS CSPRNG failure aborts the program from within the runtime — a condition this package cannot observe or recover from.
type Verifier ¶
type Verifier = internalalg.Verifier
Verifier checks a JWS signature.
func NewECDSAVerifier ¶
NewECDSAVerifier returns an ES256/ES384/ES512 Verifier.
func NewEd25519Verifier ¶
NewEd25519Verifier returns an EdDSA (Ed25519) Verifier.
func NewHMACVerifier ¶
NewHMACVerifier returns an HS256/HS384/HS512 Verifier.
func NewRSAPKCS1Verifier ¶
NewRSAPKCS1Verifier returns an RS256/RS384/RS512 Verifier.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic_hmac
command
Command basic_hmac signs a JWT with HS256 and verifies it back.
|
Command basic_hmac signs a JWT with HS256 and verifies it back. |
|
http_middleware
command
Command http_middleware protects an HTTP handler with jwt.Middleware and exercises it with an in-process request.
|
Command http_middleware protects an HTTP handler with jwt.Middleware and exercises it with an in-process request. |
|
jwe_roundtrip
command
Command jwe_roundtrip encrypts a claim set as a compact JWE with ECDH-ES+A256KW / A256GCM and decrypts it back.
|
Command jwe_roundtrip encrypts a claim set as a compact JWE with ECDH-ES+A256KW / A256GCM and decrypts it back. |
|
refresh_rotation
command
Command refresh_rotation demonstrates opaque refresh-token rotation with reuse detection: the library supplies the shapes (OpaqueToken, TokenFamily, RotationResult) and a RevocationStore; the rotation policy and storage are the application's.
|
Command refresh_rotation demonstrates opaque refresh-token rotation with reuse detection: the library supplies the shapes (OpaqueToken, TokenFamily, RotationResult) and a RevocationStore; the rotation policy and storage are the application's. |
|
verify_idtoken
command
Command verify_idtoken shows the JWKS + provider-claims path: an OpenID provider signs an ID token with ES256 and publishes its public key in a JWK Set; a relying party verifies it as a jwt.GoogleIDToken.
|
Command verify_idtoken shows the JWKS + provider-claims path: an OpenID provider signs an ID token with ES256 and publishes its public key in a JWK Set; a relying party verifies it as a jwt.GoogleIDToken. |
|
internal
|
|
|
alg
Package alg contains the built-in JWS algorithms.
|
Package alg contains the built-in JWS algorithms. |
|
b64
Package b64 provides the base64url (RFC 4648 §5, no padding) encoding used throughout JOSE compact serialization.
|
Package b64 provides the base64url (RFC 4648 §5, no padding) encoding used throughout JOSE compact serialization. |
|
bytes
Package bytes contains byte-slice helpers shared by internal implementations.
|
Package bytes contains byte-slice helpers shared by internal implementations. |
|
errors
Package errors contains sentinel values shared by internal implementations and the public jwt package.
|
Package errors contains sentinel values shared by internal implementations and the public jwt package. |
|
option
Package option contains small helpers shared by public constructors.
|
Package option contains small helpers shared by public constructors. |
|
Package jwttest provides fakes and shared conformance suites for code that plugs into the jwt package's injectable interfaces — so callers need not re-implement jwt.KeyProvider / jwt.RevocationStore nor re-derive the behaviour Parse and the revocation helpers expect.
|
Package jwttest provides fakes and shared conformance suites for code that plugs into the jwt package's injectable interfaces — so callers need not re-implement jwt.KeyProvider / jwt.RevocationStore nor re-derive the behaviour Parse and the revocation helpers expect. |