jwt

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 39 Imported by: 0

README

jwt

Go Reference Latest release CI codecov Scheduled fuzzing Release

OpenSSF Scorecard OpenSSF Best Practices CodeQL Security scans Dependabot Updates

A single-package JWT / JOSE library for Go with secure defaults: JWS signing and verification, JWE encryption, JWK / JWKS handling with pluggable key resolution, OpenID Connect and provider claim sets, the RFC 9068 access-token profile, the RFC 9999 cmw attestation claim, opaque tokens, revocation, and an RFC 6750 HTTP bearer adapter.

  • One import path, no third-party runtime dependencies. Standard library only.
  • Hard to misuse. Algorithm allowlists are mandatory, alg: none cannot be expressed, audience is enforced, crit is honored, and untrusted JSON and base64url are decoded strictly.
  • Checked against the standards. RFC test vectors, interoperability tests against golang-jwt/jwt/v5 and go-jose/go-jose/v4, continuous fuzzing, and a requirement-by-requirement compliance matrix.

Status: pre-1.0. The API may still change between minor versions; every change is listed in the CHANGELOG. Requires Go 1.27.4 or later.

Contents

Install

go get github.com/NyeKo-ItL/jwt

Quick start

A claims value is any struct that marshals to a JSON object. Embed jwt.RegisteredClaims to get iss, sub, aud, exp, nbf, iat, jti and cnf, and give every other field an exact json tag. Member names are matched case-sensitively.

type MyClaims struct {
    jwt.RegisteredClaims
    Role string `json:"role,omitempty"`
}

// Issue
signer, _ := jwt.NewEd25519Signer(priv, "key-1") // kid is optional
token, _ := jwt.Sign(MyClaims{
    RegisteredClaims: jwt.RegisteredClaims{
        Issuer:    "https://auth.example.com",
        Audience:  jwt.Audience{"https://api.example.com"},
        ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
    },
    Role: "admin",
}, signer)

// Verify
keys := jwt.StaticKeyProvider(jwt.FromEd25519PublicKey(pub, "key-1"))

var claims MyClaims
err := jwt.Parse(ctx, token, &claims, keys,
    jwt.WithAllowedAlgorithms(jwt.Ed25519), // mandatory
    jwt.WithIssuer("https://auth.example.com"),
    jwt.WithAudience("https://api.example.com"),
)

Parse always checks the signature, exp and nbf. It rejects a token that carries an aud claim unless WithAudience names one of its values (RFC 7519 §4.1.3).

jwt.ParseInsecure decodes a payload without verifying anything. Use it only to inspect a token you will not trust, for example to look up a session by the jti of an expired token.

Usage

Every snippet below is also a compiled, tested example in example_test.go, shown on pkg.go.dev. Runnable programs live in examples/.

Reusable options

Declare a policy once as jwt.ParseOptions and combine it with per-call With* options. Options apply left to right; the allowlists and required claims merge.

var apiOpts = jwt.ParseOptions{
    AllowedAlgorithms: []jwt.Algorithm{jwt.Ed25519},
    Issuer:            "https://auth.example.com",
}

err := jwt.Parse(ctx, token, &claims, keys, apiOpts, jwt.WithAudience("orders"))
Option Effect
WithAllowedAlgorithms(...) Required. Accepted JWS alg values; none is never accepted; a key without alg is rejected when several compatible algorithms are allowed
WithIssuer(iss) iss must equal iss
WithAudience(aud) aud must contain aud; a token without aud is rejected
WithoutAudienceCheck() Accept a token whose aud names someone else — only for components that are not the recipient
WithRequiredType(typ) typ header must match, e.g. jwt.AccessTokenType (RFC 8725 §3.11)
WithRequiredClaims(names...) Each named claim must be present
WithLeeway(d) Clock-skew allowance for exp / nbf (default 0)
WithClock(now) Time source for all time checks
WithAllowedKeyAlgorithms(...), WithAllowedContentAlgorithms(...) Required for DecryptClaims. JWE alg / enc allowlists
WithVerifierProvider(provider) Resolve a custom Verifier by alg/kid, e.g. from an HSM or KMS
MiddlewareOptions{Realm, OnError} Middleware only
OAuth 2.0 access tokens (RFC 9068)
// Authorization server: typ MUST be "at+jwt"
token, _ := jwt.Sign(jwt.AccessTokenClaims{
    RegisteredClaims: jwt.RegisteredClaims{
        Issuer:    iss,
        Subject:   userID,
        Audience:  jwt.Audience{resource},
        IssuedAt:  jwt.NewNumericDate(now),
        ExpiresAt: jwt.NewNumericDate(now.Add(5 * time.Minute)),
        ID:        tokenID, // jti is REQUIRED by RFC 9068
    },
    ClientID: clientID,
    Scope:    "orders:read",
}, signer, jwt.WithType(jwt.AccessTokenType))

// Resource server: all RFC 9068 §4 checks
var at jwt.AccessTokenClaims
err := jwt.Parse(ctx, token, &at, keys,
    jwt.WithAllowedAlgorithms(jwt.ES256),
    jwt.WithRequiredType(jwt.AccessTokenType),
    jwt.WithIssuer(iss),
    jwt.WithAudience(resource),
)
if err == nil {
    err = jwt.ValidateAccessTokenClaims(at) // iss, exp, aud, sub, client_id, iat, jti present
}
Attestation CMW claim (RFC 9999)

The RATS Conceptual Message Wrapper travels in the registered cmw claim as a JSON record ([media-type, base64url-value, ind?]) or a collection (an object of labelled CMWs). CMWClaims models the claim; ParseCMW validates the RFC 9999 §6 CDDL strictly (media types, unpadded base64url, ind bitmap, __cmwc_t URI/OID, duplicate members, nesting depth). Errors wrap ErrInvalidClaim.

var claims jwt.CMWClaims
err := jwt.Parse(ctx, token, &claims, keys, jwt.WithAllowedAlgorithms(jwt.ES256))
if err == nil && claims.CMW != nil && claims.CMW.Collection != nil {
    evidence := claims.CMW.Collection.Members["attester A"].Record
    if evidence != nil && evidence.Indicator != nil && *evidence.Indicator&jwt.CMWEvidence != 0 {
        // evidence.Type is the media type, evidence.Value the decoded bytes
    }
}

A CMW can also be signed on its own as a JWS (RFC 9999 §4.2). The payload is the CMW, not a JWT Claims Set, and cty is application/cmw+json:

token, err := jwt.SignCMW(cmw, signer)

cmw, err := jwt.ParseSignedCMW(ctx, token, keys, jwt.WithAllowedAlgorithms(jwt.ES256))

ParseSignedCMW keeps every Parse defence (mandatory algorithm allowlist, key lookup by kid only, no none), requires the cty, and skips the JWT exp / iss / aud checks, which do not apply to a CMW. Only the compact serialization is supported. The CBOR forms (CWT cmw, CBOR tags, X.509 extension, COSE signing) are out of scope for a JWT library.

OpenID Connect ID tokens over JWKS
uri, err := jwt.DiscoverJWKSURI(ctx, "https://accounts.google.com", nil)
if err != nil { /* errors.Is(err, jwt.ErrKeyFetch) */ }
keys := jwt.NewKeyFetcher(uri)

var core jwt.IDTokenClaims
err = jwt.Parse(ctx, rawIDToken, &core, keys,
    jwt.WithAllowedAlgorithms(jwt.RS256),
    jwt.WithIssuer("https://accounts.google.com"),
    jwt.WithAudience(clientID),
    jwt.WithRequiredClaims("iss", "sub", "aud", "exp", "iat"),
)
if err == nil {
    err = jwt.ValidateIDTokenForContext(core, jwt.IDTokenValidationContext{
        ClientID:         clientID,
        ExpectedNonce:    nonceFromSession,
        RequireNonce:     true,
        AccessToken:      accessToken, // required when at_hash is present
        AuthorizationCode: code,       // required when c_hash is present
        SigningAlgorithm: jwt.RS256,
    })
}
  • DiscoverJWKSURI follows OpenID Connect Discovery 1.0: the issuer must be https, the document's issuer must equal it exactly, and there is no fallback URL.
  • KeyFetcher is HTTPS-only (every redirect included), size/key-count capped, and governed by a URL policy. Concurrent lookups share one request, and attempts are rate-limited even when they fail. Stale keys are served only for WithMaxStaleDuration (default 24 h; pass 0 to fail closed immediately). no-cache, no-store, and capped max-age are honored. Preapprove issuer hosts; use WithURLPolicy for an explicit allowlist.
  • Identifying users: use sub (or Entra's oid + tid), never email.
Encrypted tokens (JWE)
signer, _ := jwt.NewEd25519Signer(signingKey, "sig-1")
inner, _ := jwt.Sign(claims, signer)

enc, _ := jwt.NewECDHESEncrypter(&recipient.PublicKey, jwt.ECDHESA256KW, jwt.A256GCM, "enc-1")
compact, _ := jwt.EncryptNestedJWT(inner, enc, jwt.WithJWEType("example+jwt"))

dec, _ := jwt.NewECDHESDecrypter(recipient, "enc-1")
var out MyClaims
err := jwt.DecryptNestedJWT(ctx, compact, &out, dec, verificationKeys, jwt.NestedJWTPolicies{
    JWE: []jwt.ParseOption{
        jwt.WithAllowedKeyAlgorithms(jwt.ECDHESA256KW),
        jwt.WithAllowedContentAlgorithms(jwt.A256GCM),
        jwt.WithRequiredType("example+jwt"),
    },
    JWS: []jwt.ParseOption{
        jwt.WithAllowedAlgorithms(jwt.Ed25519),
        jwt.WithIssuer(issuer),
        jwt.WithAudience(audience),
    },
})

Every decryption failure returns the single jwt.ErrDecryptionFailed, and no plaintext is exposed before the AEAD tag verifies. Compression (zip) is refused.

A public-key JWE authenticates the ciphertext to the recipient, not the sender. Anyone with the recipient public key can create one. Never use direct asymmetric DecryptClaims output for authorization; sign then encrypt and use DecryptNestedJWT. Direct EncryptClaims/DecryptClaims remains appropriate when sender authenticity is established separately, such as a strictly scoped symmetric-key channel.

HTTP middleware (RFC 6750)
h := jwt.Middleware(keys,
    jwt.WithAllowedAlgorithms(jwt.ES256),
    jwt.WithAudience("https://api.example.com"),
    jwt.MiddlewareOptions{
        Realm:   "api",
        OnError: func(r *http.Request, err error) { slog.WarnContext(r.Context(), "auth failed", "err", err) },
    },
)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    var claims MyClaims
    if err := jwt.ClaimsFromContext(r.Context(), &claims); err != nil { /* ... */ }
    if claims.Role != "admin" {
        jwt.WriteInsufficientScope(w, "api", "admin") // 403
        return
    }
}))
Failure Response
No or unparsable Authorization: Bearer 401, WWW-Authenticate: Bearer realm="api"
Malformed token 400, error="invalid_request"
Expired, not yet valid, bad signature, wrong issuer/audience, … 401, error="invalid_token"
JWKS unreachable, request context ended 503, no challenge
Misconfiguration or KeyProvider backend failure 500, no challenge

Responses contain fixed text only. The full error, which may include internal hostnames, goes to OnError.

Publishing a JWKS
key := jwt.FromECDSAPublicKey(&priv.PublicKey, "2026-09")
key.Use, key.Alg = "sig", string(jwt.ES256) // one key, one algorithm (RFC 8725 §3.1)

set := jwt.NewKeySet(key)
http.HandleFunc("/.well-known/jwks.json", func(w http.ResponseWriter, _ *http.Request) {
    w.Header().Set("Content-Type", "application/jwk-set+json")
    _ = json.NewEncoder(w).Encode(set)
})

Symmetric (oct) keys refuse to marshal (jwt.ErrOctNotServable), so a secret cannot end up in a public key set. A key's use, key_ops and alg are honored when verifying.

Keys, opaque tokens and revocation
  • Key material: parsers for explicit, already-decoded encodings, with no file I/O and no format guessing: ParsePKCS8PrivateKey, ParsePKCS1PrivateKey, ParseSEC1ECPrivateKey, ParsePKIXPublicKey, ParseEd25519PrivateKeySeed, ParseOpenSSHPrivateKey, … Key generation is out of scope; use crypto/*.
  • Thumbprints: Thumbprint(key) / ThumbprintBytes(kty, raw) (RFC 7638), e.g. for cnf.jkt (RFC 7800).
  • Opaque tokens: NewOpaqueToken() returns a random credential plus the SHA-256 hash you store; VerifyOpaqueTokenHash(storedHash, raw) compares in constant time. OpaqueToken redacts Raw from normal Go formatting. OpaqueTokenFromRaw is deterministic and only as strong as its input.
  • Refresh rotation: TokenFamily and RotationResult model reuse detection; storage is yours (see examples/refresh_rotation).
  • Revocation: the RevocationStore interface (by jti, key thumbprint or token family) with an in-memory, single-process NewMemoryRevocationStore. Parse does not consult it; check it after parsing. Use NewMemoryRevocationStoreWithCapacity for a bounded local store.
  • Testing: jwttest provides fakes and conformance suites for your own KeyProvider / RevocationStore implementations.
Errors

Errors produced by library validation wrap a sentinel usable with errors.Is. Callback errors from signers/verifiers/providers are wrapped with context while preserving the original error identity:

Sentinel Meaning
ErrMalformedToken, ErrInvalidClaims, ErrInvalidDestination Malformed compact input, non-object Claims Set, or nil destination
ErrInvalidSignature Signature or MAC does not verify
ErrExpired, ErrNotYetValid exp / nbf
ErrIssuerMismatch, ErrAudienceMismatch, ErrTypeMismatch, ErrMissingClaim Claim or header policy
ErrAlgorithmNotAllowed alg / enc outside the allowlist, or key family mismatch
ErrKeyNotFound, ErrKeyUsage No key for kid; key's use / key_ops / alg forbid it
ErrUnsupportedCritical Token carries a crit header
ErrDecryptionFailed Any JWE decryption failure
ErrKeyFetch, ErrKeyProvider, ErrVerifierProvider JWKS/discovery or provider infrastructure failure
ErrNoAllowedAlgorithms Missing mandatory allowlist (configuration)
ErrWeakKey, ErrMalformedKey, ErrKeyTypeMismatch, ErrUnsupportedAlgorithm, ErrOctNotServable Key or constructor problems

Supported algorithms

Sign / encrypt Verify / decrypt
JWS HS256 HS384 HS512, PS256 PS384 PS512, ES256 ES384 ES512, Ed25519 the same, plus RS256 RS384 RS512 and the deprecated EdDSA (only when allowlisted)
JWE alg RSA-OAEP-256, ECDH-ES, ECDH-ES+A256KW, A256KW, dir same
JWE enc A128GCM, A192GCM, A256GCM same
JWK kty RSA (≥ 2048 bits), EC (P-256/384/521), OKP (Ed25519), oct same
  • Not provided: none, RSA1_5, RSA-OAEP (SHA-1), AES-CBC-HMAC, A128KW/A192KW, PBES2, Ed448/X25519, and JSON serialization. The reasons are in COMPLIANCE.md.
  • Custom algorithms: Signer, Encrypter, Decrypter, KeyProvider, and VerifierProvider are plain interfaces. Use WithVerifierProvider for an HSM/KMS verifier. Mandatory allowlists and returned alg/kid checks still apply.
  • Ed25519 naming: tokens are signed with the Ed25519 identifier from RFC 9864, which replaces EdDSA. Verifiers that predate RFC 9864, such as golang-jwt/jwt/v5, need a one-line alias; see interop/jws_test.go.

Security model

The library enforces the invariants listed in SECURITY.md. Highlights:

  • Algorithms: mandatory allowlists (JWS and JWE); none is unrepresentable. A key only verifies its own family and its own alg/use, so RSA cannot be confused with HMAC.
  • Untrusted header parameters: jku, x5u, jwk and x5c are never dereferenced or trusted, and any crit header is rejected.
  • Strict decoding: canonical base64url; encoding/json/v2 for headers, claims and JWKs (exact member names, no duplicates, valid UTF-8); NumericDate only as JSON numbers; 1 MiB token limit.
  • Claim checks: exp, nbf and aud are always enforced; the clock is injectable.
  • Secrets: constant-time comparisons; minimum key sizes (HMAC ≥ hash size, RSA 2048–8192 bits); deterministic ECDSA; deep-copied key material.
  • Decryption: JWE decryption fails closed with one generic error.
  • Remote keys: JWKS fetching is HTTPS-only, bounded and rate-limited; discovery validates the issuer.

Still your responsibility:

  • TLS for your own endpoints.
  • nonce and azp checks for OIDC logins.
  • Scope and role authorization.
  • jti replay or revocation checks via RevocationStore.
  • Key generation, storage and rotation.
  • Never using ParseInsecure output for authorization.

Reporting a vulnerability: use a private security advisory. Do not open a public issue.

Standards

Standard Coverage
RFC 7515 JWS Compact serialization, full header, crit
RFC 7516 JWE Compact serialization, AEAD algorithms
RFC 7517 JWK Keys and key sets, use / key_ops / alg
RFC 7518 JWA Algorithms above; canonical key encodings
RFC 7519 JWT Registered claims and validation
RFC 7638 JWK Thumbprint Any hash, SHA-256 default
RFC 7800 Proof-of-Possession cnf with jwk / jkt
RFC 8037 CFRG curves Ed25519 keys and signatures
RFC 9864 Fully-specified algorithms Ed25519; EdDSA deprecated
RFC 8725 JWT BCP All §3 practices (some opt-in)
RFC 6750 Bearer tokens Header method, challenges, error codes
RFC 9068 JWT access tokens Claims, at+jwt, validation
RFC 9999 RATS Conceptual Message Wrapper JSON cmw claim, signed CMW (§4.2)
OpenID Connect Core 1.0 / Discovery 1.0 ID-token claims, JWKS discovery

The per-requirement status — implemented, opt-in, not implemented, and the few deliberate deviations with their reasons — is in COMPLIANCE.md. A weekly workflow watches these standards for errata, updates and registry changes.

Project

Document Purpose
pkg.go.dev API reference with examples
COMPLIANCE.md Standards traceability matrix
SECURITY.md Enforced security invariants and vulnerability reporting
CHANGELOG.md Release notes, including breaking changes
MIGRATION.md Breaking changes and migration guidance for v1
CONTRIBUTING.md Development setup and contribution rules
spec.md Original design specification and rationale
examples/ Runnable programs
testdata/README.md Provenance of test vectors and fixtures

Quality gates (CI):

  • go test -race on Go 1.27.4+ with RFC known-answer vectors.
  • Interoperability tests (interop/).
  • Coverage ≥ 85%.
  • golangci-lint, including doc-comment checks.
  • govulncheck, CodeQL and OpenSSF Scorecard.
  • Scheduled fuzzing of Parse, DecryptClaims and ParseKeySet.
  • A fail-closed apidiff gate that computes the minimum SemVer bump; release tags rerun every quality/security gate and require a matching changelog section.

Versioning: Semantic Versioning. Before v1.0.0, minor versions may contain breaking changes, always listed in the changelog.

License

MIT — see LICENSE.

Documentation

Overview

Package jwt is a single-package JWT/JOSE library with secure defaults.

It covers JWS signing and verification (HMAC, RSA-PSS, ECDSA and Ed25519; RSA PKCS#1 v1.5 verification), JWE encryption and decryption (RSA-OAEP-256, ECDH-ES, ECDH-ES+A256KW, A256KW and 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, OpenID Connect standard and provider claim sets, the RFC 9068 access-token profile, opaque-token utilities, revocation (RevocationStore), per-encoding key material parsers, and an RFC 6750 bearer adapter.

Secure defaults

Parse requires WithAllowedAlgorithms and DecryptClaims requires WithAllowedKeyAlgorithms and WithAllowedContentAlgorithms (RFC 8725 §3.1); "none" is never representable. "exp", "nbf" and "aud" are always enforced (RFC 7519 §4.1.3–4.1.5), a "crit" header is rejected (RFC 7515 §4.1.11), and untrusted input is decoded strictly: canonical base64url, and encoding/json/v2 with exact member names, no duplicates and valid UTF-8. Header parameters such as "jku", "x5u" and "jwk" are never dereferenced (RFC 8725 §3.10). A JWK's "use", "key_ops" and "alg" restrict what it can verify, destinations are decoded atomically, and remote JWKS use bounded resource, freshness, stale, and URL policies. Public-key JWE does not prove sender identity; EncryptNestedJWT and DecryptNestedJWT provide the signed- then-encrypted path for authorization-bearing claims.

Documentation

README.md has a usage guide, COMPLIANCE.md maps each RFC requirement to its implementation and tests, SECURITY.md lists the enforced invariants, and MIGRATION.md covers stable-release changes, and spec.md records the original design plus audit amendments.

Example
package main

import (
	"context"
	"crypto/ed25519"
	"crypto/rand"
	"fmt"
	"time"

	"github.com/NyeKo-ItL/jwt"
)

type MyClaims struct {
	jwt.RegisteredClaims
	Role string `json:"role,omitempty"`
}

func main() {
	pub, priv, _ := ed25519.GenerateKey(rand.Reader)

	signer, _ := jwt.NewEd25519Signer(priv, "key-1")
	token, _ := jwt.Sign(MyClaims{
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "https://auth.example.com",
			Audience:  jwt.Audience{"https://api.example.com"},
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
		},
		Role: "admin",
	}, signer)

	keys := jwt.StaticKeyProvider(jwt.FromEd25519PublicKey(pub, "key-1"))

	var claims MyClaims

	err := jwt.Parse(context.Background(), token, &claims, keys,
		jwt.WithAllowedAlgorithms(jwt.Ed25519), // mandatory
		jwt.WithIssuer("https://auth.example.com"),
		jwt.WithAudience("https://api.example.com"),
	)
	fmt.Println(err, claims.Role)
}
Output:
<nil> admin

Index

Examples

Constants

View Source
const (
	MaxKeySetKeys       = 128
	MaxJWKJSONBytes     = 64 << 10
	MaxJWKMaterialBytes = 8 << 10
	MaxKeySetJSONBytes  = MaxKeySetKeys*MaxJWKJSONBytes + 1024
)

Defensive limits for untrusted JWKS documents. They permit 8192-bit RSA moduli and unusually large symmetric keys while bounding parser allocation.

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 CMWClaimName = "cmw"

CMWClaimName is the "cmw" JWT claim registered by RFC 9999 §9.2: a RATS Conceptual Message Wrapper carried in a JWT Claims Set.

View Source
const CMWContentType = "application/cmw+json"

CMWContentType is the "cty" of a JWS whose payload is a JSON CMW (RFC 9999 §4.2, §9.5.2).

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 reports a JWS signature or MAC that does not verify
	// (RFC 7515 §5.2 step 8).
	ErrInvalidSignature = internalalg.ErrInvalidSignature
	// ErrExpired reports that the current time is not before "exp" (minus
	// leeway) — RFC 7519 §4.1.4.
	ErrExpired = errors.New("jwt: token expired")
	// ErrNotYetValid reports that the current time is before "nbf" (plus
	// leeway) — RFC 7519 §4.1.5.
	ErrNotYetValid = errors.New("jwt: token not yet valid")
	// ErrIssuerMismatch reports an "iss" different from WithIssuer
	// (RFC 7519 §4.1.1, RFC 8725 §3.8).
	ErrIssuerMismatch = errors.New("jwt: issuer mismatch")
	// ErrAudienceMismatch reports an "aud" that does not identify this
	// recipient, or a missing "aud" when WithAudience is set (RFC 7519 §4.1.3,
	// RFC 8725 §3.9).
	ErrAudienceMismatch = errors.New("jwt: audience mismatch")
	// ErrAlgorithmNotAllowed reports a header "alg" (or JWE "enc") outside the
	// caller's allowlist, "none", or a key family that cannot serve the
	// algorithm (RFC 8725 §3.1).
	ErrAlgorithmNotAllowed = errors.New("jwt: algorithm not in allowlist")
	// ErrNoAllowedAlgorithms reports a missing mandatory allowlist — a
	// configuration error, not a token error (RFC 8725 §3.1).
	ErrNoAllowedAlgorithms = errors.New("jwt: WithAllowedAlgorithms is required")
	// ErrMissingClaim reports a claim required by WithRequiredClaims or a
	// profile validator (e.g. RFC 9068 §2.2) that is absent.
	ErrMissingClaim = errors.New("jwt: required claim missing")
	// ErrMalformedToken reports input that is not a well-formed compact
	// JWS/JWT: wrong segment count, non-canonical base64url, invalid or
	// duplicate-member JSON, a non-object header or claim set, or oversize.
	ErrMalformedToken = errors.New("jwt: malformed token")
	// ErrTypeMismatch reports a "typ" header different from WithRequiredType
	// (RFC 8725 §3.11).
	ErrTypeMismatch = errors.New("jwt: unexpected \"typ\" header")

	// ErrWeakKey reports key material below the enforced minimum: HMAC keys
	// shorter than the hash output (RFC 7518 §3.2), RSA below 2048 bits
	// (RFC 7518 §3.3, §4.2).
	ErrWeakKey = internalalg.ErrWeakKey
	// ErrUnsupportedAlgorithm reports an algorithm with no built-in
	// implementation, or a nil Signer/Encrypter/Decrypter.
	ErrUnsupportedAlgorithm = internalalg.ErrUnsupportedAlgorithm
	// ErrKeyNotFound reports that the KeyProvider has no key for the token's
	// "kid" (or several candidates for an empty "kid").
	ErrKeyNotFound = errors.New("jwt: no key for kid")
	// ErrKeyTypeMismatch reports key material of the wrong type or curve for
	// the requested algorithm (spec §4.10).
	ErrKeyTypeMismatch = internalalg.ErrKeyTypeMismatch
	// ErrMalformedKey reports unusable key material: invalid JWK members,
	// non-canonical encodings (RFC 7518 §6), points off the curve, or
	// unparsable DER/SSH input.
	ErrMalformedKey = internalalg.ErrMalformedKey
	// ErrOctNotServable is returned when marshaling a symmetric "oct" key,
	// which must never be published in a JWKS document (spec §5.3).
	ErrOctNotServable = errors.New("jwt: oct keys must not be serialized into a JWKS document")

	// ErrKeyUsage reports a key whose own "use", "key_ops" or "alg" member
	// (RFC 7517 §4.2–4.4) does not permit the requested operation.
	ErrKeyUsage = errors.New("jwt: key is not permitted for this operation")

	// ErrUnsupportedCritical reports a "crit" header (RFC 7515 §4.1.11,
	// RFC 7516 §4.1.13) listing extensions this library does not implement,
	// or a malformed "crit" value. Such a token is always invalid.
	ErrUnsupportedCritical = errors.New("jwt: unsupported critical header parameter")
)

Sentinel errors. All are comparable with errors.Is (spec §6.3); returned errors usually wrap one of them with detail that is safe to log but not meant for clients (see WriteChallenge).

View Source
var (
	// ErrInvalidClaims reports that a value supplied for signing is not a JWT
	// Claims Set JSON object. Marshal errors keep their original identity and
	// are not replaced by this sentinel.
	ErrInvalidClaims = errors.New("jwt: invalid Claims Set")
	// ErrInvalidDestination reports a nil destination passed to Parse,
	// ParseInsecure or ClaimsFromContext. Destinations are otherwise updated
	// atomically: any error leaves the caller's value unchanged.
	ErrInvalidDestination = errors.New("jwt: nil claims destination")
)
View Source
var (
	// ErrInvalidRevocationID reports an empty identifier. Empty IDs are never
	// accepted because they collapse unrelated tokens into one namespace entry.
	ErrInvalidRevocationID = errors.New("jwt: revocation id must not be empty")
	// ErrInvalidRevocationCapacity reports a non-positive bounded capacity.
	ErrInvalidRevocationCapacity = errors.New("jwt: revocation capacity must be positive")
	// ErrRevocationStoreFull reports that a bounded store cannot safely retain
	// another live revocation. Live revocations are never silently evicted.
	ErrRevocationStoreFull = errors.New("jwt: revocation store capacity reached")
)
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 ErrInvalidClaim = errors.New("jwt: invalid claim value")

ErrInvalidClaim reports a present claim whose value violates the claim's profile syntax or cross-claim constraints. It is distinct from ErrMissingClaim; profile validators wrap it with the claim name and detail.

View Source
var ErrKeyFetch = errors.New("jwt: fetching remote keys failed")

ErrKeyFetch reports that remote key material could not be obtained: a network or TLS failure, a non-200 response, an oversized or malformed document, a redirect away from HTTPS, or an OIDC discovery document that fails validation. It signals an infrastructure problem, not a bad token.

View Source
var ErrKeyProvider = errors.New("jwt: KeyProvider lookup failed")

ErrKeyProvider marks an infrastructure error returned by KeyProvider.Lookup. The returned error also wraps the provider's original error.

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.

View Source
var ErrVerifierProvider = errors.New("jwt: VerifierProvider lookup failed")

ErrVerifierProvider marks an infrastructure error returned by VerifierProvider.LookupVerifier. The returned error also wraps the provider's original error.

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 matches case-insensitively (RFC 9110 §11.1) and is followed by one or more spaces; the token must match the b64token syntax: 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"=". A request with several Authorization headers is rejected as ambiguous. The form-body and URI-query methods (§2.2–2.3) are not supported.

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). Decoding is atomic: dst is assigned only after complete successful decoding:

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). dst is updated atomically: every failure leaves its previous value unchanged.

Both JWE allowlists are mandatory (RFC 8725 §3.1, spec §4.1): WithAllowedKeyAlgorithms for "alg" and WithAllowedContentAlgorithms for "enc"; without them DecryptClaims returns ErrNoAllowedAlgorithms. They are checked against the protected header before dec is called, so they hold for caller-supplied Decrypters too. The AEAD tag is verified before any plaintext is exposed (spec §4.7). WithRequiredType applies to the JWE protected header's "typ". Nil options are ignored.

Example
package main

import (
	"context"
	"fmt"

	"github.com/NyeKo-ItL/jwt"
)

type MyClaims struct {
	jwt.RegisteredClaims
	Role string `json:"role,omitempty"`
}

func main() {
	// Direct claims encryption is appropriate here because both parties share
	// the same authenticated symmetric key. For public-key JWE, use a signed
	// inner JWT with EncryptNestedJWT / DecryptNestedJWT instead.
	key := []byte("0123456789abcdef0123456789abcdef")
	enc, _ := jwt.NewDirectEncrypter(key, jwt.A256GCM, "enc-1")
	compact, _ := jwt.EncryptClaims(MyClaims{Role: "billing"}, enc)

	dec, _ := jwt.NewDirectDecrypter(key, "enc-1")

	var claims MyClaims

	err := jwt.DecryptClaims(context.Background(), compact, &claims, dec,
		jwt.WithAllowedKeyAlgorithms(jwt.Direct),      // mandatory "alg" allowlist
		jwt.WithAllowedContentAlgorithms(jwt.A256GCM), // mandatory "enc" allowlist
	)
	fmt.Println(err, claims.Role)
}
Output:
<nil> billing

func DecryptNestedJWT added in v1.0.0

func DecryptNestedJWT[C any](ctx context.Context, compact string, dst *C, dec Decrypter, keys KeyProvider, policies NestedJWTPolicies) error

DecryptNestedJWT authenticates and decrypts an outer compact JWE, requires its protected "cty" to be "JWT", then verifies and validates the inner JWS through the same internal path as Parse. The destination is updated only after both layers and the final decode succeed.

func DiscoverJWKSURI

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

DiscoverJWKSURI resolves the "jwks_uri" of an OpenID Provider from its discovery document, as specified by OpenID Connect Discovery 1.0:

  • issuer must be an https URL with no query or fragment (OIDC Core §2);
  • the document is fetched from issuer, minus any terminating "/", plus "/.well-known/openid-configuration" (Discovery §4);
  • the document's "issuer" MUST be identical to the issuer requested (Discovery §4.3), which defeats mix-up and substituted documents;
  • "jwks_uri" must be present and https.

Every failure — network, status, size, JSON, policy, or validation — wraps ErrKeyFetch; there is no silent fallback to a guessed URL. A nil client uses a default client with a 30-second timeout; a supplied client is copied.

The optional policy is applied to the issuer discovery URL, every redirect, and the discovered jwks_uri. When omitted, the default rejects direct local and private-looking targets. The application MUST preapprove issuer hostnames; the default deliberately avoids a DNS lookup that could create a check/dial TOCTOU gap.

func EncryptClaims

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

EncryptClaims is the JWE analogue of Sign: it JSON-marshals a claims value that must encode as an object, then encrypts it as compact JWE. opts set the JWE protected header and may be reused through EncryptOptions.

func EncryptJWE added in v1.0.0

func EncryptJWE(plaintext []byte, enc Encrypter, opts ...EncryptOption) (string, error)

EncryptJWE encrypts plaintext as compact JWE and applies protected-header options. Built-in encrypters support options; a caller-defined Encrypter is supported when no effective option is supplied.

func EncryptNestedJWT added in v1.0.0

func EncryptNestedJWT(compactJWS string, enc Encrypter, opts ...EncryptOption) (string, error)

EncryptNestedJWT encrypts a syntactically valid compact JWS and forces the outer protected-header "cty" to "JWT" (RFC 7519 §5.2). The JWS must already be signed; its signature is intentionally verified only by the recipient.

func Equal deprecated

func Equal(storedHash, raw string) bool

Equal reports whether raw matches storedHash.

Deprecated: use VerifyOpaqueTokenHash.

func Hash deprecated

func Hash(raw string) string

Hash returns the SHA-256 hex digest of raw.

Deprecated: use HashOpaqueToken.

func HashOpaqueToken added in v1.0.0

func HashOpaqueToken(raw string) string

HashOpaqueToken returns the SHA-256 hex digest persisted for a raw opaque token.

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 failure it does not call next: it reports the error to MiddlewareOptions.OnError (if set) and answers via WriteChallenge — 401/400 with an RFC 6750 §3 challenge for token problems, 503 or 500 without details for infrastructure or configuration problems.

Example
package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"

	"github.com/NyeKo-ItL/jwt"
)

type MyClaims struct {
	jwt.RegisteredClaims
	Role string `json:"role,omitempty"`
}

func main() {
	secret := []byte("0123456789abcdef0123456789abcdef")
	keys := jwt.StaticKeyProvider(jwt.FromHMACSecret(secret))

	handler := jwt.Middleware(keys,
		jwt.WithAllowedAlgorithms(jwt.HS256),
		jwt.WithAudience("https://api.example.com"),
		jwt.MiddlewareOptions{
			Realm: "api",
			OnError: func(r *http.Request, err error) {
				slog.DebugContext(r.Context(), "bearer authentication failed", "err", err)
			},
		},
	)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var claims MyClaims
		if err := jwt.ClaimsFromContext(r.Context(), &claims); err != nil {
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}

		if claims.Role != "admin" {
			jwt.WriteInsufficientScope(w, "api", "admin")
			return
		}

		_, _ = fmt.Fprintln(w, "hello", claims.Subject)
	}))

	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
	fmt.Println(rec.Code, rec.Header().Get("WWW-Authenticate"))
}
Output:
401 Bearer realm="api"

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

Registered-claim validation runs regardless of what dst models. Decoding is atomic: dst is assigned only after complete successful decoding. Nil options are ignored. 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

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

ParseEd25519PublicKey parses a raw 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"). The compact input must still contain exactly three segments. Decoding is atomic: dst is assigned only after complete successful decoding.

func ParseKeySetPermissive added in v1.0.0

func ParseKeySetPermissive(data []byte) (*KeySet, []KeySetDiagnostic, error)

ParseKeySetPermissive parses an RFC 7517 §5 JWK Set while ignoring members whose key type or representation is not understood. Each ignored member is reported in diagnostics. Document-level syntax and all resource limits stay fatal; valid understood keys are returned in their original order.

func ParseOpenSSHPrivateKey

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

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

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

ParsePKCS8PrivateKey parses a DER-encoded PKCS#8 private key.

func ParsePKIXPublicKey

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

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 — which must marshal to a JSON object — 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". Nil options are ignored. Errors returned by a custom Signer are wrapped with context while retaining their identity for errors.Is/errors.As.

func SignCMW added in v1.1.0

func SignCMW(cmw CMW, signer Signer, opts ...SignOption) (string, error)

SignCMW signs a JSON CMW as a compact JWS (RFC 9999 §4.2): the payload is the CMW itself, not a JWT Claims Set, and the protected header carries "alg" and "cty": "application/cmw+json". "typ" is omitted unless WithType sets it; "cty" cannot be overridden. The CMW is validated first.

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, iat and jti MUST be present. It also validates the RFC 7519 StringOrURI syntax of iss, sub, and every aud value without normalizing them.

Example
package main

import (
	"context"
	"crypto/ed25519"
	"crypto/rand"
	"fmt"
	"slices"
	"strings"
	"time"

	"github.com/NyeKo-ItL/jwt"
)

func main() {
	pub, priv, _ := ed25519.GenerateKey(rand.Reader)
	signer, _ := jwt.NewEd25519Signer(priv)
	now := time.Now()

	// Authorization server side: RFC 9068 requires typ "at+jwt".
	token, _ := jwt.Sign(jwt.AccessTokenClaims{
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "https://auth.example.com",
			Subject:   "user-42",
			Audience:  jwt.Audience{"https://api.example.com"},
			IssuedAt:  jwt.NewNumericDate(now),
			ExpiresAt: jwt.NewNumericDate(now.Add(5 * time.Minute)),
			ID:        "at-1",
		},
		ClientID: "web-app",
		Scope:    "orders:read",
	}, signer, jwt.WithType(jwt.AccessTokenType))

	// Resource server side: every RFC 9068 §4 check.
	var at jwt.AccessTokenClaims

	err := jwt.Parse(context.Background(), token, &at, jwt.StaticKeyProvider(jwt.FromEd25519PublicKey(pub)),
		jwt.WithAllowedAlgorithms(jwt.Ed25519),
		jwt.WithRequiredType(jwt.AccessTokenType),
		jwt.WithIssuer("https://auth.example.com"),
		jwt.WithAudience("https://api.example.com"),
	)
	if err == nil {
		err = jwt.ValidateAccessTokenClaims(at)
	}

	fmt.Println(err, slices.Contains(strings.Fields(at.Scope), "orders:read"))
}
Output:
<nil> true

func ValidateIDTokenClaims added in v1.0.0

func ValidateIDTokenClaims(claims IDTokenClaims) error

ValidateIDTokenClaims validates the provider-neutral OIDC Core §2 ID-token profile. iss, sub, aud, exp and iat are required. iss, sub, aud, and azp use RFC 7519 StringOrURI syntax without normalization. azp is required for a multi-audience token and, whenever present, must identify one audience. at_hash and c_hash, when present, must be canonical unpadded base64url; their flow-specific digest comparison remains the caller's responsibility.

func ValidateIDTokenForContext added in v1.0.0

func ValidateIDTokenForContext(claims IDTokenClaims, validation IDTokenValidationContext) error

ValidateIDTokenForContext applies ValidateIDTokenClaims and the OIDC checks that depend on relying-party state: client audience, additional trusted audiences, azp, nonce, at_hash, and c_hash. It performs exact comparisons and never normalizes identifiers.

func ValidateStringOrURI added in v1.0.0

func ValidateStringOrURI(value string) error

ValidateStringOrURI validates RFC 7519 §2 StringOrURI syntax. Values without a colon are arbitrary case-sensitive strings. Values containing a colon must be valid RFC 3986 URIs. The function validates only; it never normalizes, so callers can continue to compare issuer, subject, and audience values exactly.

func VerifyOpaqueTokenHash added in v1.0.0

func VerifyOpaqueTokenHash(storedHash, raw string) bool

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

func WriteChallenge

func WriteChallenge(w http.ResponseWriter, realm string, err error)

WriteChallenge answers a failed bearer authentication. Responses carry only fixed text, never err's message, so internal detail (hostnames, backend errors) cannot leak to clients:

  • nil: 401 with a bare "WWW-Authenticate: Bearer" challenge — credentials required (RFC 6750 §3.1, no error code);
  • ErrMalformedToken: 400, error="invalid_request";
  • a token failure (bad signature, expired, wrong issuer/audience, unknown kid, disallowed algorithm, ...): 401, error="invalid_token", with a generic error_description ("expired" and "not yet valid" are named);
  • ErrKeyFetch or a context cancellation/deadline: 503, no challenge;
  • anything else (misconfiguration such as ErrNoAllowedAlgorithms, a KeyProvider backend failure, a broken stored key): 500, no challenge.

realm, when non-empty, is included in challenges with quotes, backslashes and control characters removed.

func WriteInsufficientScope added in v0.2.0

func WriteInsufficientScope(w http.ResponseWriter, realm string, scopes ...string)

WriteInsufficientScope writes the RFC 6750 §3.1 "insufficient_scope" response (403) for a valid token that lacks the scopes a resource needs. Scope values that are not RFC 6749 §3.3 scope-tokens are omitted.

Types

type AccessTokenClaims

type AccessTokenClaims struct {
	RegisteredClaims

	// ClientID is "client_id" (RFC 9068 §2.2, RFC 8693 §4.3): the OAuth
	// client the token was issued to. REQUIRED.
	ClientID string `json:"client_id"`
	// Scope is "scope" (RFC 9068 §2.2.3): space-separated scope-tokens.
	Scope string `json:"scope,omitempty"`
	// AuthTime is "auth_time" (RFC 9068 §2.2.1, OIDC Core §2).
	AuthTime *NumericDate `json:"auth_time,omitempty"`
	// ACR is "acr", the authentication context class (RFC 9068 §2.2.1).
	ACR string `json:"acr,omitempty"`
	// AMR is "amr", the authentication methods (RFC 9068 §2.2.1, RFC 8176).
	AMR []string `json:"amr,omitempty"`
	// Groups is "groups" (RFC 9068 §2.2.3.1, RFC 7643 §4.1.2).
	Groups []string `json:"groups,omitempty"`
	// Roles is "roles" (RFC 9068 §2.2.3.1, RFC 7643 §4.1.2).
	Roles []string `json:"roles,omitempty"`
	// Entitlements is "entitlements" (RFC 9068 §2.2.3.1, RFC 7643 §4.1.2).
	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"`      // full mailing address, may contain newlines
	StreetAddress string `json:"street_address,omitempty"` // street, house number, apartment, ...
	Locality      string `json:"locality,omitempty"`       // city
	Region        string `json:"region,omitempty"`         // state, province, prefecture or region
	PostalCode    string `json:"postal_code,omitempty"`    // zip or postal code
	Country       string `json:"country,omitempty"`        // country name
}

Address is the OIDC Core 1.0 §5.1.1 address claim.

type Algorithm

type Algorithm = internalalg.Algorithm

Algorithm identifies a JWS signing algorithm (RFC 7518 §3, RFC 9864 §2.2). It is an open string type, not a closed enum: callers may define custom algorithm values for their own Signer/Verifier implementations.

const (
	HS256 Algorithm = internalalg.HS256 // RFC 7518 §3.2: HMAC SHA-256, key >= 32 bytes
	HS384 Algorithm = internalalg.HS384 // RFC 7518 §3.2: HMAC SHA-384, key >= 48 bytes
	HS512 Algorithm = internalalg.HS512 // RFC 7518 §3.2: HMAC SHA-512, key >= 64 bytes
	RS256 Algorithm = internalalg.RS256 // RFC 7518 §3.3: RSASSA-PKCS1-v1_5 SHA-256, verify-only, >= 2048 bits
	RS384 Algorithm = internalalg.RS384 // RFC 7518 §3.3: RSASSA-PKCS1-v1_5 SHA-384, verify-only
	RS512 Algorithm = internalalg.RS512 // RFC 7518 §3.3: RSASSA-PKCS1-v1_5 SHA-512, verify-only
	PS256 Algorithm = internalalg.PS256 // RFC 7518 §3.5: RSASSA-PSS SHA-256, MGF1, salt = hash size
	PS384 Algorithm = internalalg.PS384 // RFC 7518 §3.5: RSASSA-PSS SHA-384
	PS512 Algorithm = internalalg.PS512 // RFC 7518 §3.5: RSASSA-PSS SHA-512
	ES256 Algorithm = internalalg.ES256 // RFC 7518 §3.4: ECDSA P-256 SHA-256, 64-byte R||S
	ES384 Algorithm = internalalg.ES384 // RFC 7518 §3.4: ECDSA P-384 SHA-384, 96-byte R||S
	ES512 Algorithm = internalalg.ES512 // RFC 7518 §3.4: ECDSA P-521 SHA-512, 132-byte R||S
	// Ed25519 is EdDSA using the Ed25519 parameter set (RFC 9864 §2.2,
	// RFC 8032 §5.1) — the fully-specified identifier the built-in Ed25519
	// signer emits.
	Ed25519 Algorithm = internalalg.Ed25519

	// EdDSA is the polymorphic identifier of RFC 8037 §3.1.
	//
	// Deprecated: RFC 9864 §4.1.2 deprecates "EdDSA" in favor of Ed25519.
	// It is still verified — over Ed25519 keys only — when explicitly listed
	// in WithAllowedAlgorithms, for tokens from issuers that have not
	// migrated; nothing in this library emits it.
	EdDSA Algorithm = internalalg.EdDSA
)

Built-in JWS algorithms. Signing is offered for HS*, PS*, ES* and Ed25519; RS* is verify-only (spec §0.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 Bool added in v0.2.0

type Bool bool

Bool is an OIDC boolean claim such as "email_verified". OpenID Connect Core 1.0 §5.1 defines these as JSON booleans, but some providers emit the strings "true" / "false" instead (Google's documented example, Amazon Cognito). Bool accepts exactly those four forms and always marshals as a JSON boolean. Its underlying type is bool, so it can be used directly in conditions: if claims.EmailVerified != nil && *claims.EmailVerified { ... }.

func (*Bool) UnmarshalJSON added in v0.2.0

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

UnmarshalJSON accepts true, false, "true" or "false".

type CMW added in v1.1.0

type CMW struct {
	Record     *CMWRecord
	Collection *CMWCollection
}

CMW is a JSON CMW: exactly one of Record and Collection is set.

func ParseCMW added in v1.1.0

func ParseCMW(data []byte) (CMW, error)

ParseCMW decodes and validates a JSON CMW per the RFC 9999 §6 CDDL. Duplicate member names and malformed members are rejected; errors wrap ErrInvalidClaim.

func ParseSignedCMW added in v1.1.0

func ParseSignedCMW(ctx context.Context, token string, keys KeyProvider, opts ...ParseOption) (CMW, error)

ParseSignedCMW verifies a compact JWS produced by SignCMW and returns the validated CMW. It applies the same defences as Parse (mandatory WithAllowedAlgorithms, key lookup by "kid" only, no "none"), requires "cty": "application/cmw+json" (RFC 9999 §4.2), and skips the JWT claims checks (exp, iss, aud), which do not apply to a CMW; ParseOptions about claims are ignored. A JWT is rejected: its payload is not a CMW.

func (CMW) MarshalJSON added in v1.1.0

func (c CMW) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. The CMW is validated first, so an invalid value never reaches a token.

func (*CMW) UnmarshalJSON added in v1.1.0

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

UnmarshalJSON implements json.Unmarshaler with the rules of ParseCMW.

func (CMW) Validate added in v1.1.0

func (c CMW) Validate() error

Validate reports whether c is a well-formed CMW (RFC 9999 §6).

type CMWClaims added in v1.1.0

type CMWClaims struct {
	RegisteredClaims

	// CMW is "cmw" (RFC 9999 §4.3): a record or a collection.
	CMW *CMW `json:"cmw,omitempty"`
}

CMWClaims is a JWT Claims Set carrying the RFC 9999 "cmw" claim next to the RFC 7519 registered claims.

type CMWCollection added in v1.1.0

type CMWCollection struct {
	// Type is "__cmwc_t": an absolute URI or an OID in dotted form; empty
	// when absent.
	Type string
	// Members are the labelled CMWs; at least one is required.
	Members map[string]CMW
}

CMWCollection is a JSON-encoded collection CMW (RFC 9999 §3.3): an object of labelled CMWs with an optional "__cmwc_t" collection type.

type CMWIndicator added in v1.1.0

type CMWIndicator uint32

CMWIndicator is the "ind" bitmap of a CMW record (RFC 9999 §3.1): bit n is set when the record carries the RATS conceptual message with indicator value n in the IANA "RATS Conceptual Message Wrapper (CMW) Indicators" registry. Bits 5–31 are unassigned and are preserved, not rejected.

const (
	CMWReferenceValues    CMWIndicator = 1 << 0
	CMWEndorsements       CMWIndicator = 1 << 1
	CMWEvidence           CMWIndicator = 1 << 2
	CMWAttestationResults CMWIndicator = 1 << 3
	CMWAppraisalPolicy    CMWIndicator = 1 << 4
)

The initial indicator bits (RFC 9999 §9.4).

type CMWRecord added in v1.1.0

type CMWRecord struct {
	// Type is the media type of the wrapped conceptual message.
	Type string
	// Value is the decoded conceptual message.
	Value []byte
	// Indicator is the optional "ind" bitmap; nil when absent.
	Indicator *CMWIndicator
}

CMWRecord is a JSON-encoded record CMW (RFC 9999 §3.1): [type, value, ind?]. The wire form of Value is unpadded base64url.

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" // AES-128-GCM, 16-byte CEK
	A192GCM ContentAlgorithm = "A192GCM" // AES-192-GCM, 24-byte CEK
	A256GCM ContentAlgorithm = "A256GCM" // AES-256-GCM, 32-byte CEK
)

AES-GCM content encryption with a 96-bit IV and 128-bit tag (RFC 7518 §5.3).

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. Keys must be complete, internally consistent, and at most 8192 bits.

type EncryptOption added in v1.0.0

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

EncryptOption customizes the protected header emitted by EncryptJWE, EncryptClaims, and EncryptNestedJWT. Nil options are ignored.

func WithJWEContentType added in v1.0.0

func WithJWEContentType(cty string) EncryptOption

WithJWEContentType sets the JWE protected-header "cty" parameter.

func WithJWEType added in v1.0.0

func WithJWEType(typ string) EncryptOption

WithJWEType sets the JWE protected-header "typ" parameter.

type EncryptOptions added in v1.0.0

type EncryptOptions struct {
	Type        string // "typ" (RFC 7516 §4.1.11)
	ContentType string // "cty" (RFC 7516 §4.1.12)
}

EncryptOptions is the reusable form of the JWE protected-header options. Empty values omit the corresponding header parameter.

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. This asymmetric JWE encryption authenticates the ciphertext to the recipient but does not authenticate its sender; sign before encrypting, preferably with EncryptNestedJWT, when issuer authentication is required.

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 must be between 2048 and 8192 bits. This asymmetric JWE encryption authenticates the ciphertext to the recipient but does not authenticate its sender; sign before encrypting, preferably with EncryptNestedJWT, when issuer authentication is required.

type EntraClaims

type EntraClaims struct {
	TenantID   string   `json:"tid,omitempty"`         // tenant GUID; restrict accepted tenants with it
	ObjectID   string   `json:"oid,omitempty"`         // immutable user object GUID within the tenant
	UPN        string   `json:"upn,omitempty"`         // user principal name; mutable, not an identifier
	Roles      []string `json:"roles,omitempty"`       // app roles assigned to the user
	Groups     []string `json:"groups,omitempty"`      // group object IDs, when the groups claim is configured
	AppID      string   `json:"appid,omitempty"`       // v1.0 tokens: application ID of the client
	Version    string   `json:"ver,omitempty"`         // "1.0" or "2.0"
	UniqueName string   `json:"unique_name,omitempty"` // v1.0 tokens: display-only name

	IdentityProvider string `json:"idp,omitempty"` // authenticating IdP when it differs from iss (e.g. guests)
	SessionID        string `json:"sid,omitempty"` // session GUID
	TokenID          string `json:"uti,omitempty"` // Entra's per-token identifier, equivalent to jti
}

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 requests. The client is copied, never modified: the copy wraps its CheckRedirect so that no redirect may leave HTTPS, then defers to the caller's own policy.

func WithMaxCacheDuration added in v0.2.0

func WithMaxCacheDuration(d time.Duration) FetcherOption

WithMaxCacheDuration caps how long a Cache-Control max-age hint may keep a document fresh (default 24 hours). Non-positive values are ignored.

func WithMaxKeyCount added in v1.0.0

func WithMaxKeyCount(n int) FetcherOption

WithMaxKeyCount caps the number of keys accepted in one JWKS document (default 100). Non-positive values are ignored.

func WithMaxResponseBytes

func WithMaxResponseBytes(n int64) FetcherOption

WithMaxResponseBytes caps the JWKS response body size (default 1 MiB).

func WithMaxStaleDuration added in v1.0.0

func WithMaxStaleDuration(d time.Duration) FetcherOption

WithMaxStaleDuration sets how long a stale cached document may be used when refresh fails (default 24 hours). Zero disables stale serving. Negative values are ignored.

func WithMinRefreshInterval

func WithMinRefreshInterval(d time.Duration) FetcherOption

WithMinRefreshInterval sets the shortest interval between network attempts triggered by Lookup (default 1 minute). It also acts as the retry backoff after a failed attempt. Refresh bypasses it.

func WithURLPolicy added in v1.0.0

func WithURLPolicy(policy URLPolicy) FetcherOption

WithURLPolicy replaces the default URL/network policy. Use an allowlist policy when the URI or issuer originates from untrusted input. A nil policy is ignored. The policy does not replace HTTPS validation.

type GoogleClaims

type GoogleClaims struct {
	HostedDomain    string `json:"hd,omitempty"`      // Google Workspace domain of the user
	AuthorizedParty string `json:"azp,omitempty"`     // OIDC Core §2: client the token was issued to
	AccessTokenHash string `json:"at_hash,omitempty"` // OIDC Core §3.2.2.9; not verified by Parse
}

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 is "alg" (RFC 7515 §4.1.1): checked against the mandatory
	// allowlist before anything else.
	Algorithm Algorithm `json:"alg"`
	// Type is "typ" (§4.1.9), compared by WithRequiredType (RFC 8725 §3.11).
	Type string `json:"typ,omitempty"`
	// ContentType is "cty" (§4.1.10); "JWT" marks a nested JWT, which is not
	// unwrapped automatically.
	ContentType string `json:"cty,omitempty"`
	// KeyID is "kid" (§4.1.4), passed to KeyProvider.Lookup.
	KeyID string `json:"kid,omitempty"`
	// JWKSetURL is "jku" (§4.1.2). Never fetched (RFC 8725 §3.10).
	JWKSetURL string `json:"jku,omitempty"`
	// JWK is "jwk" (§4.1.3). Never trusted to verify the token.
	JWK *Key `json:"jwk,omitempty"`
	// X509URL is "x5u" (§4.1.5). Never fetched.
	X509URL string `json:"x5u,omitempty"`
	// X509CertChain is "x5c" (§4.1.6), base64 (not base64url) DER
	// certificates. Not validated or trusted.
	X509CertChain []string `json:"x5c,omitempty"`
	// X509CertSHA1 is "x5t" (§4.1.7). Informational only.
	X509CertSHA1 string `json:"x5t,omitempty"`
	// X509CertSHA256 is "x5t#S256" (§4.1.8). Informational only.
	X509CertSHA256 string `json:"x5t#S256,omitempty"`
	// Critical is "crit" (§4.1.11). No extension is implemented, so Parse
	// rejects any token carrying it (ErrUnsupportedCritical).
	Critical []string `json:"crit,omitempty"`
	// EncapsulatedKey is "ek", a base64url-encoded HPKE encapsulated secret
	// (RFC-ietf-jose-hpke-encrypt-22 §4.1). It is parsed for inspection only;
	// HPKE is not implemented by this package.
	EncapsulatedKey string `json:"ek,omitempty"`
	// PreSharedKeyID is "psk_id", the base64url-encoded HPKE pre-shared-key
	// identifier (RFC-ietf-jose-hpke-encrypt-22 §4). It is parsed for
	// inspection only; HPKE is not implemented by this package.
	PreSharedKeyID string `json:"psk_id,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 IDTokenClaims added in v1.0.0

type IDTokenClaims struct {
	RegisteredClaims
	StandardClaims

	// AuthorizedParty is "azp": the client to which the ID Token was issued.
	AuthorizedParty string `json:"azp,omitempty"`
	// AccessTokenHash is "at_hash" (OIDC Core §3.1.3.6/§3.2.2.9).
	AccessTokenHash string `json:"at_hash,omitempty"`
	// CodeHash is "c_hash" (OIDC Core §3.3.2.11).
	CodeHash string `json:"c_hash,omitempty"`
	// AuthTime is "auth_time": time of end-user authentication.
	AuthTime *NumericDate `json:"auth_time,omitempty"`
	// ACR is "acr": authentication context class reference.
	ACR string `json:"acr,omitempty"`
	// AMR is "amr": authentication method references (RFC 8176 values).
	AMR []string `json:"amr,omitempty"`
}

IDTokenClaims is the provider-neutral OpenID Connect Core 1.0 ID Token Claims Set. Embed it in an application-specific ID-token type when the provider-specific ready-made types below are not appropriate.

AccessTokenHash and CodeHash carry the OIDC half-hash values. This package validates their base64url representation but cannot recompute them without the access token or authorization code; the relying party remains responsible for that flow-specific comparison. Nonce is available through StandardClaims and likewise requires comparison with the authentication request by the relying party.

type IDTokenValidationContext added in v1.0.0

type IDTokenValidationContext struct {
	ClientID          string
	TrustedAudiences  []string
	ExpectedNonce     string
	RequireNonce      bool
	AccessToken       string
	AuthorizationCode string
	SigningAlgorithm  Algorithm
}

IDTokenValidationContext supplies the relying-party state needed for the flow-dependent checks in OIDC Core §3.1.3.7. ClientID is required. Additional trusted audiences, expected nonce, access token, and authorization code are optional and checked when configured or when the corresponding hash claim is present.

type Key

type Key struct {
	// Kty is "kty" (RFC 7517 §4.1); it must match the algorithm family.
	Kty KeyType
	// Kid is "kid" (RFC 7517 §4.5), matched against the token header "kid".
	Kid string
	// Use is the RFC 7517 §4.2 public key use: "sig" or "enc". When set to
	// anything other than "sig", the key cannot verify signatures.
	Use string
	// KeyOps is the RFC 7517 §4.3 list of permitted operations. When
	// non-empty, it must contain "verify" for the key to verify signatures.
	KeyOps []string
	// Alg is the RFC 7517 §4.4 algorithm the key is intended for. When set,
	// the key only verifies tokens whose header "alg" is identical
	// (RFC 8725 §3.1: one key, one algorithm).
	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) Clone added in v1.0.0

func (k Key) Clone() Key

Clone returns a deep copy of k, including KeyOps and all key material.

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. Beyond JSON and base64url validity it rejects, with an error wrapping ErrMalformedKey, the encodings that would give one key several representations (and thus several RFC 7638 thumbprints): RSA "n"/"e" with leading zero octets (RFC 7518 §6.3.1.1), EC coordinates that are not exactly the curve's coordinate size (RFC 7518 §6.2.1.2), and Ed25519 "x" that is not 32 bytes (RFC 8037 §2). It also rejects duplicate "key_ops" values and a "key_ops" inconsistent with "use" (RFC 7517 §4.3).

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"        // RFC 7518 §4.6: direct key agreement (P-256/384/521)
	ECDHESA256KW KeyAlgorithm = "ECDH-ES+A256KW" // RFC 7518 §4.6: key agreement + AES-256 Key Wrap
	RSAOAEP256   KeyAlgorithm = "RSA-OAEP-256"   // RFC 7518 §4.3: RSAES-OAEP, SHA-256 and MGF1-SHA-256
	A256KW       KeyAlgorithm = "A256KW"         // RFC 7518 §4.4: AES-256 Key Wrap (RFC 3394)
	Direct       KeyAlgorithm = "dir"            // RFC 7518 §4.5: pre-shared symmetric CEK
)

Built-in JWE key-management algorithms.

type KeyFetcher

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

KeyFetcher retrieves and caches a remote JWKS document (RFC 7517 §5); it satisfies KeyProvider directly, so it plugs in wherever a KeySet would.

Hardening, all on by default:

  • HTTPS only, including every redirect hop (a redirect to any other scheme fails with ErrKeyFetch).
  • The response body is size-capped (WithMaxResponseBytes).
  • Concurrent lookups share a single in-flight request, and network attempts — successful or not — are rate-limited to one per WithMinRefreshInterval, so unknown "kid" values or an unreachable upstream cannot amplify traffic.
  • Cache-Control is honored and max-age is capped (WithMaxCacheDuration), so a revoked key cannot stay pinned for long.
  • Failed refreshes may use the last good document only for the bounded WithMaxStaleDuration window; the default eventually fails closed.
  • The default URL policy rejects local, private-looking, and IP-literal targets. Callers must still preapprove issuer hostnames: no DNS lookup is performed because checking an address without binding the HTTP dial to that same address would introduce a DNS TOCTOU vulnerability.

func NewKeyFetcher

func NewKeyFetcher(uri string, opts ...FetcherOption) *KeyFetcher

NewKeyFetcher returns a KeyFetcher for the given JWKS URI. Nothing is fetched until the first Lookup or Refresh. The URI's issuer/host must be preapproved by the application even when the default URL policy is used.

Example
package main

import (
	"context"
	"time"

	"github.com/NyeKo-ItL/jwt"
)

func main() {
	ctx := context.Background()

	// OpenID Connect Discovery: the returned issuer must match exactly.
	uri, err := jwt.DiscoverJWKSURI(ctx, "https://accounts.google.com", nil)
	if err != nil {
		return // errors.Is(err, jwt.ErrKeyFetch)
	}

	keys := jwt.NewKeyFetcher(uri, jwt.WithMaxCacheDuration(6*time.Hour))

	var idt jwt.GoogleIDToken

	err = jwt.Parse(ctx, "raw-id-token", &idt, keys,
		jwt.WithAllowedAlgorithms(jwt.RS256),
		jwt.WithIssuer("https://accounts.google.com"),
		jwt.WithAudience("1234987819200.apps.googleusercontent.com"), // your client ID
		jwt.WithRequiredClaims("sub", "iat"),
	)
	if err != nil {
		return
	}

	// Relying-party checks the library cannot do for you (OIDC Core §3.1.3.7):
	expectedNonce := "value-stored-in-the-session"
	if idt.Nonce != expectedNonce {
		return
	}
}

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 and rate-limiting rules) the JWKS document as needed. It satisfies KeyProvider. A kid absent from a successfully fetched document is reported as not found with a nil error; a fetch failure is reported as ErrKeyFetch unless the last good document still holds the key.

func (*KeyFetcher) Refresh

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

Refresh forces an immediate re-fetch of the JWKS document, ignoring the rate limit. If a fetch is already in flight, Refresh joins it instead of starting another.

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. Parse wraps such errors with ErrKeyProvider
	// while preserving the original error for errors.Is/errors.As.
	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. Keys are deep-copied at every boundary, so callers cannot mutate material held by the set.

func NewKeySet

func NewKeySet(keys ...Key) *KeySet

NewKeySet returns a KeySet seeded with deep copies of keys.

func ParseKeySet

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

ParseKeySet parses a JWKS document ({"keys":[ ... ]}) in strict mode. A malformed or unsupported member rejects the complete set. The document, member count, member JSON size, and encoded key-material sizes are bounded by the exported Max* constants above.

func (*KeySet) Add

func (s *KeySet) Add(k Key)

Add inserts a deep copy of k, replacing any existing key with the same non-empty kid while retaining its insertion-order position.

func (*KeySet) Clone added in v1.0.0

func (s *KeySet) Clone() *KeySet

Clone returns an independent deep copy of s.

func (*KeySet) Keys

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

Keys returns a deep 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. Returned keys are deep copies.

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

Example
package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"encoding/json"
	"errors"
	"fmt"
	"strings"

	"github.com/NyeKo-ItL/jwt"
)

func main() {
	priv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

	key := jwt.FromECDSAPublicKey(&priv.PublicKey, "2026-09")
	key.Use, key.Alg = "sig", string(jwt.ES256) // RFC 8725 §3.1: one key, one algorithm

	doc, _ := json.Marshal(jwt.NewKeySet(key))
	fmt.Println(strings.HasPrefix(string(doc), `{"keys":[{"kty":"EC","kid":"2026-09","use":"sig","alg":"ES256","crv":"P-256"`))

	// Symmetric keys can never be published.
	_, err := json.Marshal(jwt.NewKeySet(jwt.FromHMACSecret([]byte("0123456789abcdef0123456789abcdef"))))
	fmt.Println(errors.Is(err, jwt.ErrOctNotServable))
}
Output:
true
true

func (*KeySet) Remove

func (s *KeySet) Remove(kid string)

Remove deletes every key with the given kid.

type KeySetDiagnostic added in v1.0.0

type KeySetDiagnostic struct {
	Index int
	Err   error
}

KeySetDiagnostic describes a key ignored by ParseKeySetPermissive.

func (KeySetDiagnostic) Error added in v1.0.0

func (d KeySetDiagnostic) Error() string

func (KeySetDiagnostic) Unwrap added in v1.0.0

func (d KeySetDiagnostic) Unwrap() error

Unwrap exposes the malformed-key cause for errors.Is/errors.As.

type KeyType

type KeyType string

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

const (
	KeyTypeRSA KeyType = "RSA" // RFC 7518 §6.3: "n", "e"
	KeyTypeEC  KeyType = "EC"  // RFC 7518 §6.2: "crv" (P-256/384/521), "x", "y"
	KeyTypeOKP KeyType = "OKP" // RFC 8037 §2: "crv" Ed25519, "x"
	KeyTypeOct KeyType = "oct" // RFC 7518 §6.4: "k"; never serialized into a JWKS

	// MaxRSAKeyBits bounds RSA work and JWK allocation. Larger RSA keys are
	// rejected by both JWK reconstruction and built-in JWS algorithms.
	MaxRSAKeyBits = 8192
)

Key types (RFC 7518 §6.1, RFC 8037 §2).

type MiddlewareOptions added in v0.2.0

type MiddlewareOptions struct {
	// Realm is sent as the "realm" challenge attribute (RFC 6750 §3).
	Realm string
	// OnError, when set, receives every verification failure with its full
	// detail, for logging. Clients only ever see the fixed, non-revealing
	// responses documented on WriteChallenge.
	OnError func(r *http.Request, err error)
}

MiddlewareOptions configures Middleware. It satisfies ParseOption so it can be passed alongside the parse options; Parse and DecryptClaims ignore it.

type NestedJWTPolicies added in v1.0.0

type NestedJWTPolicies struct {
	JWE []ParseOption
	JWS []ParseOption
}

NestedJWTPolicies keeps the outer JWE and inner JWS policies separate. JWE must contain WithAllowedKeyAlgorithms and WithAllowedContentAlgorithms. JWS must contain WithAllowedAlgorithms. Nil options in either slice are ignored.

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 seconds since the Unix epoch as a JSON number, preserving nanosecond precision when present. Integer times retain their compact form.

func (*NumericDate) UnmarshalJSON

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

UnmarshalJSON accepts only what RFC 7519 §2 defines: a JSON numeric value of seconds since the epoch, integer or fractional, or null (leaving the value unchanged). Strings — including "NaN" and "Inf" — are rejected, as are values outside years 1 to 9999, whose conversion to an integer would otherwise be platform-dependent.

type OktaClaims

type OktaClaims struct {
	Version  int          `json:"ver,omitempty"`       // a JSON number (e.g. 1) in Okta ID tokens
	AuthTime *NumericDate `json:"auth_time,omitempty"` // OIDC Core §2: time of the end-user authentication
	AMR      []string     `json:"amr,omitempty"`       // authentication methods, RFC 8176 values
	IDP      string       `json:"idp,omitempty"`       // Okta org or external IdP that authenticated the user
	Groups   []string     `json:"groups,omitempty"`    // present when a groups claim is configured
}

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 // the credential given to the client; never store it
	Hash string // hex SHA-256 of Raw; the only value to persist
}

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 deprecated

func DeriveOpaqueToken(raw string) OpaqueToken

DeriveOpaqueToken deterministically builds a token from caller-provided raw input.

Deprecated: use OpaqueTokenFromRaw. Derived tokens are only as strong as the input and must not be created from low-entropy secrets.

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.

func OpaqueTokenFromRaw added in v1.0.0

func OpaqueTokenFromRaw(raw string) OpaqueToken

OpaqueTokenFromRaw deterministically builds a token from raw instead of drawing fresh randomness. It performs only SHA-256 hashing, not password stretching: the token is only as strong as raw. Never use a password, short code, predictable identifier, or other low-entropy input.

func (OpaqueToken) GoString added in v1.0.0

func (t OpaqueToken) GoString() string

GoString redacts Raw for %#v formatting as well.

func (OpaqueToken) String added in v1.0.0

func (t OpaqueToken) String() string

String redacts Raw so logging an OpaqueToken does not disclose the bearer credential.

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 WithAllowedContentAlgorithms added in v0.2.0

func WithAllowedContentAlgorithms(encs ...ContentAlgorithm) ParseOption

WithAllowedContentAlgorithms sets the JWE content-encryption ("enc") allowlist that DecryptClaims requires (RFC 8725 §3.1). "none" and the empty string are never accepted, even if listed. Parse and Middleware ignore it.

func WithAllowedKeyAlgorithms added in v0.2.0

func WithAllowedKeyAlgorithms(algs ...KeyAlgorithm) ParseOption

WithAllowedKeyAlgorithms sets the JWE key-management ("alg") allowlist that DecryptClaims requires (RFC 8725 §3.1). "none" and the empty string are never accepted, even if listed. Parse and Middleware ignore it.

func WithAudience

func WithAudience(aud string) ParseOption

WithAudience identifies the recipient: aud must be one of the values of the "aud" claim (exact, case-sensitive string comparison), and a token without "aud" is rejected.

Without WithAudience, a token that carries an "aud" claim is rejected with ErrAudienceMismatch, because RFC 7519 §4.1.3 requires a principal that cannot identify itself with a value in "aud" to reject the JWT (see also RFC 8725 §3.9). Use WithoutAudienceCheck to opt out explicitly.

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 and non-null in the payload. False, zero, empty strings, and empty arrays remain present.

func WithRequiredType

func WithRequiredType(typ string) ParseOption

WithRequiredType requires the JOSE "typ" header — of the JWS for Parse, of the JWE protected header for DecryptClaims — to match typ as a media type (RFC 8725 §3.11, RFC 7515 §4.1.9).

func WithVerifierProvider added in v1.0.0

func WithVerifierProvider(provider VerifierProvider) ParseOption

WithVerifierProvider makes Parse and Middleware resolve a custom Verifier by the protected "alg" and "kid" values instead of using their KeyProvider argument. A nil provider is ignored. The mandatory algorithm allowlist and returned verifier algorithm/key-ID checks remain enforced.

func WithoutAudienceCheck added in v0.2.0

func WithoutAudienceCheck() ParseOption

WithoutAudienceCheck accepts a token carrying an "aud" claim even though no WithAudience is configured. It deliberately departs from RFC 7519 §4.1.3 and should be reserved for components that are not the token's recipient (e.g. a gateway that only inspects a token before forwarding it). It has no effect when WithAudience is also given: an explicit audience is always enforced.

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
	// AllowedKeyAlgorithms and AllowedContentAlgorithms are the mandatory JWE
	// "alg" and "enc" allowlists for DecryptClaims; Parse and Middleware
	// ignore them. They merge with WithAllowedKeyAlgorithms /
	// WithAllowedContentAlgorithms in the same call.
	AllowedKeyAlgorithms     []KeyAlgorithm
	AllowedContentAlgorithms []ContentAlgorithm // see AllowedKeyAlgorithms
	Issuer                   string             // require "iss" to equal this (RFC 7519 §4.1.1)
	Audience                 string             // require this to be present in "aud" (RFC 7519 §4.1.3)
	SkipAudienceCheck        bool               // accept a present "aud" when Audience is empty (see WithoutAudienceCheck)
	RequiredType             string             // require the JOSE "typ" header to match (RFC 8725 §3.11)
	RequiredClaims           []string           // require each named claim to be present and non-null
	Leeway                   time.Duration      // clock-skew allowance on "exp"/"nbf" (default 0)
	Clock                    func() time.Time   // time source for every time-based check (default time.Now)
	VerifierProvider         VerifierProvider   // custom verifier lookup for Parse/Middleware; replaces KeyProvider when non-nil
}

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.

Example
package main

import (
	"context"
	"crypto/ed25519"
	"crypto/rand"
	"fmt"

	"github.com/NyeKo-ItL/jwt"
)

type MyClaims struct {
	jwt.RegisteredClaims
	Role string `json:"role,omitempty"`
}

func main() {
	pub, priv, _ := ed25519.GenerateKey(rand.Reader)
	signer, _ := jwt.NewEd25519Signer(priv)
	token, _ := jwt.Sign(MyClaims{RegisteredClaims: jwt.RegisteredClaims{
		Issuer: "https://auth.example.com", Audience: jwt.Audience{"orders"},
	}}, signer)
	keys := jwt.StaticKeyProvider(jwt.FromEd25519PublicKey(pub))

	// Declare the shared policy once...
	apiOpts := jwt.ParseOptions{
		AllowedAlgorithms: []jwt.Algorithm{jwt.Ed25519},
		Issuer:            "https://auth.example.com",
	}

	// ...and add per-call settings.
	var claims MyClaims

	err := jwt.Parse(context.Background(), token, &claims, keys, apiOpts, jwt.WithAudience("orders"))
	fmt.Println(err)
}
Output:
<nil>

type RegisteredClaims

type RegisteredClaims struct {
	// Issuer is "iss" (RFC 7519 §4.1.1), checked by WithIssuer.
	Issuer string `json:"iss,omitempty"`
	// Subject is "sub" (RFC 7519 §4.1.2).
	Subject string `json:"sub,omitempty"`
	// Audience is "aud" (RFC 7519 §4.1.3). When present, Parse rejects the
	// token unless WithAudience names one of its values.
	Audience Audience `json:"aud,omitempty"`
	// ExpiresAt is "exp" (RFC 7519 §4.1.4), always checked when present.
	ExpiresAt *NumericDate `json:"exp,omitempty"`
	// NotBefore is "nbf" (RFC 7519 §4.1.5), always checked when present.
	NotBefore *NumericDate `json:"nbf,omitempty"`
	// IssuedAt is "iat" (RFC 7519 §4.1.6). Informational; not validated.
	IssuedAt *NumericDate `json:"iat,omitempty"`
	// ID is "jti" (RFC 7519 §4.1.7), e.g. a key for RevocationStore.
	ID string `json:"jti,omitempty"`
	// Confirmation is "cnf" (RFC 7800 §3.1), a proof-of-possession key
	// binding. Its presence is not enforced by Parse; checking the proof is
	// the caller's responsibility.
	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"          // identifier is usually a "jti" or session ID
	ReasonKeyCompromised RevocationReason = "key_compromised" // identifier is usually a JWK thumbprint
	ReasonReuseDetected  RevocationReason = "reuse_detected"  // identifier is a TokenFamily.ID
	ReasonAdmin          RevocationReason = "admin_revoked"   // any identifier, revoked by an operator
)

Revocation reasons recorded with RevocationStore.Revoke.

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 an unbounded, single-process RevocationStore. Expiry cleanup is heap-based and amortized rather than a full map sweep on each write.

func NewMemoryRevocationStoreWithCapacity added in v1.0.0

func NewMemoryRevocationStoreWithCapacity(capacity int) (RevocationStore, error)

NewMemoryRevocationStoreWithCapacity returns a bounded, single-process RevocationStore. capacity must be positive. Revoke returns ErrRevocationStoreFull instead of evicting a live revocation when full.

type RotationResult

type RotationResult struct {
	Next          OpaqueToken // the replacement token, when rotation succeeded
	ReuseDetected bool        // a superseded token was presented: revoke the whole family
}

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 // "typ" header (RFC 7515 §4.1.9); zero keeps DefaultType
	ContentType string // "cty" header (RFC 7515 §4.1.10); zero omits it
}

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

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

NewECDSASigner returns an ES256/ES384/ES512 Signer.

func NewEd25519Signer

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

NewEd25519Signer returns a Signer for the RFC 9864 "Ed25519" algorithm.

func NewHMACSigner

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

NewHMACSigner returns an HS256/HS384/HS512 Signer.

func NewRSAPSSSigner

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

NewRSAPSSSigner returns a PS256/PS384/PS512 Signer.

type StandardClaims

type StandardClaims struct {
	Name              string `json:"name,omitempty"`               // full name
	GivenName         string `json:"given_name,omitempty"`         // first name(s)
	FamilyName        string `json:"family_name,omitempty"`        // surname(s)
	MiddleName        string `json:"middle_name,omitempty"`        // middle name(s)
	Nickname          string `json:"nickname,omitempty"`           // casual name
	PreferredUsername string `json:"preferred_username,omitempty"` // mutable; not an identifier (§5.7)
	Profile           string `json:"profile,omitempty"`            // profile page URL
	Picture           string `json:"picture,omitempty"`            // profile picture URL
	Website           string `json:"website,omitempty"`            // web page or blog URL
	Email             string `json:"email,omitempty"`              // mutable; not an identifier (§5.7)
	// EmailVerified is "email_verified"; string forms are accepted (see Bool).
	EmailVerified *Bool  `json:"email_verified,omitempty"`
	Gender        string `json:"gender,omitempty"`       // "female", "male" or other values
	Birthdate     string `json:"birthdate,omitempty"`    // ISO 8601 YYYY-MM-DD, or YYYY / 0000-MM-DD
	ZoneInfo      string `json:"zoneinfo,omitempty"`     // IANA time zone, e.g. "Europe/Paris"
	Locale        string `json:"locale,omitempty"`       // BCP 47 language tag, e.g. "fr-FR"
	PhoneNumber   string `json:"phone_number,omitempty"` // E.164 recommended, e.g. "+1 (425) 555-1212"
	// PhoneNumberVerified is "phone_number_verified"; string forms are
	// accepted (see Bool).
	PhoneNumberVerified *Bool        `json:"phone_number_verified,omitempty"`
	Address             *Address     `json:"address,omitempty"`    // §5.1.1 structured address
	UpdatedAt           *NumericDate `json:"updated_at,omitempty"` // last profile update
	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.

None of these claims is validated by Parse. In particular, "sub" (not "email" or "preferred_username") is the stable identifier (OIDC Core §5.7), and "nonce" must be compared with the value sent in the authentication request by the relying party (OIDC Core §3.1.3.7 step 11).

type TokenFamily

type TokenFamily struct {
	ID string // random, URL-safe; the RevocationStore identifier for the family
}

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 URLPolicy added in v1.0.0

type URLPolicy func(*url.URL) error

URLPolicy validates an absolute HTTPS URL before a request is sent. It is applied to the initial URL, discovery results, and every redirect. Policies used by a KeyFetcher must be safe for concurrent use.

type Verifier

type Verifier = internalalg.Verifier

Verifier checks a JWS signature.

func NewECDSAVerifier

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

NewECDSAVerifier returns an ES256/ES384/ES512 Verifier.

func NewEd25519Verifier

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

NewEd25519Verifier returns a Verifier for the RFC 9864 "Ed25519" algorithm. Parse also verifies deprecated "EdDSA" tokens with an Ed25519 key when EdDSA is allowlisted.

func NewHMACVerifier

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

NewHMACVerifier returns an HS256/HS384/HS512 Verifier.

func NewRSAPKCS1Verifier

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

NewRSAPKCS1Verifier returns an RS256/RS384/RS512 Verifier.

func NewRSAPSSVerifier

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

NewRSAPSSVerifier returns a PS256/PS384/PS512 Verifier.

type VerifierProvider added in v1.0.0

type VerifierProvider interface {
	// LookupVerifier returns a verifier for alg and kid. The bool is false (with
	// a nil error) when no verifier exists. Parse wraps callback errors with
	// ErrVerifierProvider while preserving the original error.
	LookupVerifier(ctx context.Context, alg Algorithm, kid string) (verifier Verifier, found bool, err error)
}

VerifierProvider resolves a caller-defined Verifier by the protected "alg" and "kid" header parameters. Use WithVerifierProvider to make Parse or Middleware use it instead of a KeyProvider. Parse still enforces its algorithm allowlist and checks that the returned Verifier reports the same algorithm and, when the token has a kid, the same key ID.

type VerifierProviderFunc added in v1.0.0

type VerifierProviderFunc func(context.Context, Algorithm, string) (Verifier, bool, error)

VerifierProviderFunc adapts a function to VerifierProvider.

func (VerifierProviderFunc) LookupVerifier added in v1.0.0

func (f VerifierProviderFunc) LookupVerifier(ctx context.Context, alg Algorithm, kid string) (Verifier, bool, error)

LookupVerifier calls f. A nil VerifierProviderFunc is treated as an absent provider when passed through WithVerifierProvider.

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 signs a claim set, encrypts the compact JWS with ECDH-ES+A256KW / A256GCM, then authenticates and decrypts both layers.
Command jwe_roundtrip signs a claim set, encrypts the compact JWS with ECDH-ES+A256KW / A256GCM, then authenticates and decrypts both layers.
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 its core OIDC claims and flow context.
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 its core OIDC claims and flow context.
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.
keyparse
Package keyparse parses private and public key material from explicit, caller-decoded encodings (PKCS#8, PKCS#1, SEC1, PKIX, raw Ed25519, openssh-key-v1).
Package keyparse parses private and public key material from explicit, caller-decoded encodings (PKCS#8, PKCS#1, SEC1, PKIX, raw Ed25519, openssh-key-v1).
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.

Jump to

Keyboard shortcuts

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