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.
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 spec.md records the original design.
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 ¶
- Constants
- Variables
- func BearerToken(r *http.Request) (string, bool)
- func ClaimsFromContext[C any](ctx context.Context, dst *C) error
- func DecryptClaims[C any](ctx context.Context, compact string, dst *C, dec Decrypter, ...) error
- func DiscoverJWKSURI(ctx context.Context, issuer string, client *http.Client) (string, error)
- func EncryptClaims[C any](claims C, enc Encrypter) (string, error)
- func Equal(storedHash, raw string) bool
- func Hash(raw string) string
- func Middleware(keys KeyProvider, opts ...ParseOption) func(http.Handler) http.Handler
- func Parse[C any](ctx context.Context, token string, dst *C, keys KeyProvider, ...) error
- func ParseEd25519PrivateKeyExpanded(raw []byte) (ed25519.PrivateKey, error)
- func ParseEd25519PrivateKeySeed(seed []byte) (ed25519.PrivateKey, error)
- func ParseEd25519PublicKey(raw []byte) (ed25519.PublicKey, error)
- func ParseInsecure[C any](token string, dst *C) error
- func ParseOpenSSHPrivateKey(raw []byte) (crypto.Signer, error)
- func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
- func ParsePKCS8PrivateKey(der []byte) (crypto.Signer, error)
- func ParsePKIXPublicKey(der []byte) (crypto.PublicKey, error)
- func ParseSEC1ECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
- func Sign[C any](claims C, signer Signer, opts ...SignOption) (string, error)
- func Thumbprint(k Key, hash ...crypto.Hash) (string, error)
- func ThumbprintBytes(kty KeyType, raw []byte, hash ...crypto.Hash) (string, error)
- func ValidateAccessTokenClaims(claims AccessTokenClaims) error
- func WriteChallenge(w http.ResponseWriter, realm string, err error)
- func WriteInsufficientScope(w http.ResponseWriter, realm string, scopes ...string)
- type AccessTokenClaims
- type Address
- type Algorithm
- type Audience
- type Bool
- type Confirmation
- type ContentAlgorithm
- type Decrypter
- func NewA256KWDecrypter(kek []byte, kid ...string) (Decrypter, error)
- func NewDirectDecrypter(cek []byte, kid ...string) (Decrypter, error)
- func NewECDHESDecrypter(priv *ecdsa.PrivateKey, kid ...string) (Decrypter, error)
- func NewRSAOAEP256Decrypter(priv *rsa.PrivateKey, kid ...string) (Decrypter, error)
- type Encrypter
- func NewA256KWEncrypter(kek []byte, content ContentAlgorithm, kid ...string) (Encrypter, error)
- func NewDirectEncrypter(cek []byte, content ContentAlgorithm, kid ...string) (Encrypter, error)
- func NewECDHESEncrypter(pub *ecdsa.PublicKey, alg KeyAlgorithm, content ContentAlgorithm, ...) (Encrypter, error)
- func NewRSAOAEP256Encrypter(pub *rsa.PublicKey, content ContentAlgorithm, kid ...string) (Encrypter, error)
- type EntraClaims
- type EntraIDToken
- type FetcherOption
- type GoogleClaims
- type GoogleIDToken
- type Header
- type Key
- type KeyAlgorithm
- type KeyFetcher
- type KeyProvider
- type KeySet
- type KeyType
- type MiddlewareOptions
- type NumericDate
- type OktaClaims
- type OktaIDToken
- type OpaqueToken
- type ParseOption
- func WithAllowedAlgorithms(algs ...Algorithm) ParseOption
- func WithAllowedContentAlgorithms(encs ...ContentAlgorithm) ParseOption
- func WithAllowedKeyAlgorithms(algs ...KeyAlgorithm) ParseOption
- func WithAudience(aud string) ParseOption
- func WithClock(now func() time.Time) ParseOption
- func WithIssuer(iss string) ParseOption
- func WithLeeway(d time.Duration) ParseOption
- func WithRequiredClaims(names ...string) ParseOption
- func WithRequiredType(typ string) ParseOption
- func WithoutAudienceCheck() ParseOption
- type ParseOptions
- type RegisteredClaims
- type RevocationReason
- type RevocationStore
- type RotationResult
- type SignOption
- type SignOptions
- type Signer
- func NewECDSASigner(alg Algorithm, key *ecdsa.PrivateKey, kid ...string) (Signer, error)
- func NewEd25519Signer(key ed25519.PrivateKey, kid ...string) (Signer, error)
- func NewHMACSigner(alg Algorithm, key []byte, kid ...string) (Signer, error)
- func NewRSAPSSSigner(alg Algorithm, key *rsa.PrivateKey, kid ...string) (Signer, error)
- type StandardClaims
- type TokenFamily
- type Verifier
- func NewECDSAVerifier(alg Algorithm, key *ecdsa.PublicKey, kid ...string) (Verifier, error)
- func NewEd25519Verifier(key ed25519.PublicKey, kid ...string) (Verifier, error)
- func NewHMACVerifier(alg Algorithm, key []byte, kid ...string) (Verifier, error)
- func NewRSAPKCS1Verifier(alg Algorithm, key *rsa.PublicKey, kid ...string) (Verifier, error)
- func NewRSAPSSVerifier(alg Algorithm, key *rsa.PublicKey, kid ...string) (Verifier, error)
Examples ¶
Constants ¶
const AccessTokenType = "at+jwt"
AccessTokenType is the mandatory "typ" header value per RFC 9068 §2.1, intended for use with WithRequiredType.
const DefaultType = "JWT"
DefaultType is the "typ" header value Sign stamps on a token unless WithType overrides it: the RFC 7519 §5.1 recommended media type, also satisfying the explicit-typing guidance of RFC 8725 §3.11. For an RFC 9068 access token pass WithType(AccessTokenType).
Variables ¶
var ( // ErrInvalidSignature 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).
var ErrDecryptionFailed = errors.New("jwt: decryption failed")
ErrDecryptionFailed is the single, generic error every decryption failure resolves to: a bad tag, a bad wrapped key, a malformed token or an algorithm mismatch are deliberately indistinguishable (spec §4.7).
var 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.
var ErrNoClaimsInContext = errors.New("jwt: no verified claims in context")
ErrNoClaimsInContext is returned by ClaimsFromContext when the request did not pass through Middleware.
Functions ¶
func BearerToken ¶
BearerToken extracts the credential from an "Authorization: Bearer <token>" header (RFC 6750 §2.1). The scheme 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 ¶
ClaimsFromContext unmarshals the verified payload that Middleware stored on the request context into dst (a pointer to any claims struct; its type is inferred, so no explicit type argument):
var claims MyClaims
if err := jwt.ClaimsFromContext(r.Context(), &claims); err != nil { ... }
func DecryptClaims ¶
func DecryptClaims[C any](ctx context.Context, compact string, dst *C, dec Decrypter, opts ...ParseOption) error
DecryptClaims is the JWE analogue of Parse: decrypt a compact JWE, validate its registered claims per opts, and unmarshal the plaintext into dst (its type is inferred; no explicit type argument).
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".
Example ¶
package main
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"github.com/NyeKo-ItL/jwt"
)
type MyClaims struct {
jwt.RegisteredClaims
Role string `json:"role,omitempty"`
}
func main() {
recipient, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
enc, _ := jwt.NewECDHESEncrypter(&recipient.PublicKey, jwt.ECDHESA256KW, jwt.A256GCM, "enc-1")
compact, _ := jwt.EncryptClaims(MyClaims{Role: "billing"}, enc)
dec, _ := jwt.NewECDHESDecrypter(recipient, "enc-1")
var claims MyClaims
err := jwt.DecryptClaims(context.Background(), compact, &claims, dec,
jwt.WithAllowedKeyAlgorithms(jwt.ECDHESA256KW), // mandatory "alg" allowlist
jwt.WithAllowedContentAlgorithms(jwt.A256GCM), // mandatory "enc" allowlist
)
fmt.Println(err, claims.Role)
}
Output: <nil> billing
func DiscoverJWKSURI ¶
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, 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 and given the same HTTPS-only redirect guard as KeyFetcher.
func EncryptClaims ¶
EncryptClaims is the JWE analogue of Sign: JSON-marshal a claims value (any struct that marshals to an object) and encrypt it as a compact JWE.
func Equal ¶
Equal reports whether raw hashes to storedHash, comparing in constant time (crypto/subtle) to avoid leaking the digest through timing.
func Middleware ¶
func Middleware(keys KeyProvider, opts ...ParseOption) func(http.Handler) http.Handler
Middleware verifies the request's bearer token with keys and opts, then stores the verified payload on the request context for ClaimsFromContext to decode. On 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. WithAllowedAlgorithms is mandatory (RFC 8725 §3.1); Parse returns ErrNoAllowedAlgorithms if no usable algorithm is supplied.
func ParseEd25519PrivateKeyExpanded ¶
func ParseEd25519PrivateKeyExpanded(raw []byte) (ed25519.PrivateKey, error)
ParseEd25519PrivateKeyExpanded parses a raw expanded Ed25519 private key.
func ParseEd25519PrivateKeySeed ¶
func ParseEd25519PrivateKeySeed(seed []byte) (ed25519.PrivateKey, error)
ParseEd25519PrivateKeySeed parses a raw Ed25519 seed.
func ParseEd25519PublicKey ¶
ParseEd25519PublicKey parses a raw Ed25519 public key.
func ParseInsecure ¶
ParseInsecure decodes the payload into dst WITHOUT verifying the signature or checking expiry. Its result MUST NOT drive any authorization decision — read-only inspection only (e.g. looking up a session by an expired token's "jti"). dst's type is inferred; no explicit type argument.
func ParseOpenSSHPrivateKey ¶
ParseOpenSSHPrivateKey parses an unencrypted OpenSSH private key blob.
func ParsePKCS1PrivateKey ¶
func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
ParsePKCS1PrivateKey parses a DER-encoded PKCS#1 RSA private key.
func ParsePKCS8PrivateKey ¶
ParsePKCS8PrivateKey parses a DER-encoded PKCS#8 private key.
func ParsePKIXPublicKey ¶
ParsePKIXPublicKey parses a DER-encoded PKIX public key.
func ParseSEC1ECPrivateKey ¶
func ParseSEC1ECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
ParseSEC1ECPrivateKey parses a DER-encoded SEC1 EC private key.
func Sign ¶
func Sign[C any](claims C, signer Signer, opts ...SignOption) (string, error)
Sign JSON-encodes claims — any value that marshals to a JSON object, most often a struct embedding RegisteredClaims — and produces a compact JWS (RFC 7515 §7.1). The generated header carries "alg", "typ" (DefaultType unless WithType is given), an optional "cty" from WithContentType, and — when the signer has one — "kid".
func Thumbprint ¶
Thumbprint computes the RFC 7638 JWK thumbprint of an already-parsed Key. hash is optional and defaults to SHA-256 (the hash behind the "jkt" confirmation value). The canonical form contains only the type-specific required members, with keys in lexicographic order and no whitespace (RFC 7638 §3).
func ThumbprintBytes ¶
ThumbprintBytes computes an RFC 7638-shaped thumbprint directly from raw key material the caller already holds, without a parsed Key. It supports the unambiguous single-blob key types: "oct" (raw is the secret) and "OKP" (raw is the 32-byte Ed25519 public key). RSA and EC keys have no single canonical byte form — use Thumbprint with a parsed Key for those. hash is optional and defaults to SHA-256.
func ValidateAccessTokenClaims ¶
func ValidateAccessTokenClaims(claims AccessTokenClaims) error
ValidateAccessTokenClaims checks the RFC 9068 §2.2 required-claims profile beyond what Parse already validates: iss, exp, aud, sub, client_id and iat MUST be present. (jti only SHOULD be present, so it is not enforced.)
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 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) MarshalJSON ¶
MarshalJSON emits a single-element audience as a bare string and any other length as a JSON array (RFC 7519 §4.1.3).
func (*Audience) UnmarshalJSON ¶
UnmarshalJSON accepts a bare string, a JSON array of strings, or null.
type 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
UnmarshalJSON accepts true, false, "true" or "false".
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 ¶
NewA256KWDecrypter unwraps the CEK of a JWE "alg":"A256KW" token.
func NewDirectDecrypter ¶
NewDirectDecrypter decrypts JWE "alg":"dir" tokens with a pre-shared CEK.
func NewECDHESDecrypter ¶
func NewECDHESDecrypter(priv *ecdsa.PrivateKey, kid ...string) (Decrypter, error)
NewECDHESDecrypter decrypts JWE tokens whose "alg" is ECDH-ES or ECDH-ES+A256KW, using an EC private key.
func NewRSAOAEP256Decrypter ¶
func NewRSAOAEP256Decrypter(priv *rsa.PrivateKey, kid ...string) (Decrypter, error)
NewRSAOAEP256Decrypter unwraps the CEK of a JWE "alg":"RSA-OAEP-256" token.
type Encrypter ¶
type Encrypter interface {
// KeyAlgorithm reports the "alg" (key-management) value written to the
// protected header.
KeyAlgorithm() KeyAlgorithm
// ContentAlgorithm reports the "enc" (content-encryption) value.
ContentAlgorithm() ContentAlgorithm
// KeyID is the "kid" written to the header; empty if none.
KeyID() string
// Encrypt returns the compact JWE for plaintext.
Encrypt(plaintext []byte) (compact string, err error)
}
Encrypter produces a compact JWE (RFC 7516 §7.1).
func NewA256KWEncrypter ¶
func NewA256KWEncrypter(kek []byte, content ContentAlgorithm, kid ...string) (Encrypter, error)
NewA256KWEncrypter wraps a fresh CEK under a 256-bit key-encryption key (JWE "alg":"A256KW").
func NewDirectEncrypter ¶
func NewDirectEncrypter(cek []byte, content ContentAlgorithm, kid ...string) (Encrypter, error)
NewDirectEncrypter uses a pre-shared content-encryption key directly (JWE "alg":"dir"). The key length must match content (16/24/32 bytes for A128/A192/A256GCM).
func NewECDHESEncrypter ¶
func NewECDHESEncrypter(pub *ecdsa.PublicKey, alg KeyAlgorithm, content ContentAlgorithm, kid ...string) (Encrypter, error)
NewECDHESEncrypter derives (ECDH-ES) or derives-and-wraps (ECDH-ES+A256KW) the CEK against an EC public key. alg must be ECDHES or ECDHESA256KW.
func NewRSAOAEP256Encrypter ¶
func NewRSAOAEP256Encrypter(pub *rsa.PublicKey, content ContentAlgorithm, kid ...string) (Encrypter, error)
NewRSAOAEP256Encrypter wraps a fresh CEK with RSA-OAEP using SHA-256 (JWE "alg":"RSA-OAEP-256"). Keys below 2048 bits are rejected (spec §4.6).
type EntraClaims ¶
type EntraClaims struct {
TenantID string `json:"tid,omitempty"` // 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 WithMaxResponseBytes ¶
func WithMaxResponseBytes(n int64) FetcherOption
WithMaxResponseBytes caps the JWKS response body size (default 1 MiB).
func WithMinRefreshInterval ¶
func WithMinRefreshInterval(d time.Duration) FetcherOption
WithMinRefreshInterval sets the shortest interval between network attempts triggered by Lookup (default 1 minute). It also acts as the retry backoff after a failed attempt. Refresh bypasses it.
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 ¶
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"`
}
Header is the JOSE header (RFC 7515 §4.1), modeling every registered parameter. jku/x5u/jwk/x5c are parsed and readable but are NEVER automatically dereferenced or trusted to select a verification key (spec §4.8, RFC 8725 §3.9-3.10).
type Key ¶
type Key struct {
// Kty 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 ¶
FromECDSAPublicKey builds a "sig" JWK from an ECDSA public key. If the point is invalid the coordinate fields are left empty and the failure surfaces later, at PublicKey/Verifier time.
func FromEd25519PublicKey ¶
FromEd25519PublicKey builds a "sig" JWK from an Ed25519 public key.
func FromHMACSecret ¶
FromHMACSecret builds a symmetric (kty "oct") JWK. Such a key cannot be marshaled into a servable JWKS document (see MarshalJSON).
func FromRSAPublicKey ¶
FromRSAPublicKey builds a "sig" JWK from an RSA public key.
func (Key) MarshalJSON ¶
MarshalJSON renders the key as an RFC 7517 JWK object. It returns ErrOctNotServable for symmetric keys so a symmetric secret can never be published in a discoverable keyset by accident.
func (*Key) UnmarshalJSON ¶
UnmarshalJSON parses an RFC 7517 JWK object. 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).
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.
- A Cache-Control max-age hint is honored but capped (WithMaxCacheDuration), so a revoked key cannot stay pinned for long.
- When a refresh fails, keys from the last good document keep resolving.
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.
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
}
}
Output:
func (*KeyFetcher) Lookup ¶
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.
type KeyProvider ¶
type KeyProvider interface {
// Lookup returns the key for kid. The bool is false (with a nil error)
// when no such key exists; a non-nil error signals a backing-store
// failure and aborts Parse.
Lookup(ctx context.Context, kid string) (key Key, found bool, err error)
}
KeyProvider resolves a Key by "kid" (which may be empty, meaning "the only key"). Parse uses it to obtain the verification key for a token. A single fixed key and a full JWKS-backed store satisfy the same interface.
func MapKeyProvider ¶
func MapKeyProvider(byKID map[string]Key) KeyProvider
MapKeyProvider adapts a fixed set of Keys, keyed by kid. As with any KeyProvider, an empty requested kid resolves to the sole key when the map holds exactly one.
func StaticKeyProvider ¶
func StaticKeyProvider(k Key) KeyProvider
StaticKeyProvider adapts a single fixed Key — the common case where an application has exactly one signing key. A non-empty requested kid that does not match the key's own non-empty kid resolves to "not found".
type KeySet ¶
type KeySet struct {
// contains filtered or unexported fields
}
KeySet is a mutable, concurrency-safe KeyProvider (RFC 7517 §5's JWK Set) — the library's built-in in-memory implementation. Insertion order is preserved for serving as a JWKS document.
func ParseKeySet ¶
ParseKeySet parses a JWKS document ({"keys":[ ... ]}) into a ready-to-use KeySet. Unlike many hand-rolled parsers it does not silently drop keys it cannot fully interpret: a malformed member is an error.
func (*KeySet) Lookup ¶
Lookup resolves a key by kid. An empty kid matches a sole key (or a sole key that itself has no kid); it is ambiguous when the set holds several keys, and Lookup then reports not-found rather than guessing.
func (*KeySet) MarshalJSON ¶
MarshalJSON renders the set as an RFC 7517 §5 JWK Set document. It fails if any contained key refuses to marshal (e.g. a symmetric "oct" key, which must never be published — see Key.MarshalJSON).
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
type KeyType ¶
type KeyType string
KeyType is the RFC 7517 §4.1 "kty" value.
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 NumericDate ¶
NumericDate is RFC 7519 §2's NumericDate (seconds since the Unix epoch), exposed as a time.Time.
func NewNumericDate ¶
func NewNumericDate(t time.Time) *NumericDate
NewNumericDate wraps t as a *NumericDate.
func (NumericDate) MarshalJSON ¶
func (n NumericDate) MarshalJSON() ([]byte, error)
MarshalJSON emits the value as integer seconds since the Unix epoch.
func (*NumericDate) UnmarshalJSON ¶
func (n *NumericDate) UnmarshalJSON(b []byte) error
UnmarshalJSON accepts 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 ¶
func DeriveOpaqueToken(raw string) OpaqueToken
DeriveOpaqueToken deterministically builds a token from a string the caller already holds, instead of drawing fresh randomness. Raw is the input verbatim; Hash is its SHA-256 hex digest.
func NewOpaqueToken ¶
func NewOpaqueToken() (OpaqueToken, error)
NewOpaqueToken generates a fresh token: 32 bytes of crypto/rand, base64url-encoded, paired with its SHA-256 hex digest.
type ParseOption ¶
type ParseOption interface {
// contains filtered or unexported methods
}
ParseOption configures Parse, DecryptClaims and Middleware. Both the functional options below (WithIssuer, WithAudience, ...) and a ParseOptions struct satisfy it, so a reusable declarative config and per-call overrides combine in a single call — options apply left to right, so a later one wins:
base := jwt.ParseOptions{
AllowedAlgorithms: []jwt.Algorithm{jwt.RS256, jwt.ES256},
Issuer: "https://accounts.google.com",
}
err := jwt.Parse(ctx, tok, &claims, keys, base, jwt.WithAudience(clientID))
func WithAllowedAlgorithms ¶
func WithAllowedAlgorithms(algs ...Algorithm) ParseOption
WithAllowedAlgorithms sets the mandatory algorithm allowlist (RFC 8725 §3.1). "none" and the empty string are never accepted, even if listed.
func 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 in the payload.
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 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
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)
}
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 a ThumbprintBytes-derived kid 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 the library's built-in RevocationStore: an in-process, mutex-guarded map with lazy expiry. Documented as single-process-only.
type RotationResult ¶
type RotationResult struct {
Next OpaqueToken // 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.
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 ¶
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 ¶
NewHMACSigner returns an HS256/HS384/HS512 Signer.
func NewRSAPSSSigner ¶
NewRSAPSSSigner returns a PS256/PS384/PS512 Signer.
type StandardClaims ¶
type StandardClaims struct {
Name string `json:"name,omitempty"` // 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 Verifier ¶
type Verifier = internalalg.Verifier
Verifier checks a JWS signature.
func NewECDSAVerifier ¶
NewECDSAVerifier returns an ES256/ES384/ES512 Verifier.
func NewEd25519Verifier ¶
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 ¶
NewHMACVerifier returns an HS256/HS384/HS512 Verifier.
func NewRSAPKCS1Verifier ¶
NewRSAPKCS1Verifier returns an RS256/RS384/RS512 Verifier.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic_hmac
command
Command basic_hmac signs a JWT with HS256 and verifies it back.
|
Command basic_hmac signs a JWT with HS256 and verifies it back. |
|
http_middleware
command
Command http_middleware protects an HTTP handler with jwt.Middleware and exercises it with an in-process request.
|
Command http_middleware protects an HTTP handler with jwt.Middleware and exercises it with an in-process request. |
|
jwe_roundtrip
command
Command jwe_roundtrip encrypts a claim set as a compact JWE with ECDH-ES+A256KW / A256GCM and decrypts it back.
|
Command jwe_roundtrip encrypts a claim set as a compact JWE with ECDH-ES+A256KW / A256GCM and decrypts it back. |
|
refresh_rotation
command
Command refresh_rotation demonstrates opaque refresh-token rotation with reuse detection: the library supplies the shapes (OpaqueToken, TokenFamily, RotationResult) and a RevocationStore; the rotation policy and storage are the application's.
|
Command refresh_rotation demonstrates opaque refresh-token rotation with reuse detection: the library supplies the shapes (OpaqueToken, TokenFamily, RotationResult) and a RevocationStore; the rotation policy and storage are the application's. |
|
verify_idtoken
command
Command verify_idtoken shows the JWKS + provider-claims path: an OpenID provider signs an ID token with ES256 and publishes its public key in a JWK Set; a relying party verifies it as a jwt.GoogleIDToken.
|
Command verify_idtoken shows the JWKS + provider-claims path: an OpenID provider signs an ID token with ES256 and publishes its public key in a JWK Set; a relying party verifies it as a jwt.GoogleIDToken. |
|
internal
|
|
|
alg
Package alg contains the built-in JWS algorithms.
|
Package alg contains the built-in JWS algorithms. |
|
b64
Package b64 provides the base64url (RFC 4648 §5, no padding) encoding used throughout JOSE compact serialization.
|
Package b64 provides the base64url (RFC 4648 §5, no padding) encoding used throughout JOSE compact serialization. |
|
bytes
Package bytes contains byte-slice helpers shared by internal implementations.
|
Package bytes contains byte-slice helpers shared by internal implementations. |
|
errors
Package errors contains sentinel values shared by internal implementations and the public jwt package.
|
Package errors contains sentinel values shared by internal implementations and the public jwt package. |
|
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. |