jwt

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 32 Imported by: 0

README

jwt

A single-package JWT / JOSE library for Go: JWS signing and verification, JWE encryption, JWK / JWKS handling with pluggable key resolution, OIDC and provider-specific claim sets, opaque-token utilities, revocation, and a thin HTTP bearer adapter — one import path, no third-party runtime dependencies.

See spec.md for the full design and RFC-compliance matrix.

Install

go get github.com/NyeKo-ItL/jwt

At a glance

Sign and verify a JWS
// A claims value is any struct that marshals to a JSON object; embed
// jwt.RegisteredClaims for iss/sub/exp/... to flatten in.
type MyClaims struct {
    jwt.RegisteredClaims
    Role string `json:"role,omitempty"`
}

signer, _ := jwt.NewEd25519Signer(priv) // kid is optional
token, _ := jwt.Sign(MyClaims{
    RegisteredClaims: jwt.RegisteredClaims{Issuer: "me", ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))},
    Role:             "admin",
}, signer)

keys := jwt.StaticKeyProvider(jwt.FromEd25519PublicKey(pub))
var claims MyClaims // type is inferred from &claims — no jwt.Parse[...]
err := jwt.Parse(ctx, token, &claims, keys,
    jwt.WithAllowedAlgorithms(jwt.EdDSA),
    jwt.WithIssuer("me"),
) // claims.Role, claims.Subject, ...

jwt.WithAllowedAlgorithms is mandatory (RFC 8725 §3.1); alg: none is never representable in either direction.

Options are reusable: declare a jwt.ParseOptions{} once and combine it with per-call With* overrides —

var apiOpts = jwt.ParseOptions{
    AllowedAlgorithms: []jwt.Algorithm{jwt.EdDSA},
    Issuer:            "me",
}
err := jwt.Parse(ctx, token, &claims, keys, apiOpts, jwt.WithAudience("orders"))
Verify third-party ID tokens over JWKS
uri, _ := jwt.DiscoverJWKSURI(ctx, "https://accounts.google.com", nil)
keys := jwt.NewKeyFetcher(uri)
var idt jwt.GoogleIDToken
err := jwt.Parse(ctx, raw, &idt, keys,
    jwt.WithAllowedAlgorithms(jwt.RS256),
    jwt.WithAudience(clientID),
)
Encrypt claims as a JWE
enc, _ := jwt.NewECDHESEncrypter(recipientPub, jwt.ECDHESA256KW, jwt.A256GCM, "")
compact, _ := jwt.EncryptClaims(claims, enc)

dec, _ := jwt.NewECDHESDecrypter(recipientPriv, "")
var out MyClaims
err := jwt.DecryptClaims(ctx, compact, &out, dec)

Scope

In: JWS (HMAC, RSA-PSS sign / PKCS#1 v1.5 verify, ECDSA, Ed25519), JWE (RSA-OAEP-256, ECDH-ES(+A256KW), A256KW, dir with AES-GCM), JWK/JWKS, RFC 7638 thumbprints, RFC 9068 access-token claims, opaque tokens, refresh rotation shapes, revocation, RFC 6750 bearer extraction.

Out: OAuth 2.x authorization server, OIDC relying-party flow orchestration, file I/O, key generation. See spec.md §2.2.

License

MIT — see LICENSE.

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

View Source
const AccessTokenType = "at+jwt"

AccessTokenType is the mandatory "typ" header value per RFC 9068 §2.1, intended for use with WithRequiredType.

View Source
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

View Source
var (
	ErrInvalidSignature    = errors.New("jwt: invalid signature")
	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              = errors.New("jwt: key does not meet minimum size")
	ErrUnsupportedAlgorithm = errors.New("jwt: unsupported algorithm")
	ErrKeyNotFound          = errors.New("jwt: no key for kid")
	ErrKeyTypeMismatch      = errors.New("jwt: key type does not match algorithm")
	ErrMalformedKey         = errors.New("jwt: malformed key material")
	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).

View Source
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).

View Source
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

func BearerToken(r *http.Request) (string, bool)

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

func ClaimsFromContext[C any](ctx context.Context, dst *C) error

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

func DiscoverJWKSURI(ctx context.Context, issuer string, client *http.Client) (string, error)

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

func EncryptClaims[C any](claims C, enc Encrypter) (string, error)

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

func Equal(storedHash, raw string) bool

Equal reports whether raw hashes to storedHash, comparing in constant time (crypto/subtle) to avoid leaking the digest through timing.

func Hash

func Hash(raw string) string

Hash returns the SHA-256 hex digest of raw.

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 64-byte expanded Ed25519 key (32-byte seed followed by the 32-byte public key), verifying the two halves are consistent.

func ParseEd25519PrivateKeySeed

func ParseEd25519PrivateKeySeed(seed []byte) (ed25519.PrivateKey, error)

ParseEd25519PrivateKeySeed parses a raw 32-byte Ed25519 seed.

func ParseEd25519PublicKey

func ParseEd25519PublicKey(raw []byte) (ed25519.PublicKey, error)

ParseEd25519PublicKey parses a raw 32-byte Ed25519 public key.

func ParseInsecure

func ParseInsecure[C any](token string, dst *C) error

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

func ParseOpenSSHPrivateKey(raw []byte) (crypto.Signer, error)

ParseOpenSSHPrivateKey parses the OpenSSH private key binary format (the bytes inside the "-----BEGIN OPENSSH PRIVATE KEY-----" PEM block, already base64-decoded by the caller). Encrypted keys are rejected.

func ParsePKCS1PrivateKey

func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)

ParsePKCS1PrivateKey parses a DER-encoded PKCS#1 RSA private key.

func ParsePKCS8PrivateKey

func ParsePKCS8PrivateKey(der []byte) (crypto.Signer, error)

ParsePKCS8PrivateKey parses a DER-encoded PKCS#8 private key, returning the concrete key type embedded (*rsa.PrivateKey, *ecdsa.PrivateKey or ed25519.PrivateKey), all of which satisfy crypto.Signer.

func ParsePKIXPublicKey

func ParsePKIXPublicKey(der []byte) (crypto.PublicKey, error)

ParsePKIXPublicKey parses a DER-encoded PKIX (SubjectPublicKeyInfo) public key (RSA, EC or Ed25519).

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

func Thumbprint(k Key, hash ...crypto.Hash) (string, error)

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

func ThumbprintBytes(kty KeyType, raw []byte, hash ...crypto.Hash) (string, error)

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 string

Algorithm identifies a JWA/EdDSA signing algorithm. It is an open string type, not a closed enum: a caller implementing a custom Signer/Verifier can define their own Algorithm value and it works exactly like a built-in one everywhere an Algorithm is accepted (spec §0.2, §5.1).

const (
	HS256 Algorithm = "HS256"
	HS384 Algorithm = "HS384"
	HS512 Algorithm = "HS512"
	RS256 Algorithm = "RS256" // built-in verify-only (spec §0.2)
	RS384 Algorithm = "RS384" // built-in verify-only
	RS512 Algorithm = "RS512" // built-in verify-only
	PS256 Algorithm = "PS256"
	PS384 Algorithm = "PS384"
	PS512 Algorithm = "PS512"
	ES256 Algorithm = "ES256"
	ES384 Algorithm = "ES384"
	ES512 Algorithm = "ES512"
	EdDSA Algorithm = "EdDSA"
)

Registered algorithm identifiers (spec §5.1). "none" (RFC 7518 §3.6) deliberately has no constant and is never representable in either direction (spec §0.2, §4.2).

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) Has

func (a Audience) Has(v string) bool

Has reports whether v is one of the audience values.

func (Audience) MarshalJSON

func (a Audience) MarshalJSON() ([]byte, error)

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

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

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

func NewA256KWDecrypter(kek []byte, kid ...string) (Decrypter, error)

NewA256KWDecrypter unwraps the CEK of a JWE "alg":"A256KW" token.

func NewDirectDecrypter

func NewDirectDecrypter(cek []byte, kid ...string) (Decrypter, error)

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

func FromECDSAPublicKey(pub *ecdsa.PublicKey, kid ...string) Key

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

func FromEd25519PublicKey(pub ed25519.PublicKey, kid ...string) Key

FromEd25519PublicKey builds a "sig" JWK from an Ed25519 public key.

func FromHMACSecret

func FromHMACSecret(secret []byte, kid ...string) Key

FromHMACSecret builds a symmetric (kty "oct") JWK. Such a key cannot be marshaled into a servable JWKS document (see MarshalJSON).

func FromRSAPublicKey

func FromRSAPublicKey(pub *rsa.PublicKey, kid ...string) Key

FromRSAPublicKey builds a "sig" JWK from an RSA public key.

func ParseKey

func ParseKey(data []byte) (Key, error)

ParseKey parses a single JSON Web Key (RFC 7517 §4).

func (Key) MarshalJSON

func (k Key) MarshalJSON() ([]byte, error)

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) PublicKey

func (k Key) PublicKey() (crypto.PublicKey, error)

PublicKey reconstructs the stdlib public key for an RSA/EC/OKP JWK.

func (Key) Secret

func (k Key) Secret() ([]byte, error)

Secret returns the raw symmetric key bytes for an "oct" JWK.

func (*Key) UnmarshalJSON

func (k *Key) UnmarshalJSON(b []byte) error

UnmarshalJSON parses an RFC 7517 JWK object.

func (Key) Verifier

func (k Key) Verifier() (Verifier, error)

Verifier builds a Verifier from the key material and the key's own Alg.

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.

func (*KeyFetcher) Lookup

func (f *KeyFetcher) Lookup(ctx context.Context, kid string) (Key, bool, error)

Lookup resolves a key by kid, fetching (or refetching, subject to the caching rules) the JWKS document as needed. It satisfies KeyProvider.

func (*KeyFetcher) Refresh

func (f *KeyFetcher) Refresh(ctx context.Context) error

Refresh forces an immediate re-fetch of the JWKS document.

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 NewKeySet

func NewKeySet(keys ...Key) *KeySet

NewKeySet returns a KeySet seeded with keys.

func ParseKeySet

func ParseKeySet(data []byte) (*KeySet, error)

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) Add

func (s *KeySet) Add(k Key)

Add inserts k, replacing any existing key with the same non-empty kid.

func (*KeySet) Keys

func (s *KeySet) Keys(_ context.Context) ([]Key, error)

Keys returns a snapshot copy of the set, for serving as a JWKS document.

func (*KeySet) Lookup

func (s *KeySet) Lookup(_ context.Context, kid string) (Key, bool, error)

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

func (s *KeySet) MarshalJSON() ([]byte, error)

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

func (*KeySet) Remove

func (s *KeySet) Remove(kid string)

Remove deletes every key with the given kid.

type KeyType

type KeyType string

KeyType is the RFC 7517 §4.1 "kty" value.

const (
	KeyTypeRSA KeyType = "RSA"
	KeyTypeEC  KeyType = "EC"
	KeyTypeOKP KeyType = "OKP" // Ed25519 (RFC 8037)
	KeyTypeOct KeyType = "oct" // symmetric; internal use only
)

type NumericDate

type NumericDate struct{ time.Time }

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

type OpaqueToken struct {
	Raw  string
	Hash string
}

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.

func WithType

func WithType(typ string) SignOption

WithType overrides the "typ" header parameter (RFC 7515 §4.1.9). The default is DefaultType; pass "" to omit "typ" entirely, or AccessTokenType for the RFC 9068 profile.

type SignOptions

type SignOptions struct {
	Type        string
	ContentType string
}

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 interface {
	// Algorithm reports the JWS "alg" value this signer produces; Sign stamps
	// it into the protected header.
	Algorithm() Algorithm
	// KeyID is the RFC 7515 §4.1.4 "kid"; empty if the key has none.
	KeyID() string
	// Sign returns the signature over signingInput
	// ("<b64url header>.<b64url payload>").
	Sign(signingInput []byte) (signature []byte, err error)
}

Signer produces a JWS signature over the ASCII signing input "<base64url header>.<base64url payload>" (RFC 7515 §5.1). It is a plain interface: a caller may implement it for an algorithm the built-in constructors do not cover (e.g. PKCS#1 v1.5 RSA, or an HSM/KMS-backed key). Sign has no type-switch over a closed set of known signers.

func NewECDSASigner

func NewECDSASigner(alg Algorithm, key *ecdsa.PrivateKey, kid ...string) (Signer, error)

NewECDSASigner returns an ES256/ES384/ES512 Signer. The key's curve must match the algorithm. kid is optional.

func NewEd25519Signer

func NewEd25519Signer(key ed25519.PrivateKey, kid ...string) (Signer, error)

NewEd25519Signer returns an EdDSA (Ed25519, RFC 8037) Signer. kid is optional.

func NewHMACSigner

func NewHMACSigner(alg Algorithm, key []byte, kid ...string) (Signer, error)

NewHMACSigner returns an HS256/HS384/HS512 Signer. The key must be at least as long as the hash output (spec §4.6). kid is optional.

func NewRSAPSSSigner

func NewRSAPSSSigner(alg Algorithm, key *rsa.PrivateKey, kid ...string) (Signer, error)

NewRSAPSSSigner returns a PS256/PS384/PS512 (RSA-PSS) Signer. PKCS#1 v1.5 signing is intentionally not offered as a built-in (spec §0.2). kid is optional.

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 interface {
	// Algorithm reports the JWS "alg" value this verifier accepts; Parse
	// requires it to match the token header before calling Verify.
	Algorithm() Algorithm
	// KeyID is the RFC 7515 §4.1.4 "kid"; empty if the key has none.
	KeyID() string
	// Verify returns nil if signature is a valid signature over signingInput,
	// and a non-nil error otherwise.
	Verify(signingInput, signature []byte) error
}

Verifier checks a JWS signature. The library ships constructors for the full applicable registry, including verify-only algorithms, because it must validate tokens issued by third parties this library would never itself sign with. Like Signer, it is a plain interface open to caller extension.

func NewECDSAVerifier

func NewECDSAVerifier(alg Algorithm, key *ecdsa.PublicKey, kid ...string) (Verifier, error)

NewECDSAVerifier returns an ES256/ES384/ES512 Verifier. kid is optional.

func NewEd25519Verifier

func NewEd25519Verifier(key ed25519.PublicKey, kid ...string) (Verifier, error)

NewEd25519Verifier returns an EdDSA (Ed25519, RFC 8037) Verifier. kid is optional.

func NewHMACVerifier

func NewHMACVerifier(alg Algorithm, key []byte, kid ...string) (Verifier, error)

NewHMACVerifier returns an HS256/HS384/HS512 Verifier. The same minimum key-size rule as NewHMACSigner applies (spec §4.6). kid is optional.

func NewRSAPKCS1Verifier

func NewRSAPKCS1Verifier(alg Algorithm, key *rsa.PublicKey, kid ...string) (Verifier, error)

NewRSAPKCS1Verifier returns an RS256/RS384/RS512 (PKCS#1 v1.5) Verifier. This is verify-only: common external IdPs (Google, Okta, Entra ID) issue RS256 ID tokens (spec §0.2). kid is optional.

func NewRSAPSSVerifier

func NewRSAPSSVerifier(alg Algorithm, key *rsa.PublicKey, kid ...string) (Verifier, error)

NewRSAPSSVerifier returns a PS256/PS384/PS512 Verifier. kid is optional.

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

Jump to

Keyboard shortcuts

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