Skip to content
MichaelFraser99Public

About

A Go implementation of the JOSE suite of specifications - JWE, JWK, JWS, and JWT

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Go Jose

A Go implementation of the JOSE suite of specifications — JWS (RFC 7515), JWE (RFC 7516, Compact Serialization only), JWA (RFC 7518), JWK (RFC 7517), and JWT (RFC 7519).

Requirements

  • Go 1.27 or higher

Import paths

There is no root package. Import the subpackage you need:

import (
	"github.com/MichaelFraser99/go-jose/jwa"        // algorithm identifiers
	"github.com/MichaelFraser99/go-jose/jwe"        // encryption and decryption
	"github.com/MichaelFraser99/go-jose/jwk"        // jwk conversion
	"github.com/MichaelFraser99/go-jose/jws"        // signers and validators
	"github.com/MichaelFraser99/go-jose/jwt"        // jwt signing and validation
	"github.com/MichaelFraser99/go-jose/joseerror"  // error sentinels
	"github.com/MichaelFraser99/go-jose/model"      // shared types and options
)

Installation

go get github.com/MichaelFraser99/go-jose

Algorithms Supported

This section lists the signature algorithms. For the JWE algorithms, see Encrypting and decrypting.

Currently, the module supports the following asymmetric algorithms:

  • ES256
  • ES384
  • ES512
  • RS256
  • RS384
  • RS512
  • PS256
  • PS384
  • PS512
  • Ed25519
  • ML-DSA-44
  • ML-DSA-65
  • ML-DSA-87

ML-DSA-44, ML-DSA-65 and ML-DSA-87 are the FIPS 204 post-quantum signature parameter sets, as RFC 9964 section 5 registers them for JOSE. They use the standard library's crypto/mldsa. That package is unavailable under the FIPS 140-3 Go Cryptographic Module v1.0.0, and there building an ML-DSA signer or validator returns an error. HashML-DSA is not supported: RFC 9964 section 7.2 registers no JOSE algorithm for it.

Ed25519 is EdDSA with the Ed25519 parameters of RFC 8032 section 5.1, as RFC 9864 section 4.1.1 registers it. Ed448 is not supported.

EdDSA is accepted for verification only, and only with an Ed25519 key. RFC 9864 section 4.1.2 deprecates EdDSA in favour of Ed25519. Section 4.4 tells new producers to prefer the replacement, but it does not tell verifiers to refuse the old identifier. So:

  • A token whose alg is EdDSA verifies under an Ed25519 key, as RFC 8037 defines it.
  • GetSigner, GetSignerFromPrivateKey, GetSignerFromJwk and jwt.New refuse EdDSA with ErrUnsupportedAlgorithm. Sign with Ed25519.
  • EdDSA and Ed25519 are separate values of jwa.Algorithm. To refuse EdDSA tokens, set AllowedSigningAlgorithms to jwa.Ed25519 without jwa.EdDSA. While your issuers move from EdDSA to Ed25519, list both: a list that names only one refuses a token that names the other.

Also supported are the following HMAC with SHA2 symmetric algorithms:

  • HS256
  • HS384
  • HS512

GetSigner requires a secret key as *[]byte, passed in model.Opts.SecretKey. With no secret it returns an error: the random-secret path inside each package is not reachable through the public API. GetSignerFromJwk takes the secret as an oct jwk instead.

This is a breaking change in v0.11.0: a secret must be at least as long as the hash output. That is 32 bytes for HS256, 48 for HS384, and 64 for HS512. RFC 7518 section 3.2 makes the rule a MUST, because a shorter secret caps the cost of a forgery at the entropy of the secret instead of the strength of the MAC. GetSigner refuses a shorter secret with ErrInvalidPrivateKey. Earlier versions accepted a secret of any length, a one-byte secret included, and a nil secret gave a usable validator.

Give your secret at least that many bytes.

A validator for these algorithms can only be built from a signer. GetValidator accepts what Signer.Public returns and nothing else: a raw []byte is refused, and GetValidatorFromJwk refuses an oct key outright. So to verify an HS token with a secret you were given, construct a signer with that secret first:

signer, err := jws.GetSigner(jwa.HS256, &model.Opts{SecretKey: &secret})
validator, err := jws.GetValidator(signer.Alg(), signer.Public())

GetValidator applies the same length rule and refuses with ErrInvalidPublicKey, but a secret that reached it through a signer has already passed the rule, so the refusal is not one you can trigger from outside this library.

Public returns a SecretKey, a type defined in an internal package. It holds the secret and the algorithm that it was made for. A consumer cannot name the type, so reach its Equal method through an interface:

if comparer, ok := validator.Public().(interface{ Equal(crypto.PublicKey) bool }); ok {
	if comparer.Equal(other.Public()) {
		// the two validators hold the same secret
	}
}

SecretKey.Equal reports whether two keys were made for the same algorithm and hold the same bytes. A []byte is never equal to it, even when it holds the same bytes. It compares the bytes in constant time, because an early-exit comparison tells a caller who submits guesses how many leading bytes were correct.

Note what Equal does not answer. HMAC pads a key shorter than its block size and hashes a longer one, so two different byte strings can key identically. Equal compares the bytes as given, and reports such a pair as unequal.

Algorithms are identified by the jwa package:

type jwa.Algorithm int

Its zero value is jwa.Unknown, so a variable you forgot to set names no algorithm rather than ES256.

func (a Algorithm) String() string

String returns the name of the algorithm, such as "RS256". It returns the empty string for Unknown.

func GetAlgorithm(alg string) Algorithm

GetAlgorithm returns the algorithm a name identifies, and Unknown if no algorithm has that name. The comparison is case sensitive, because RFC 7515 section 4.1.1 makes the alg header value case sensitive.

Signers

To create a Signer, use jws.GetSigner. It takes an algorithm and an optional model.Opts, and returns a model.Signer with a generated key pair. Opts.BitSize sets the modulus size for the RSA algorithms. Opts.SecretKey carries the secret for the HMAC algorithms, where it is required rather than optional. Of a key that GetSigner generates, the signer gives only the public half, through Public. So a generated key lasts only as long as the signer. An HMAC signer is different: you pass the secret, and its Public returns that secret. To keep a key, generate it yourself, save it with jwk.PrivateJwk, and build the signer with GetSignerFromPrivateKey or GetSignerFromJwk. The example below generates a signer for ES256:

signer, err := jws.GetSigner(jwa.ES256, nil)

jws.GetSignerFromPrivateKey builds a signer from a key you already hold. It takes an algorithm and a crypto.PrivateKey. It refuses the HMAC algorithms, which take their secret through model.Opts instead. The example below builds a signer for ES256:

signer, err := jws.GetSignerFromPrivateKey(jwa.ES256, privateKey)

jws.GetSignerFromJwk builds a signer from a private jwk, decoded as a map[string]any. It reads the key by its kty, as jwk.PrivateFromJwk does. For HS256, HS384 and HS512, the jwk must be an oct jwk, and its k is the secret. RFC 7518 section 6.4 defines the oct jwk. The secret must be as long as GetSigner requires. For every other algorithm, the jwk must hold a private key that GetSignerFromPrivateKey accepts, and an oct jwk is refused. A jwk with no private part, such as an EC jwk without d, is refused. A jwk that carries an alg member is refused unless that member is the algorithm you asked for. RFC 8725 section 3.1 requires each key to be used with exactly one algorithm. A jwk whose alg member is "EdDSA" is accepted for jwa.Ed25519, because with an Ed25519 key both names mean the same algorithm. jwa.EdDSA itself is refused as the algorithm argument. A jwk whose kid or alg is not a string is refused (RFC 7517 sections 4.4 and 4.5). A jwk whose use is present and is not "sig" is refused. So is a jwk whose key_ops is present and does not include "sign", or lists a value twice, or names an operation that is not consistent with its use. RFC 7517 sections 4.2 and 4.3 set these rules. key_ops can be a []any, as encoding/json decodes it, or a []string. A fault in the algorithm argument is refused with ErrUnsupportedAlgorithm. A fault in the jwk is refused with ErrInvalidPrivateKey. To sign with a key whose use or key_ops is refused, read it with jwk.PrivateFromJwk. Then give it to GetSignerFromPrivateKey, or give a secret to GetSigner. Neither has a key-use rule. The last argument is a *model.JoseOptions, and it can be nil. Of its fields, only StrictKeyOperations applies here. The example below builds a signer for ES256 and one for HS256:

signer, err := jws.GetSignerFromJwk(jwa.ES256, privateKeyMap, nil)

hmacSigner, err := jws.GetSignerFromJwk(jwa.HS256, map[string]any{"kty": "oct", "k": encodedSecret}, nil)

Which keys a signer or validator accepts

GetSigner, GetSignerFromPrivateKey, GetSignerFromJwk, GetValidator and GetValidatorFromJwk refuse a key the algorithm cannot use, with ErrInvalidPrivateKey or ErrInvalidPublicKey:

  • RS and PS: the modulus must be 2048 to 8192 bits. RFC 7518 sections 3.3 and 3.5 make 2048 bits a MUST. The 8192-bit ceiling is this library's: the cost of an RSA verification grows with the square of the modulus, and a token can name its own key, so an unbounded modulus lets a peer hold a core for seconds. 8192 bits is also the default cap crypto/tls puts on a peer's RSA key. Opts.BitSize takes the same range.
  • RS and PS exponent: the public exponent must be odd and between 3 and 2^31 - 1. RFC 8017 section 3.1 puts e between 3 and n - 1 with GCD(e, λ(n)) = 1, and λ(n) is even, so e is odd. With e = 1 a signature is its own encoded message, so anyone could forge one. crypto/rsa refuses such a key when it verifies, and this library refuses it earlier, when the signer or validator is built.
  • ES: the key must lie on the algorithm's own curve: P-256 for ES256, P-384 for ES384 and P-521 for ES512. RFC 7518 section 3.1 defines each algorithm by its curve. A private key's d must be the private key of its point.
  • ML-DSA: the key must be an *mldsa.PrivateKey or *mldsa.PublicKey of the algorithm's own parameter set, so an ML-DSA-65 key is refused for ML-DSA-44. A zero-value key, such as &mldsa.PrivateKey{}, is refused. A zero-value private key reports the all-zero seed, so it is not rebuilt from it: that is the published example key of RFC 9964 Appendix A.
  • Ed25519: the key must be an ed25519.PrivateKey or ed25519.PublicKey, or a pointer to one. A private key must be 64 bytes, and its public half must be the public key of its seed. A public key must be 32 bytes. RFC 8032 section 5.1.5 sets these sizes. A public key must encode a y below 2^255 - 19, because RFC 8032 section 5.1.3 says that any other y fails to decode. A public key whose x is 0 must have its sign bit clear. A public key of small order is refused too. NIST SP 800-186 appendix D.1.3.2 refuses such a key in full public key validation, and under the neutral element one fixed signature verifies every message. This check does not refuse a key of mixed order.
  • Every family: a nil key, or one missing the modulus, exponent, curve, coordinates or private scalar, is refused when the signer or validator is built rather than panicking later. An RSA private key needs only D, as RFC 7518 section 6.3.2 makes the primes optional. Without primes, the signer recovers the two primes from N, E and D, as NIST SP 800-56B Rev. 2 Appendix C.1 describes, and signs with them. If D does not undo E, or the modulus is not the product of two primes, the key is refused. With primes, the key must pass rsa.PrivateKey.Validate. The signer and validator keep their own copy of the key, so a later change to your key does not affect them. Public returns a new copy each time, so a change to that copy does not affect them either.

Signing Contract

The Sign method follows JOSE conventions per RFC 7518 rather than Go's crypto.Signer contract. It supports two modes:

  • JOSE mode (opts == nil or opts.HashFunc() == 0): pass the raw JWS Signing Input — the signer hashes it internally using the algorithm's designated hash. This is the expected usage for JWS operations.
  • Pre-hashed mode (opts.HashFunc() != 0): pass an already-hashed digest — the signer skips internal hashing. This supports interoperability with callers following Go's crypto.Signer convention. ES, RS and PS implement this mode. They refuse a Hash that is not the algorithm's own, and a digest whose length is not that hash's output size, with ErrSigningError.

The HMAC algorithms have no pre-hashed mode, and refuse one. HMAC is itself a keyed hash, so there is no internal hashing step for a caller to skip. HS256, HS384 and HS512 refuse a non-zero opts.HashFunc() with ErrSigningError. Pass the signing input whole and leave opts nil.

The HMAC refusal is a breaking change in v0.11.0, and it breaks two kinds of caller differently. One passed a pre-hashed digest with a non-zero Hash, as the old documentation described: they were already producing a MAC over the digest rather than over the signing input, which no validator accepts, with no error to say so. They now get an error at the call that causes it. The other is generic over crypto.Signer and passes a non-zero Hash alongside the raw signing input — that worked, because opts was ignored, and it no longer does. Such a caller passes nil for an HS algorithm, or a zero Hash.

Ed25519 has no pre-hashed mode either, and refuses one. Ed25519 hashes the whole signing input as part of the signature. For a non-zero hash, crypto/ed25519 signs with Ed25519ph, which is a different algorithm. So the Ed25519 signer refuses a non-zero opts.HashFunc() with ErrSigningError. An *ed25519.Options with a non-empty Context is refused the same way: RFC 8032 section 5.1 gives Ed25519 no context, and a context asks crypto/ed25519 for Ed25519ctx.

ML-DSA has no pre-hashed mode either, and refuses one. RFC 9964 section 5 signs the whole input. ML-DSA signers refuse a non-zero opts.HashFunc() with ErrSigningError, including crypto.MLDSAMu, which asks crypto/mldsa to sign an externally computed mu. RFC 9964 section 5 also requires an empty context, so an *mldsa.Options with a non-empty Context is refused the same way. An ML-DSA signature is hedged, the default variant of FIPS 204 section 3.4, so two signatures of one input differ.

Every signer accepts a nil rand. PS signatures are randomised, so the PS signers then read from crypto/rand.Reader.

A SignerOpts implementation is provided:

type SignerOpts struct {
	Hash crypto.Hash
}

ValidateSignature always expects the raw signing input (not pre-hashed) and hashes internally.

Validators

In addition to the packaged signers, a validator type is also included for each algorithm. This can be constructed in one of two ways:

The GetValidator method takes in a crypto.PublicKey implementation and returns a validator instance. The below example shows how to generate a validator for ES256:

// Construct a validator from a public key
validator, err := jws.GetValidator(jwa.ES256, publicKey)

// Construct a validator from a signer instance
signer, err := jws.GetSigner(jwa.ES256, nil)
signerValidator, err := jws.GetValidator(signer.Alg(), signer.Public())

jws.GetValidatorFromJwk builds a validator from a jwk, decoded as a map[string]any rather than raw bytes. It reads the key by its kty, as jwk.PublicFromJwk does, so a jwk without a kty, or whose kty does not match its algorithm, is refused. RFC 8725 section 3.1 requires each key to be used with exactly one algorithm, so a jwk that carries an alg member is refused with ErrInvalidPublicKey unless that member is the algorithm you asked for. EdDSA and Ed25519 count as the same algorithm here, because this library supports only the Ed25519 curve for EdDSA. A jwk whose kid or alg is not a string is refused with ErrInvalidPublicKey (RFC 7517 sections 4.4 and 4.5). A jwk whose use is present and is not "sig" is refused with ErrInvalidPublicKey. So is a jwk whose key_ops is present and does not include "verify", or lists a value twice, or names an operation that is not consistent with its use. RFC 7517 section 4.3 says the last two MUST NOT happen. key_ops can be a []any or a []string. RFC 7517 sections 4.2 and 4.3 let a publisher mark a key as not for verifying signatures. IgnoreKeyUse does not apply to GetValidatorFromJwk. To verify with such a key, read it with jwk.PublicFromJwk and give the key to GetValidator, which has no key-use rule. The last argument is a *model.JoseOptions, and it can be nil. Of its fields, only StrictKeyOperations applies here. GetValidatorFromJwk refuses the HMAC algorithms with ErrUnsupportedAlgorithm, because an oct key cannot be reached this way. The example below builds a validator for ES256:

// Construct a validator from a jwk public key
validator, err := jws.GetValidatorFromJwk(jwa.ES256, publicKeyMap, nil)

ValidateSignature takes the raw signing input and the signature, and reports whether the signature verifies. Do not hash the input first: the validator hashes it internally with the algorithm's own hash. A signature that does not verify returns false with a nil error. The error is non-nil only when the signature could not be checked at all. This holds for every family: an RS or PS signature that crypto/rsa rejects returns false with a nil error, and so does an ES signature of the wrong length, because RFC 7518 section 3.4 says that "the validation has failed".

// Validate a signature
validator, err := jws.GetValidator(jwa.ES256, publicKey)

valid, err := validator.ValidateSignature(signingInput, signature)

Finally, validators expose their PublicKey with the Public() method

validator, err := jws.GetValidator(jwa.ES256, publicKey)
pk := validator.Public()

Binding a key to one algorithm

RFC 8725 section 3.1 requires each key to be used with exactly one algorithm. A bare crypto.PublicKey carries no algorithm, so this library cannot check that for you when the key comes from GetValidator or from a model.Retriever. One RSA key builds a validator for each of RS256, RS384, RS512, PS256, PS384 and PS512, and a retriever's RSA key verifies a token that names any of them. Binding the key is your job:

  • With GetValidator, pass the algorithm the key was issued for, not the alg a token names.
  • With a retriever, set JoseOptions.AllowedSigningAlgorithms to the algorithm your keys are for.

A jwk can carry its own alg. GetSignerFromJwk, GetValidatorFromJwk, a member of JoseOptions.KeySet and a token's jwk header all enforce it. So when you hold your keys as a JWK Set, pass it as KeySet rather than through a retriever.

A secret key is bound for you. What Public() returns for an HMAC signer or validator, or for an AES key wrap or AES GCM key wrap encrypter or decrypter, is a SecretKey bound to that algorithm. GetValidator, jwe.GetEncrypter and jwe.GetDecrypter refuse a SecretKey made for another algorithm. GetValidator and jwe.GetEncrypter refuse it with ErrInvalidPublicKey, and jwe.GetDecrypter with ErrInvalidPrivateKey. A retriever key of this kind is skipped, so if no other key verifies the token, the error is ErrInvalidSignature. So the Public() of an HS256 signer cannot build an HS512 validator or an A256KW encrypter. A []byte carries no algorithm, so jwe.GetEncrypter and jwe.GetDecrypter accept the same bytes for any algorithm whose key size they fit. Use each secret for one algorithm only.

Verifying a JWS

jws.Verify checks a JWS Compact Serialization and returns its protected header and its payload as the signed octets. RFC 7515 section 2 lets a payload be "an arbitrary sequence of octets", so Verify does not parse it. Text, binary data and an empty payload all verify:

head, payload, err := jws.Verify(ctx, token, retriever, opts)

jws.VerifyCompactSerialization does the same checks and also parses the payload as a JSON object, which is what a JWT carries. It refuses any other payload, including null. jwt.Validate is built on it. It checks no claim, so it ignores RequiredClaims, ExpectedIssuer and ExpectedAudience. Use jwt.Validate for those.

Both apply the same rules to the token:

  • Each segment must be base64url exactly as RFC 7515 section 2 defines it. A segment holding a line break, whitespace, = padding or any other character outside A-Z a-z 0-9 - _ is refused, as section 5.2 steps 2, 6 and 7 require. A final character whose unused low bits are not zero is refused too, as RFC 4648 section 3.5 permits. So each segment has exactly one accepted encoding.
  • The protected header must be a UTF-8 JSON object, as section 5.2 step 3 and RFC 8725 section 3.7 require. VerifyCompactSerialization holds the payload to the same rule.
  • A JSON string in the protected header must not hold an unpaired UTF-16 surrogate escape, such as "\ud800". RFC 8259 section 8.2 calls the behaviour of a receiver of such a string unpredictable. Go would turn it into U+FFFD, so different signed bytes would give the same value. VerifyCompactSerialization holds the payload to the same rule.
  • An alg this library has no validator for is refused with ErrUnsupportedAlgorithm before any key is sought, so no jku or x5u is fetched for it.
  • A b64 header of false is refused with ErrMissingCriticalClaim, even when you name b64 in UnderstoodCriticalHeaders. RFC 7797 section 3 says such a payload is not base64url-encoded, and this library always decodes it. A b64 header that is not a JSON boolean is refused with ErrMalformedClaim, as RFC 7797 section 3 requires.
  • A typ or cty header that is not a string is refused with ErrMalformedClaim, whether or not you set AcceptedTypes. RFC 7515 sections 4.1.9 and 4.1.10 define each as a media type, which is a string.

One message can still have more than one valid token. ECDSA signatures are malleable: for an ES256, ES384 or ES512 token, anyone can replace the signature's S with n - S and get a second token that verifies. This needs no key. So do not key a replay or deduplication cache on the raw token string. Key it on a claim such as jti instead.

VerifyCompactSerialization refuses a JWT signed inside another JWS with ErrUnsupportedAlgorithm, before any key is sought. RFC 7519 allows this nesting, and this library does not implement it. A JWT signed and then encrypted is supported: see Encrypted JWTs. RFC 7519 section 5.2 marks a nested JWT with a cty of JWT, compared as RFC 7515 section 4.1.10 describes: ignoring the case of ASCII letters, with application/ treated as prepended. Media-type parameters are ignored, so application/jwt; charset=utf-8 is a nested JWT too. Verify does not look at cty, because section 4.1.10 says JWS implementations ignore it. To unwrap a nested JWT yourself, call Verify and verify the payload it returns.

Both try the keys from every source until one verifies the signature, up to JoseOptions.MaxKeysTried, which is 100 when unset. RFC 7517 section 4.5 does not require a kid to be unique, so a key set a peer publishes can hold thousands of keys under one kid, and each costs a signature verification. A token that would need more keys than the limit is refused with ErrTooManyKeys, not ErrInvalidSignature, so you can tell an oversized key set from a forgery. Only a key that a validator can be built from for the token's alg counts. The limit covers the keys your retriever returns and the members of your KeySet that are selected for the token too. When the limit is reached, no further jku or x5u is fetched.

Verifying with your own key set

A model.Retriever returns bare keys, so every key it returns is tried, whatever the token's kid and alg. When you hold your keys as a JWK Set (RFC 7517 section 5), set JoseOptions.KeySet instead. An issuer's jwks_uri document that you fetched yourself is an example:

var keySet model.Jwks
if err := json.Unmarshal(jwksDocument, &keySet); err != nil {
    return err
}
head, payload, err := jws.Verify(ctx, token, nil, &model.JoseOptions{KeySet: &keySet})

The set holds your own keys, so it needs no other option. It does not turn on UseTokenProvidedKeys, and a jwk or jku the token names is still ignored. A member is used for a token only when it passes the rules in Which keys are selected. So the token's kid selects among your keys. A member published for another alg, of a key type the alg cannot use, or marked for another use is skipped. IgnoreKeyUse and StrictKeyOperations apply as they do to a jku set. A member this library cannot read as a public key is skipped, as RFC 7517 section 5 recommends. A member that holds a private key is read for its public half, because the set is your own and RFC 7517 section 5 lets a set hold private keys.

An oct member is never used, because a secret key has no public half. To verify an HMAC token, build a signer with the secret, as Algorithms Supported describes, and return signer.Public() from your retriever.

The selected keys are tried after your retriever's keys and before any key the token names. Each selected key counts towards MaxKeysTried. If no member is selected and no other key verifies the token, the error is ErrInvalidSignature, which also matches ErrNoKeyIdentifierMatch, unless another key source failed. A KeySet that is not nil counts as a key source even when it holds no keys. So an empty set refuses every token with that error, a 401, and not with ErrInvalidOptions.

ErrNoKeyIdentifierMatch means that no member was selected. It is a reliable sign that your set lacks the token's key, and that you can fetch your jwks_uri again, only when the token has a kid and every member has one. A member with no kid is selected for every kid. A token with no kid selects every member that its alg can use. In those cases, a token signed with a key you do not have reports ErrInvalidSignature without ErrNoKeyIdentifierMatch.

The set is read again on every call. Never change a set while a call that uses it can run. To refresh it while you serve requests, decode the new document into a new model.Jwks and swap the pointer:

var current atomic.Pointer[model.Jwks]

func refresh(document []byte) error {
    var keySet model.Jwks
    if err := json.Unmarshal(document, &keySet); err != nil {
        return err
    }
    current.Store(&keySet)
    return nil
}

func verify(ctx context.Context, token string) (map[string]any, []byte, error) {
    return jws.Verify(ctx, token, nil, &model.JoseOptions{KeySet: current.Load()})
}

Store a set before you serve requests. Until the first Store, current.Load() returns nil, so KeySet is unset and every call fails with ErrInvalidOptions.

Keys a token carries

A JOSE header can name the key that signed the token, through jwk, jku, x5c or x5u. RFC 7515 section 10.3 says the technique used to get a public key "must authenticate the origin of the key". The four headers differ in whether anything authenticates the key, so each has its own switch:

Header Used when What authenticates the key
x5c X509Roots is set The chain validates against your roots, as section 4.1.6 requires
x5u X509Roots and HttpClient are set The same chain validation, after the fetch
jwk UseTokenProvidedKeys is true Nothing. The token names its own key
jku UseTokenProvidedKeys is true and HttpClient is set Nothing. The token's signer chooses the URL, and TLS proves only the server's identity

jwk and jku are off by default, including when you pass no options, because anyone can sign a token and name their own key. A token that verifies against such a key proves only that its signer holds that key. Turn UseTokenProvidedKeys on only when your application ties those keys to a party you trust some other way:

validated, err := jwt.Validate(ctx, token, nil, nil, &model.JoseOptions{UseTokenProvidedKeys: true}, nil)

Setting X509Roots does not turn jwk or jku on.

When you supply your own retriever and also use a header source, both are tried. The token verifies if a key from either source verifies it.

This is a breaking change in v0.11.0 for a caller that passes no options. v0.10.0 used a jwk header key when opts was nil. Such a caller must now pass UseTokenProvidedKeys: true to keep using it. A caller that set UseTokenProvidedKeys keeps a jwk header key, and now also gets jku when HttpClient is set. A caller that constructed JoseOptions without it was already getting no token keys.

jku and x5u need a client

The two remote headers name a URL this library fetches. Supply the client it should use. The example below uses x5u; jku also needs UseTokenProvidedKeys:

validated, err := jwt.Validate(ctx, token, nil, nil, &model.JoseOptions{
    HttpClient: &http.Client{Transport: yourGuardedTransport},
    X509Roots:  roots,
}, nil)

Both URLs come from the header of the token being verified, so this library makes an outbound request to an address a peer chose, before the signature is checked. Give the client a transport that rejects the destinations your deployment will not allow, such as private, loopback, link-local and other reserved ranges. The body is capped at 4 MiB whatever client you supply. Each fetch uses a copy of your client without its cookie jar. The fetch sends no cookies, and a cookie the server sets does not go into your jar. RFC 8725 section 3.10 asks for this.

Every request a fetch makes must use https, including each redirect hop. RFC 7515 sections 4.1.2 and 4.1.5 say an HTTP GET to retrieve the resource MUST use TLS, so a redirect to plain http is refused before the request is sent, whatever transport you supply. Your client's own redirect policy still applies. When it sets no CheckRedirect, Go's default stops after 10 redirects.

To fetch only the URLs you expect, list them in JoseOptions.AllowedKeyURLs. draft-ietf-oauth-rfc8725bis section 3.10 names this allowlist as a defence against server-side request forgery:

validated, err := jwt.Validate(ctx, token, nil, nil, &model.JoseOptions{
    UseTokenProvidedKeys: true,
    HttpClient:           &http.Client{Transport: yourGuardedTransport},
    AllowedKeyURLs:       []string{"https://issuer.example/jwks.json"},
}, nil)

A jku or x5u must equal an entry exactly, character for character (RFC 3986 section 6.2.1). Nothing is normalised, so https://issuer.example/jwks.json/ and https://ISSUER.example/jwks.json do not match. A URL that matches no entry is not fetched and contributes no key. Another key source can still verify the token. If none does, the error is ErrInvalidSignature, and it also matches ErrNoKeyIdentifierMatch.

A redirect hop must send the request that a listed entry sends. The hop is compared as the absolute URL the client requests: a relative Location is resolved, dot-segments are removed, and the fragment is dropped, because a fragment is never sent. Each entry is parsed the same way, without its fragment. So an entry https://issuer.example/jwks.json#keys matches a hop to https://issuer.example/jwks.json, and the case of a hop's scheme does not matter. A hop that matches no entry is refused before the request is sent, and the fetch fails with ErrApplicationError.

One list serves both jku and x5u. An empty or nil list puts no restriction on either. The list does not turn a source on. jku still needs UseTokenProvidedKeys, and x5u still needs X509Roots. To refuse every fetch, leave UseTokenProvidedKeys off and X509Roots unset, or give no HttpClient. An entry that is not an https URL with a host, or that holds a character no URI holds, can match no header, so every call fails with ErrInvalidOptions. Call jws.CheckOptions at startup to find such an entry before the first token arrives. The list controls which URL a peer can name. It does not control the address that a listed host resolves to, so keep your guarded transport.

Each fetch is also bounded in time, provided your client's transport honours the request's context. JoseOptions.FetchTimeout covers the whole fetch, from sending the request to reading the last byte of the body. When it is zero, the limit is 10 seconds. A deadline or cancellation on the ctx you pass to jwt.Validate, jws.Verify or jws.VerifyCompactSerialization also stops the fetch. The limit applies to each fetch, so a token naming both jku and x5u can take two of them. Use ctx to bound the whole call. Keep FetchTimeout below your own request deadline. Otherwise a slow key server can end your ctx first, and the result is the context's error, which Errors and HTTP responses maps to a 504, not a 401.

A fetch stopped by either limit returns an error that matches ErrApplicationError and context.DeadlineExceeded. One stopped by cancelling ctx matches context.Canceled.

ctx is also checked before each key source is tried, and after the last. So once it has ended, verification stops with its error, which matches context.Canceled or context.DeadlineExceeded, even when no fetch runs. Two cases are different:

  • A token whose format or header is wrong reports that fault, because those checks run first.
  • A key that verifies the token while ctx is ending still verifies it. Ending ctx stops further work, but a signature already checked stays valid. jwe.Decrypt does the same.

With no client, jku and x5u contribute no key. Each member of a jku set is judged on its own, as Which keys are selected describes, and a member this library cannot read is skipped, as RFC 7517 section 5 recommends. A document that is not a JWK Set is refused as a whole: one without a keys member, one whose keys is null or not an array, and one whose keys array holds a null, number, string, boolean or array. An x5u resource is read as the PEM encoding RFC 7515 section 4.1.5 requires. A server that sends raw DER instead is still read: a body that parses as DER certificates is taken as exactly those certificates, and is never searched for PEM text. Any other body is read as PEM text, so a body whose explanatory text is not valid UTF-8 is refused.

Which keys are selected

A key from a jwk header, a member of a jku set, or a member of your JoseOptions.KeySet verifies the token only when all of these hold:

  • Its kid is absent or equals the header's kid. RFC 7515 section 4.1.4 calls the header's kid a hint, and RFC 7517 section 4.5 makes a jwk's kid optional, so a key that names no kid stays a candidate.
  • Its alg is absent or equals the header's alg. RFC 8725 section 3.1 says "each key MUST be used with exactly one algorithm". EdDSA and Ed25519 count as equal, because with an Ed25519 key they name the same algorithm. A key that names no alg stays a candidate, since RFC 7517 section 4.4 makes alg optional. Such a key verifies under any algorithm its key type allows, so pin AllowedSigningAlgorithms to bind it to one.
  • Its kty, and its crv where the key type has one, can serve the header's alg. RFC 7518 sections 3.2 to 3.5 give oct to HS256 to HS512, RSA to the RS and PS families, and EC to ES256, ES384 and ES512 on P-256, P-384 and P-521. RFC 9864 gives OKP with crv Ed25519 to Ed25519. This library implements EdDSA (RFC 8037 section 3.1) with Ed25519 only, so it gives EdDSA the same key. RFC 9964 gives AKP to the ML-DSA algorithms, and its alg names the parameter set. Any other crv string is not selected, such as secp256k1, X25519 or Ed448. A key with no crv, or a crv that is not a string, is left to the key reader, which refuses it.
  • Its use is absent or "sig", and its key_ops is absent or includes "verify". RFC 7517 sections 4.2 and 4.3 let a publisher mark a key as not for verifying signatures.

A set is never used whole because nothing in it matched. When no member of a jku set or of KeySet qualifies, that set contributes no key, and the result matches ErrNoKeyIdentifierMatch. VerifyCompactSerialization then tries the next key source. If no key verifies, it reports ErrInvalidSignature, and the error also matches ErrNoKeyIdentifierMatch, unless another source failed.

A jwk header names a public key (RFC 7515 section 4.1.3). A jwk header that holds a private key member, d, p, q, dp, dq, qi, oth, k or priv, makes the header malformed. The token is refused with ErrMalformedToken and ErrMalformedClaim, whether or not UseTokenProvidedKeys is set. The same applies to a JWE's jwk and epk. The member names are case-sensitive, so D is not a private member.

When a key source fails, verification continues with the next source. A source fails when a fetch fails, a body is too large, a body does not decode, or your retriever returns an error. A key the token carries in its header, a jwk or an x5c, is different. Its bytes are in the signed header, so a fault in it is the same every time. So when verification reaches such a key and it cannot be used, the token is refused at once, and no later source is tried. A carried key that is only not selected, such as a jwk whose kid differs from the header's or an x5c chain that reaches none of your roots, gives way like any other source. Verification stops at the first key that verifies, so a key from your own retriever, which is tried first, can verify the token before a carried key is read. If no key verifies the signature, the error wraps each failure. It matches ErrApplicationError for a failed fetch, and context.DeadlineExceeded or context.Canceled when applicable. It does not match ErrInvalidSignature. A kid, alg, use or key_ops of the wrong JSON type means a member of a jku set or of KeySet is not selected. In an inline jwk, it makes the header malformed, so the token is refused with ErrMalformedToken and ErrMalformedClaim, whatever the header holds. A key_ops that lists a value twice is treated the same way. So is a use and key_ops that are not consistent, because RFC 7517 section 4.3 says they MUST be consistent when both are present. A use of "sig" is not consistent with encrypt, decrypt, wrapKey, unwrapKey, deriveKey or deriveBits. A use of "enc" is not consistent with sign or verify. With IgnoreKeyUse set, use and key_ops are not read, so only kid, alg and the key type are checked.

No RFC makes use or key_ops a requirement: section 4.3 leaves it to each application to say which, if either, it honours. This library honours both by default. Set JoseOptions.IgnoreKeyUse to skip that check. It never relaxes the kid, alg and key type rules.

Keys that section 4.3 discourages

RFC 7517 section 4.3 says that a jwk SHOULD NOT carry both use and key_ops. It also says that key_ops SHOULD NOT name unrelated operations. The only related pairs are sign with verify, encrypt with decrypt, and wrapKey with unwrapKey. Neither rule is a MUST, so this library accepts such a jwk by default.

Set JoseOptions.StrictKeyOperations to refuse such a jwk. Then a key_ops of more than one value must be one of the three pairs. This also refuses deriveKey with deriveBits, which WebCrypto gives an ECDH private key. The option applies to a token's jwk and jku keys, to the members of KeySet, to jws.GetSignerFromJwk and to jws.GetValidatorFromJwk. jwe.GetEncrypterFromJwk and jwe.GetDecrypterFromJwk take the same option in model.JWEOptions. IgnoreKeyUse turns it off for a token's keys and for KeySet, because no use or key_ops rule applies to them then.

Stating what you expect of a header

Most JOSE profiles pin their own typ, many require a kid, and RFC 7515 section 4.1.11 says a JWS whose crit lists an extension the recipient does not understand MUST be rejected. Rather than decoding the header yourself to check those, say what you expect:

validated, err := jwt.Validate(ctx, token, retriever, nil, &model.JoseOptions{
    AcceptedTypes:             []string{"example+jwt"},
    RequireKeyIdentifier:      true,
    UnderstoodCriticalHeaders: []string{"x-example"},
    AllowedSigningAlgorithms:  []jwa.Algorithm{jwa.ES256, jwa.RS256},
}, nil)

Each is off when unset, so none of this changes what an existing caller sees, except crit and the error AllowedSigningAlgorithms reports, below.

An AcceptedTypes entry must be a media type name, as RFC 6838 section 4.2 defines it, optionally with parameters. An entry such as "", " JWT", "JWT " or "*/*" can match no typ, so the call fails with ErrInvalidOptions, whatever the token. This catches a value read with stray whitespace from a configuration file, which would otherwise lock out every token. The same applies to an AllowedSigningAlgorithms entry that is not a signature algorithm this library implements, such as jwa.A128KW, and to the AcceptedTypes and allow-lists of model.JWEOptions. jwt.Validate checks both options values before it reads the token, whatever its shape.

AcceptedTypes compares as RFC 7515 section 4.1.9 requires: it ignores the case of ASCII letters only, as RFC 6838 section 4.2 defines media type names in ASCII. So a lookalike letter such as ſ (a long s) does not match s. It treats application/ as prepended to any value containing no /. So naming example+jwt accepts application/example+jwt and Example+JWT, and refuses x-example+jwt. Media-type parameters are ignored on both sides, so example+jwt; v=1 matches example+jwt. Spaces and tabs before the ; are ignored too. Whitespace at the start of the value, or at its end with no parameters, is not, so " example+jwt" and "example+jwt " are refused. A typ with no type before its parameters matches nothing.

RequireKeyIdentifier refuses a kid that is absent or is not a non-empty string. RFC 7517 section 4.5 leaves kid optional, which is why it is off by default.

UnderstoodCriticalHeaders names the extensions you handle. This one is a breaking change in v0.11.0: this library understands no extensions of its own, so with nothing named, any crit is now refused. Previously a crit listing an unknown extension was accepted, which section 4.1.11 forbids. A caller that handles an extension names it; a caller that handles none needs no change, because a token carrying crit was never safe for them to accept.

An alg outside AllowedSigningAlgorithms is refused during header validation rather than at signature verification, so a declined algorithm stops before any jku or x5u is fetched on that header's behalf. It reports ErrUnsupportedAlgorithm: the signature was never examined, so a caller can tell this from a bad signature with errors.Is.

x5c and x5u need trust anchors

The two certificate headers are different, and they do nothing unless you configure roots for them. RFC 7515 section 4.1.6 says a recipient:

MUST validate the certificate chain according to RFC 5280 and consider the certificate or certificate chain to be invalid if any validation failure occurs.

RFC 5280 path validation takes a trust anchor as an input. A chain cannot vouch for itself, so without an anchor there is nothing to validate against and the header cannot be used:

roots := x509.NewCertPool()
roots.AppendCertsFromPEM(issuerRootPEM)

validated, err := jwt.Validate(ctx, token, nil, nil, &model.JoseOptions{X509Roots: roots}, nil)

With no X509Roots configured, a token's x5c and x5u headers contribute no key. They are not an error — section 4.1.6 makes use of the header OPTIONAL — so the token still verifies if another key source does. If none does, the error is ErrInvalidSignature when your retriever's keys were tried. With no retriever, it is ErrInvalidOptions when neither KeySet nor UseTokenProvidedKeys is set, because no key source can exist. Otherwise it is ErrNoKeyIdentifierMatch, or ErrInvalidSignature when a key was tried.

A malformed x5c is refused whether or not roots are configured, because its shape is a property of the claim rather than of your trust configuration. An array that is not an array of strings, an empty array, or an entry that is not exactly one base64-encoded DER certificate is ErrMalformedClaim. Section 4.1.6 names the base64 of RFC 4648 section 4, and RFC 4648 section 3.3 says a decoder MUST reject characters outside the alphabet. So an entry holding a line break is refused, as is one whose pad bits are not zero. An x5u body is PEM, where line breaks are part of the format, so this does not apply to it.

The signing key is taken from the first certificate, and that certificate is the one validated against your roots, as section 4.1.6 requires. The algorithm the issuer used to sign that certificate is not compared with the token's alg. An ES256 key in a certificate issued by an RSA root is usable.

An x5c or x5u chain must be in order. Each certificate after the first must be the one that signed the certificate before it, as RFC 7515 sections 4.1.5 and 4.1.6 require. Its subject must be the issuer of the certificate before it. A chain can hold at most 16 certificates. A chain that breaks either rule is refused with ErrMalformedClaim. This library checks the x5c count even when no roots are configured.

That first certificate must also be one whose key may verify a signature. x5c and x5u get the same checks:

  • Key usage. When the certificate has a key usage extension, it must assert digitalSignature or nonRepudiation (x509.KeyUsageContentCommitment). RFC 5280 section 4.2.1.3 defines both as the bits for a key that verifies signatures, and requires at least one bit to be set when the extension appears, so an extension with no bit set is refused. A CA certificate that asserts only keyCertSign is refused, as is a key agreement certificate. An intermediate whose key usage extension is present must assert keyCertSign, as RFC 5280 section 6.1.4(n) requires. Go's chain verification checks this only when some bit is set, so this library also refuses an intermediate whose extension asserts no bit. The certificate is accepted when at least one chain avoids such an intermediate, and the trust anchor is not checked.
  • Extended key usage. RFC 5280 section 4.2.1.12 says that when the extension is present, the certificate "MUST only be used for one of the purposes indicated". No purpose is registered for JWS, so you name the ones you accept in JoseOptions.X509ExtKeyUsages. When it is unset, only the signing certificate is checked: if its extension is present, it must name anyExtendedKeyUsage. When it is set, it is passed to Go's chain verification, which nests extended key usage, so the signing certificate and every CA above it must permit one of those purposes. A certificate with no extended key usage extension is accepted either way. A signing certificate or intermediate whose extension names no purpose is refused in every case, because the section defines it as a sequence of at least one. Go's chain verification treats such an extension as no restriction at all, so this library checks every chain it returns, and accepts the certificate when at least one chain has no such intermediate. The trust anchor is not checked: RFC 5280 section 6.1.1 takes from it only a name and a key.
validated, err := jwt.Validate(ctx, token, nil, nil, &model.JoseOptions{
    X509Roots:        roots,
    X509ExtKeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning},
}, nil)

Naming x509.ExtKeyUsageAny turns the purpose check off, as it does in Go's x509.VerifyOptions. A purpose Go has no constant for, such as a private OID, cannot be named, so a certificate restricted to one is accepted only with the check off. A refusal for either usage matches ErrNoKeyIdentifierMatch, as a chain that does not validate does.

Jwks

The jwk package converts keys to jwks and back, and computes thumbprints.

Every jwk these methods return carries a kid: the key's RFC 7638 JWK SHA-256 Thumbprint, base64url encoded. RFC 7638 hashes only the key type's required members, kty included, so two keys of different types cannot share a kid. Any other implementation computes the same value for the same key. A private key's kid is that of its public key, as RFC 7638 section 3.2.1 defines. The kid is a suggestion: set your own on the returned map if you name keys another way.

jwk.Thumbprint computes the thumbprint of any jwk of kty EC, RSA, oct, OKP or AKP. For AKP the members are alg, kty and pub, as RFC 9964 section 6 defines:

func jwk.Thumbprint(jwk map[string]any) (string, error)

It refuses a jwk missing a required member, or one whose member would need escaping in JSON, because RFC 7638 section 3.3 defines no thumbprint for it.

jwk.PublicJwk and jwk.PrivateJwk return the jwk of a key:

func jwk.PublicJwk(publicKey crypto.PublicKey) (*map[string]any, error)
func jwk.PrivateJwk(privateKey crypto.PrivateKey) (*map[string]any, error)

Pass the key in the form the standard library gives it. An *ecdsa.PublicKey, an *rsa.PublicKey, an ed25519.PublicKey (or a pointer to one), or an *mldsa.PublicKey is accepted. PrivateJwk takes the private equivalents. Anything else is refused with ErrInvalidPublicKey or ErrInvalidPrivateKey.

A key that cannot be encoded is refused with the same errors:

  • A nil key, or a key with a missing field.
  • An EC key on a curve other than P-256, P-384 and P-521, the curves RFC 7518 section 6.2.1.1 registers. The curve must be the standard library's own elliptic.P256(), P384() or P521(); another curve that carries one of those names is refused.
  • An EC key whose point is not on its curve, including a negative coordinate or one too large for the curve.
  • An EC private key whose d is outside [1, n-1], where n is the order of the curve.
  • An EC private key whose d is not the private key of its point.
  • An Ed25519 private key whose second half is not the public key of its seed.
  • An Ed25519 public key that is not the canonical encoding of a point. RFC 8032 section 5.1.3 refuses a y of 2^255-19 or more, and a set sign bit when x is 0.
  • An RSA key whose e is not an odd integer from 3 to 2^31-1.
  • An RSA private key whose d is not between 0 and n, or does not undo e.
  • An RSA private key with a modulus over 8192 bits, with or without its primes. No signer or decrypter of this library accepts one.
  • An RSA private key with one prime, or more than two. RFC 7518 section 6.3.2.7 says a consumer that does not support more than two MUST NOT use such a key, and PrivateFromJwk refuses a jwk that carries oth.
  • An RSA private key with a prime that is not positive. RFC 8017 section 3.2 makes p and q positive integers.
  • A two-prime RSA private key that rsa.PrivateKey.Validate rejects, such as one whose primes do not multiply to n.

An EC private key's d is padded to the length of the curve order, as RFC 7518 section 6.2.2.1 requires.

An RSA private key with no primes is encoded as n, e and d. RFC 7518 section 6.3.2 makes d the only required private member. A two-prime key also carries p, q, dp, dq and qi, which that section says producers SHOULD include. The CRT values are computed on a copy, so the caller's key is not changed.

// Direct from a public key
jwkMap, err := jwk.PublicJwk(publicKey)

// From a Signer. Note Public() is a call. Its result is already a pointer
// for the EC, RSA and ML-DSA algorithms, and a value for Ed25519. An HMAC
// signer's Public() is its secret, which PublicJwk refuses
signer, err := jws.GetSigner(jwa.ES256, nil)
signerJwkMap, err := jwk.PublicJwk(signer.Public())

Two methods convert a jwk back into a key:

func jwk.PublicFromJwk(jwk map[string]any) (crypto.PublicKey, error)
func jwk.PrivateFromJwk(jwk map[string]any) (crypto.PrivateKey, error)

The key is returned in the type that x509.ParsePKIXPublicKey or x509.ParsePKCS8PrivateKey returns for it. An EC key is an *ecdsa.PublicKey, an RSA key an *rsa.PublicKey, and an ML-DSA key an *mldsa.PublicKey. An Ed25519 key is an ed25519.PublicKey, which is a value and not a pointer. See Ed25519 keys are values. PrivateFromJwk returns the private equivalents.

An oct jwk holds a symmetric key in k, as RFC 7518 section 6.4.1 defines. PrivateFromJwk reads it as a []byte, and refuses a k that is absent, not a string, not strict base64url or empty. PrivateJwk writes a []byte as an oct jwk with no kid, because RFC 7638 section 7 says to conceal the thumbprint of a symmetric key. It writes what Public() returns for a secret key the same way, with an alg that names the algorithm the key was made for. GetSignerFromJwk and the jwe jwk constructors hold the jwk to that alg. PrivateFromJwk reads the jwk as a []byte, which carries no algorithm, so the binding ends there, as it does if the alg is removed. A symmetric key has no public half, so PublicFromJwk and PublicJwk refuse it with ErrInvalidPublicKey. jws.GetSignerFromJwk builds an HS256, HS384 or HS512 signer from an oct jwk.

An OKP jwk is read when its crv is Ed25519 or X25519, the two OKP subtypes this library supports. RFC 8037 section 2 requires crv, so a jwk without a string crv is refused as an invalid key. Any other subtype, such as X448, is refused with ErrUnsupportedAlgorithm, because Go has no X448.

For Ed25519, PublicFromJwk returns an ed25519.PublicKey and PrivateFromJwk returns an ed25519.PrivateKey. Each of x and d must be 32 octets, the key sizes RFC 8032 section 5.1.5 sets. For a private key, x must be the public key of d. x must be the canonical encoding of a point, so one key has one x and one thumbprint. The readers and PublicJwk do not refuse a point of small order, but the Ed25519 validator does. See Which keys a signer or validator accepts.

For X25519, PublicFromJwk returns an *ecdh.PublicKey and PrivateFromJwk returns an *ecdh.PrivateKey. Each of x and d must be 32 octets. For a private key, x must be the public key of d. A public x that is not canonical is accepted, because RFC 7748 section 5 requires it. PublicJwk and PrivateJwk write an X25519 *ecdh key as an OKP jwk, and an *ecdh key on P-256, P-384 or P-521 as an EC jwk, which reads back as an *ecdsa key. RFC 8037 section 3.2 forbids signing with an X25519 key, so no signer or validator accepts one: jws.GetValidatorFromJwk refuses an X25519 jwk with ErrInvalidPublicKey, and verification skips one in a jku set or an inline jwk.

This is a breaking change in v0.11.0 for OKP keys. Earlier versions ignored the value of crv, so an X25519 or Ed448 key was returned as an Ed25519 key. They also accepted any length of x and d, and did not compare x with d. A key that those versions read can now be refused.

An AKP jwk is read as RFC 9964 defines it. Section 3 requires alg, and it must be ML-DSA-44, ML-DSA-65 or ML-DSA-87. A jwk with no string alg is refused as an invalid key, and any other alg with ErrUnsupportedAlgorithm. pub must be the public key size section 5 gives for that alg: 1312, 1952 or 2592 octets. A private key's priv must be the 32 octet seed of section 4, and pub must be the public key that seed derives, which section 7.4 calls for. PublicFromJwk reads the public key of a private AKP jwk and does not read priv, as it does for EC and RSA. PublicJwk never writes priv, which section 3 says MUST NOT be present in a public key.

An EC jwk is read only when its crv is P-256, P-384 or P-521. Any other curve is refused with ErrUnsupportedAlgorithm. Each of x and y must be the full size of a coordinate of the curve: 32, 48 or 66 octets. RFC 7518 sections 6.2.1.2 and 6.2.1.3 require this, so a coordinate with a leading zero octet dropped or added is refused. The point must be on the curve. A private key must carry d, which RFC 7518 section 6.2.2 makes REQUIRED. d must be the length of the curve order, in [1, n-1], and x and y must be its public point.

Each integer member of an RSA jwk (n, e, d, p, q, dp, dq and qi) must use the minimum number of octets, as RFC 7518 section 2 requires of a Base64urlUInt. A member with a leading zero octet is refused with ErrMalformedClaim. Zero itself is the one octet "AA". Without this rule one key would have more than one jwk, and so more than one RFC 7638 thumbprint.

An RSA jwk's e must be an odd integer from 3 to 2^31-1. RFC 8017 section 3.1 sets the lower bound and requires an odd value, and crypto/rsa refuses a larger one. A private key's d must be a positive integer less than n, as RFC 3447 section 3.2 defines it. When p and q are present, the key must pass rsa.PrivateKey.Validate, and dp, dq and qi must be the CRT values of p, q and d. When they are absent, the reader recovers p and q from n, e and d, as NIST SP 800-56B Rev. 2 Appendix C.1 describes. The key must then pass rsa.PrivateKey.Validate. The key that the reader returns carries p, q and their CRT values, so it signs as fast as a key read with them. A p or q that is not less than n is refused before Validate runs, as RFC 8017 section 3.2 makes n their product. If d does not undo e, the primes are not found or the key fails Validate, and the jwk is refused. The method recovers only two primes, so a key with no primes whose modulus has more than two is refused, like a jwk that carries oth. An *rsa.PrivateKey that lists more than two primes, as rsa.GenerateMultiPrimeKey returns, is still accepted by the signers. Recovery usually costs one or two full-size exponentiations, so a key without its primes reads about ten times slower than one with them: about 0.5 seconds at 8192 bits. A modulus that is prime is refused before recovery starts. PrivateFromJwk refuses a bad n, e, d, prime or CRT value in an RSA private key with ErrInvalidPrivateKey, and a bad n or e also matches ErrInvalidPublicKey, because PublicFromJwk refuses it too. A Base64urlUInt with no octets is refused with ErrMalformedClaim. An n of zero is refused. A modulus over 8192 bits is refused before any private member is checked, with or without the primes. PrivateFromJwk sets no minimum size, so it reads a 1024-bit key. PublicFromJwk sets no size bound at all. The signers, validators, encrypters and decrypters refuse a modulus outside 2048 to 8192 bits, and RFC 7518 sections 3.3, 3.5 and 4.3 require the minimum.

A kty or crv that this library does not read, and an AKP alg that it does not implement, are refused with ErrUnsupportedAlgorithm. Every other refusal by PublicFromJwk matches ErrInvalidPublicKey, and every other refusal by PrivateFromJwk matches ErrInvalidPrivateKey. When PrivateFromJwk refuses a jwk that PublicFromJwk also refuses, other than an oct jwk, the error matches ErrInvalidPublicKey too. So test ErrInvalidPrivateKey first. A member that is absent also matches ErrMissingClaim. A member that is present but not a string, null included, or not base64url also matches ErrMalformedClaim. The error for an unsupported kty or crv names the values this library supports. It does not repeat the value the jwk carried, so a peer's text does not reach your logs.

Key sets

model.Jwks holds a JWK Set. Decoding JSON into it follows RFC 7517 section 5: the document must be an object with a keys member holding an array of JWKs. Anything else is refused with ErrKeystoreError, including a missing keys, "keys": null and a document that is itself null. A field that may hold no set should be a *model.Jwks, which null leaves nil. The member is found by its exact name, keys, as RFC 7515 section 5.3 compares names; KEYS, Keys and other spellings are ignored like any unknown member. An element of the keys array that is null or not a JSON object is refused. A document that is not UTF-8, or that holds an unpaired UTF-16 surrogate escape, is refused with ErrKeystoreError. RFC 8259 sections 8.1 and 8.2 give these rules.

Add refuses a jwk whose kty is absent, empty or not a string, with ErrKeystoreError, as RFC 7517 section 4.1 requires a kty. Decoding does not apply this rule, because RFC 7517 section 5 says that a member a reader cannot use is skipped, not that the set is refused. Opts.EnforceUniqueKIDs applies to Add only. With it, Add refuses a kid that the set already holds, or one that is not a string, and accepts any number of jwks with no kid. Decoding keeps every key, including keys with the same kid. A nil *model.Jwks holds no key: RetrieveByKeyID returns ErrKeystoreError and Add refuses with it, so neither panics.

Jwks.RetrieveByKeyID returns every key that carries the given kid, in set order, because RFC 7517 section 4.5 does not make a kid unique. It returns an error only when no key carries it.

To verify tokens with the keys of a set, pass it as JoseOptions.KeySet. Verifying with your own key set describes how a member is selected for a token.

JWTs

This library includes two methods for jwt handling

The first signs a jwt from a signer, a head map and a body map:

func jwt.New(signer crypto.Signer, head, body map[string]any, opts jwt.Opts) (*string, error)

New does not change the maps you pass. A nil head is an empty header, and a nil body is the empty claims set {}. If the head carries no typ, the token's header gets "JWT".

jwt.Opts names the algorithm to sign with:

type jwt.Opts struct {
	Algorithm jwa.Algorithm
}

The token's alg header always names the algorithm that made the signature, as RFC 7515 section 4.1.1 requires:

  • A signer from this library signs with its own algorithm, and New writes that algorithm into alg. Opts may leave Algorithm unset. New calls it in JOSE mode, with the whole signing input. So does any other model.Signer.
  • Any other crypto.Signer takes its algorithm from Opts.Algorithm, or from an alg the head names. With neither, New returns an error.
  • If the head's alg or Opts.Algorithm names a different algorithm, New returns ErrUnsupportedAlgorithm. So does an alg that is not a string.

Any other crypto.Signer, such as a KMS signer, is called as Go's crypto.Signer contract defines:

  • For ES256, ES384 and ES512, New converts the ASN.1 DER signature the signer returns to the fixed-length R||S form of RFC 7518 section 3.4. The key must be on P-256, P-384 or P-521 respectively. Output that is not DER, or an R or S outside 1 to n-1 (FIPS 186-5 section 6.4.1), is refused with ErrSigningError.

  • For PS256, PS384 and PS512, New asks for RSASSA-PSS with a salt the size of the hash, as RFC 7518 section 3.5 requires. For RS256, RS384 and RS512 it asks for RSASSA-PKCS1-v1_5.

  • For Ed25519, the key must be an Ed25519 key.

  • For ML-DSA-44, ML-DSA-65 and ML-DSA-87, the key must be an ML-DSA key of that parameter set. New passes the whole signing input with a zero hash, so crypto/mldsa signs it with an empty context.

  • A key that does not suit the algorithm, and any HS algorithm, is refused with ErrInvalidPrivateKey.

  • New passes an *ecdsa.PrivateKey, *rsa.PrivateKey, ed25519.PrivateKey or *ed25519.PrivateKey to GetSignerFromPrivateKey, and refuses each key that GetSignerFromPrivateKey refuses. So an RS or PS key needs a modulus of 2048 to 8192 bits. For any other crypto.Signer, New checks the public key that Public returns, the same way a validator does.

  • New refuses a nil signer, or a nil pointer, with ErrInvalidPrivateKey. It does not panic.

  • New refuses an alg outside jwa, such as jwa.Algorithm(999), with ErrUnsupportedAlgorithm. RFC 7515 section 4.1.1 says alg must be present and understood.

  • New checks the header it will sign with the same rules Validate applies. So it does not sign a header that its own Validate refuses for its shape:

    • jku and x5u must be HTTPS URLs. RFC 7515 sections 4.1.2 and 4.1.5 require TLS.
    • Each must name a host. RFC 9110 section 4.2.2 says a recipient MUST reject an https URI with an empty host, such as https:///jwks.
    • Each must hold only URI characters. RFC 3986 section 2 allows ASCII letters, digits, -._~:/?#[]@!$&'()*+,;= and percent-encodings, so a space, a control character or a non-ASCII character is refused. Percent-encode it instead.
    • jwk must be a JSON object, and must not hold a private key member: d, p, q, dp, dq, qi, oth, k or priv (section 4.1.3 names a public key). Its kid, alg and use must be strings, its key_ops an array of distinct strings, and its use and key_ops consistent (RFC 7517 sections 4.2 to 4.5). Validate refuses a jwk header that breaks these rules.
    • kid, typ and cty must be strings (sections 4.1.4, 4.1.9 and 4.1.10).
    • x5c must be a non-empty array of base64 DER certificates (section 4.1.6).
    • x5t and x5t#S256 must be base64url (sections 4.1.7 and 4.1.8).
    • crit must be a non-empty array of distinct names. Each name must be in the header, and must not be a parameter that RFC 7515 defines (section 4.1.11).
    • b64 must be a JSON boolean (RFC 7797 section 3).

    A fault is ErrMalformedClaim. A crit name that the header does not hold is ErrMissingCriticalClaim.

  • New refuses a b64 of false with ErrMissingCriticalClaim, because it always encodes the payload.

  • New refuses a b64 that crit does not name with ErrMissingCriticalClaim. RFC 7797 section 6 says crit MUST include b64 when b64 is used. To sign with "b64": true, also set "crit": ["b64"]. A verifier must then name b64 in UnderstoodCriticalHeaders.

The second validates a JWT of any shape: signed, encrypted, or signed and then encrypted. It returns a *jwt.Token:

func jwt.Validate(ctx context.Context, token string, outOfBoundsPublicKey model.Retriever, decrypters []model.Decrypter, opts *model.JoseOptions, jweOpts *model.JWEOptions) (*jwt.Token, error)
Token field Holds
Claims The JWT Claims Set
SignatureHeader The JOSE Header of the JWS that signed the claims, or nil for a JWT that is only encrypted
EncryptionHeader The JWE Protected Header, or nil for a JWT that is only signed
Decrypter The decrypter that decrypted the token, or nil for a JWT that is only signed

opts applies to the JWS and to the claims. jweOpts applies to the JWE, and has its own type, model.JWEOptions, so the two cannot be swapped. A rule for one layer can be wrong for the other. For example, an AcceptedTypes of JWT is correct for a signed JWT, but refuses the JWE around it, which usually has no typ. A JWT that is only signed needs no decrypters. If you give decrypters or jweOpts, Validate checks them as options for every token, as jwe.CheckOptions describes, and uses neither for a signed JWT. jwt.CheckOptions(retriever, decrypters, opts, jweOpts) takes the arguments that you pass to Validate, and runs every check that Validate makes before it reads the token. It also refuses, with ErrInvalidOptions, two kinds of argument under which no token can pass:

  • RequireEncryptedJWT with no decrypter whose alg the JWE options permit.
  • No source of signing keys, when no JWT that is only encrypted can pass either. A source is a retriever, or one of KeySet, UseTokenProvidedKeys and X509Roots. Those three supply no HMAC key, so they do not count when AllowedSigningAlgorithms names only HMAC algorithms. A JWT that is only encrypted can pass when RequireSignedJWT is off, and a decrypter is for dir, an AES key wrap or PBES2, or AllowUnauthenticatedJWT is set.

It does not find every such case. For example, it cannot see the enc that a dir decrypter is bound to. Call it at startup to find a configuration fault before the first token arrives. jws.CheckOptions and jwe.CheckOptions check the option values of jws.Verify and jwe.Decrypt. jws.CheckOptions takes no retriever, so it cannot tell that jws.Verify has no source of keys.

RFC 7519 allows a JWT that is signed, encrypted, or both. To accept only the shapes that you expect, set these in opts:

  • RequireSignedJWT refuses a JWT that is only encrypted, under any key, with ErrInvalidSignature. Set it if every JWT must carry an issuer's signature. It needs a source of signing keys: with no retriever and none of KeySet, UseTokenProvidedKeys and X509Roots, every call fails with ErrInvalidOptions. If you also hold a shared key, its other holders then cannot write claims of their own.
  • RequireEncryptedJWT refuses a JWT that is not encrypted, with ErrUnsupportedAlgorithm. Set it if your peers encrypt every JWT to you. It needs a decrypter whose alg the JWE options permit. Without one, every call fails with ErrInvalidOptions.

Validate returns a nil *Token with every error, so check err before you read the token.

The retriever supplies key material of your own. Pass nil when you set KeySet, or when a key the token's header names can verify it: when you have turned on UseTokenProvidedKeys for jwk and jku, or set X509Roots for x5c and x5u. With a nil retriever and none of these options, no token can verify, so Validate refuses every token with ErrInvalidOptions, before it reads the token. jws.Verify refuses it after it checks the header. If UseTokenProvidedKeys or X509Roots is set and the token names no key that it allows, the error is ErrNoKeyIdentifierMatch. If you give jwt.Validate decrypters, an encrypt-only JWT can pass without a retriever when RequireSignedJWT is off and a decrypter is for dir, an AES key wrap or PBES2, or AllowUnauthenticatedJWT is set. A nil retriever is then not an options fault. A signed JWT is then refused with ErrInvalidSignature, which also matches ErrNoKeyIdentifierMatch, unless a member of KeySet or a key the token names verifies it. model.JoseOptions carries everything described under Keys a token carries, and may be nil for the defaults.

Validate checks each registered claim that is present:

Claim Rule Error when broken
iss, sub, jti Must be a string (RFC 7519 sections 4.1.1, 4.1.2 and 4.1.7) ErrMalformedClaim
aud Must be a string or an array of strings (RFC 7519 section 4.1.3) ErrMalformedClaim
iat, nbf, exp Must be a JSON number, a NumericDate (RFC 7519 section 2). A fractional value keeps its fraction, and is compared as float64 seconds, to within a microsecond ErrMalformedClaim
exp The current time must be before exp (RFC 7519 section 4.1.4). A token is expired at the instant exp names ErrExpired
nbf The current time must be at or after nbf (RFC 7519 section 4.1.5) ErrNotYetValid
iat Must not be after the current time ErrNotYetValid

The iat rule is this library's own. RFC 7519 section 4.1.6 sets no acceptance rule for iat, but a token issued in the future signals a clock fault or a forged timestamp, so Validate refuses it.

JoseOptions.ClockSkewLeeway widens the window the three time claims are judged against: nbf and iat may be up to the leeway in the future, and a token stays valid until the leeway has passed after exp.

A value too large for any clock, such as an nbf of 1e19, is judged as a time far in the future. It is not converted to an integer, so the result is the same on every CPU. A number outside the float64 range, such as 1e400, is different: the JSON decoder refuses the token with ErrMalformedToken before any claim is read. RFC 8259 section 6 lets a recipient limit the range of numbers.

Validate refuses a token that does not have three or five segments with ErrMalformedToken. See Encrypted JWTs for a token of five segments.

To check the audience, name this recipient in JoseOptions.ExpectedAudience:

opts := &model.JoseOptions{ExpectedAudience: []string{"https://rp.example"}}

aud must then hold a value equal to one of these, compared exactly and case-sensitively, as RFC 7519 section 4.1.3 requires. A token with no aud is refused with ErrMissingClaim, as RFC 8725 section 3.9 requires. A token naming only other recipients is refused with ErrAudienceMismatch.

An empty string names no recipient. If ExpectedAudience holds one, Validate refuses every token with ErrInvalidOptions. This catches a value read from an unset environment variable, which would otherwise match a token whose aud is "".

With ExpectedAudience unset, this library does not meet RFC 7519 section 4.1.3. That section says: "If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected." By default, Validate checks only the type of aud and accepts a token whatever it names. Set ExpectedAudience to meet that MUST. RFC 8725 section 3.9 also requires the check whenever one issuer issues tokens for more than one audience.

To check the issuer, name the issuers that you accept in JoseOptions.ExpectedIssuer:

opts := &model.JoseOptions{ExpectedIssuer: []string{"https://issuer.example"}}

iss must then equal one of these. The comparison is exact, with no transformation or canonicalisation, as RFC 7519 section 2 requires for a StringOrURI. So https://issuer.example/ does not match https://issuer.example. A token with no iss is refused with ErrMissingClaim. A token naming another issuer is refused with ErrIssuerMismatch. An iss that is not a string is refused with ErrMalformedClaim first. If ExpectedIssuer holds an empty string, Validate refuses every token with ErrInvalidOptions.

ExpectedIssuer compares the claim only. It does not show that the key that verified the token belongs to that issuer. RFC 8725 section 3.8 requires that check too, and the application must make it. So give Validate a retriever that returns the keys of that issuer only.

To accept several issuers, call Validate once for each issuer. Give each call the retriever of that issuer, and an ExpectedIssuer that names that issuer only. Try the issuers in a fixed order, and return the first token that passes. Example_severalIssuers in jwt/example_test.go runs this code:

type issuerKeys struct {
	issuer    string
	retriever model.Retriever
}

var refusedAfterTheSignature = []error{
	joseerror.ErrExpired,
	joseerror.ErrNotYetValid,
	joseerror.ErrMissingClaim,
	joseerror.ErrMalformedClaim,
	joseerror.ErrIssuerMismatch,
	joseerror.ErrAudienceMismatch,
}

func validateFromOneOf(ctx context.Context, token string, issuers []issuerKeys) (*jwt.Token, error) {
	if len(issuers) == 0 {
		return nil, fmt.Errorf("%wno issuer is configured", joseerror.ErrInvalidOptions)
	}
	failures := make([]error, 0, len(issuers))
	for _, candidate := range issuers {
		opts := &model.JoseOptions{ExpectedIssuer: []string{candidate.issuer}}
		validated, err := jwt.Validate(ctx, token, candidate.retriever, nil, opts, nil)
		if err == nil {
			return validated, nil
		}
		failures = append(failures, err)
	}
	for _, err := range failures {
		for _, reason := range refusedAfterTheSignature {
			if errors.Is(err, reason) {
				return nil, err
			}
		}
	}
	for _, err := range failures {
		if !errors.Is(err, joseerror.ErrInvalidSignature) {
			return nil, err
		}
	}
	return nil, failures[0]
}

When every call fails, return the error of a call whose keys verified the signature. That call refused the token on its claims, such as ErrExpired or ErrIssuerMismatch, so its error is the true reason. A call with the keys of another issuer fails earlier, with ErrInvalidSignature. A fault in the header, such as an ErrMalformedClaim, is the same in every call, so returning it is also correct. If no call got past the signature, return the first error that does not match ErrInvalidSignature, such as a failure of your key store, so that an outage maps to a 5xx. Otherwise return ErrInvalidSignature. With no issuers configured, return an error that matches ErrInvalidOptions, not a nil token.

Do not name several issuers in one call that has the keys of more than one of them. Then issuer B can sign a token whose iss names issuer A, and the token passes. Name several values in one call only when they are names of one issuer.

A JWT that is only encrypted under a shared key or password has no signature. The decrypter is what shows who wrote it. So compare Token.Decrypter with the key of the issuer, or set RequireSignedJWT.

To require a claim, name it in JoseOptions.RequiredClaims:

opts := &model.JoseOptions{RequiredClaims: []string{"exp", "iss", "sub"}}

RFC 7519 section 4.1 makes no claim mandatory, and leaves the choice to the application. By default, a token with no exp never expires. With RequiredClaims set, the claims set must have a member of each name, else Validate refuses the token with ErrMissingClaim. The error names the missing claim. A member is present whatever its value, null included. The type rules in the table above still apply, so an exp of null is refused with ErrMalformedClaim. Names are compared exactly, so EXP does not satisfy exp. If RequiredClaims holds an empty string, Validate refuses every token with ErrInvalidOptions.

Encrypting and decrypting

The jwe package encrypts and decrypts the JWE Compact Serialization of RFC 7516. It does not implement the JWE JSON Serialization.

Algorithms

alg Key for GetEncrypter Key for GetDecrypter
RSA-OAEP, RSA-OAEP-256, RSA-OAEP-384, RSA-OAEP-512 *rsa.PublicKey *rsa.PrivateKey, or a crypto.Decrypter with an *rsa.PublicKey
ECDH-ES, ECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW *ecdsa.PublicKey on P-256, P-384 or P-521, or *ecdh.PublicKey on one of those curves or X25519 the matching *ecdsa.PrivateKey or *ecdh.PrivateKey
A128KW, A192KW, A256KW []byte of 16, 24 or 32 octets the same []byte
A128GCMKW, A192GCMKW, A256GCMKW []byte of 16, 24 or 32 octets the same []byte
PBES2-HS256+A128KW, PBES2-HS384+A192KW, PBES2-HS512+A256KW jwe.PasswordKey{Password: password, Count: count} a jwe.PasswordKey with the same Password
dir jwe.DirectKey{Key: secret, Enc: enc} the same jwe.DirectKey

An RSA key must have a modulus of 2048 to 8192 bits. RFC 7518 section 4.3 makes 2048 bits a MUST. RSA-OAEP-384 and RSA-OAEP-512 are not in RFC 7518. The IANA "JSON Web Signature and Encryption Algorithms" registry defines them, with SHA-384 and SHA-512 for both OAEP and MGF1.

A dir key is bound to one enc, as RFC 8725 section 3.1 requires of every key. Key must be the length that Enc requires. Encrypt refuses any other enc, and Decrypt cannot decrypt a token with any other enc. Without this binding, a 32-octet key could decrypt both A128CBC-HS256 and A256GCM tokens, and the token would choose.

CAUTION: Do not encrypt more than 2^32 tokens under one dir key with an AES GCM enc, or under one A128GCMKW, A192GCMKW or A256GCMKW key. RFC 7518 section 8.4 makes this limit a MUST. With these keys, every token uses the shared key and a random IV, and this library does not count the tokens. The other algorithms make a new key for each token.

The enc values are A128CBC-HS256, A192CBC-HS384, A256CBC-HS512, A128GCM, A192GCM and A256GCM, from RFC 7518 section 5. In Go they are jwa.A128CBCHS256 to jwa.A256GCM, of type jwa.Encryption.

To build an encrypter or decrypter from a JWK, call jwe.GetEncrypterFromJwk or jwe.GetDecrypterFromJwk. For the RSA-OAEP algorithms, give an RSA JWK: the public key for an encrypter, and the private key for a decrypter. For the ECDH-ES algorithms, give an EC JWK on P-256, P-384 or P-521, or an OKP JWK on X25519. For A128KW to A256KW and A128GCMKW to A256GCMKW, give an oct JWK whose k is 16, 24 or 32 octets. A JWK does not hold a password, so both functions refuse the PBES2 algorithms with ErrUnsupportedAlgorithm. For PBES2, build a jwe.PasswordKey.

These functions enforce what the JWK declares about itself:

  • If alg is present, it must name the algorithm that you give.
  • If use is present, it must be enc.
  • If key_ops is present, it must include wrapKey for an encrypter and unwrapKey for a decrypter, and it must not list a value twice. For an ECDH-ES decrypter, it must include deriveKey or deriveBits instead. An ECDH-ES encrypter has no required value, because no key_ops value names a public key that is used for key agreement. But if its key_ops includes sign or verify, it must also include deriveKey or deriveBits. Otherwise the values mark a signing key.
  • If use is present, key_ops must not include sign or verify, as RFC 7517 section 4.3 requires the two to agree.

Both functions take a *model.JWEOptions as the last argument, and it can be nil. If StrictKeyOperations is set, they also refuse a JWK that RFC 7517 section 4.3 discourages. See Keys that section 4.3 discourages.

A JWK's kid must be a string (RFC 7517 section 4.5). A refused JWK gives ErrInvalidPublicKey from GetEncrypterFromJwk and ErrInvalidPrivateKey from GetDecrypterFromJwk. A JWK cannot hold a dir key, because no JWK member names the enc that the key is bound to. For dir, build a jwe.DirectKey.

CAUTION: Do not log or publish what Public() returns for an A128KW to A256KW, A128GCMKW to A256GCMKW, PBES2 or dir encrypter or decrypter. A shared key or password has no public half, so Public() returns the secret itself, as it does for an HMAC signer. Printing or logging that value does not show the secret, but Errors and HTTP responses lists the routes that still can.

With ECDH-ES, the key that the two parties agree is the content encryption key, and the encrypted key is empty. With ECDH-ES+A128KW to ECDH-ES+A256KW, the agreed key wraps a random content encryption key. Encrypt makes a new ephemeral key for each token, as RFC 7518 section 4.6 requires, and writes its public half to the epk header. Do not set epk yourself: Encrypt refuses it with ErrMalformedClaim.

To bind the agreed key to the two parties, set apu and apv in the header that you give Encrypt. Each is a base64url string, and RFC 7518 section 4.6.2 requires them to be different. They enter the key derivation, so the recipient must receive the same values. Decrypt refuses an ECDH-ES token whose apu and apv are equal or are not base64url strings, as malformed. No other alg reads apu or apv, so Decrypt ignores them in a token of any other alg.

Decrypt refuses an ECDH-ES token with ErrMalformedToken if its epk is absent, has a point that is not on its curve, or carries a private member such as d. RFC 8725 section 3.4 requires this check. It also refuses an epk that cannot agree a key: one whose kty is not EC or OKP, or an OKP key whose crv is not X25519 or X448. An epk on a curve that this library does not implement, such as X448 or secp256k1, is refused with ErrUnsupportedAlgorithm. An epk on a different curve from the decrypter's key fails with ErrDecryptionFailed, like any other key that cannot decrypt the token.

AES GCM key wrap

A128GCMKW, A192GCMKW and A256GCMKW encrypt a random content encryption key with AES GCM under a shared key (RFC 7518 section 4.7). Encrypt writes the IV and the authentication tag of that encryption to the iv and tag headers. Do not set iv or tag yourself: Encrypt refuses them with ErrMalformedClaim. Decrypt refuses a token whose iv is not 12 octets or whose tag is not 16 octets, as malformed. The encrypted key is as long as the key of the enc.

Passwords (PBES2)

The PBES2 algorithms derive a key from a password with PBKDF2, and wrap the content encryption key under it with AES Key Wrap (RFC 7518 section 4.8). A text password must be its UTF-8 encoding, as section 4.8 requires. An empty password is refused.

encrypter, err := jwe.GetEncrypter(jwa.PBES2HS256A128KW, jwe.PasswordKey{Password: []byte(password)})
decrypter, err := jwe.GetDecrypter(jwa.PBES2HS256A128KW, jwe.PasswordKey{Password: []byte(password)})

Count is the number of PBKDF2 iterations, which Encrypt writes to the p2c header. If Count is 0, it is 600,000. draft-ietf-oauth-rfc8725bis section 3.13 cites this figure from OWASP for HMAC SHA-256. A negative Count is refused, because section 4.8.1.2 requires a positive p2c. A decrypter ignores Count, because each token names its own p2c. Encrypt writes a random 16-octet salt to the p2s header for each token. Do not set p2s or p2c yourself: Encrypt refuses them with ErrMalformedClaim.

CAUTION: Do not set a Count below 1000. RFC 7518 section 4.8.1.2 recommends at least 1000, and a lower count makes the password cheap to guess from any captured token. Encrypt accepts a lower count, because the section does not require the minimum. A recipient that sets RequireRecommendedPBES2Count refuses such a token.

The sender chooses p2c, and each PBES2 decrypter that Decrypt tries runs that many iterations. So JWEOptions.MaxPBES2Count limits the iterations of one call to Decrypt. A p2c that is more than MaxPBES2Count is refused with ErrOutOfBounds, whatever the decrypters. Then the limit is p2c multiplied by the number of decrypters of the token's alg. If that is more than MaxPBES2Count, Decrypt refuses the token with ErrOutOfBounds. Both refusals come before any decrypter runs. The default is 1,200,000, which is twice the OWASP figure, as draft-ietf-oauth-rfc8725bis section 3.13 recommends. Thus one password decrypter accepts the default Count of 600,000, and so do two.

If you give Decrypt more passwords, or raise Count above 600,000, the recipient must raise MaxPBES2Count too. To keep the limit low, select the password with ParseHeader, for example by kid, and give Decrypt only that one.

Decrypt accepts a p2c below 1000 by default, because RFC 7518 section 4.8.1.2 only recommends the minimum. A low count makes the password cheap to guess from a token, but the token has already been sent, so a refusal cannot undo this. Set JWEOptions.RequireRecommendedPBES2Count to refuse such a token with ErrOutOfBounds. Then the producer must raise its count. With it set, and a PBES2 alg permitted, MaxPBES2Count must be at least 1000. It must also let each decrypter of a permitted PBES2 alg run 1000 iterations: at least 1000 times the number of those decrypters. Otherwise no PBES2 token can pass, and every call fails with ErrInvalidOptions.

Decrypt refuses, as malformed, a p2s of fewer than 8 octets (a MUST in section 4.8.1.1) and a p2c that is not a positive integer.

Compression

Encrypt refuses a zip header, because draft-ietf-oauth-rfc8725bis section 3.6 says that compression SHOULD NOT be used when a JWE is made.

Decrypt refuses a token with a zip header by default, with ErrUnsupportedAlgorithm. To decrypt such a token, set JWEOptions.MaxDecompressedSize to the largest plaintext that you accept, in octets. draft-ietf-oauth-rfc8725bis section 3.15 recommends a limit, and gives 250 KB as an example. Decrypt then inflates a DEF plaintext (RFC 1951) after the token is authenticated:

  • A plaintext that inflates to more than MaxDecompressedSize octets is refused with ErrOutOfBounds. Decrypt stops when it reaches the limit, so a small token cannot make it allocate more.
  • A plaintext that is not a DEFLATE stream is refused with ErrMalformedToken, and so is one that continues after the final block of its stream.
  • A zip other than DEF is refused with ErrUnsupportedAlgorithm, and a zip that is not a string with ErrMalformedToken.

RSA1_5

This library does not implement RSA1_5, and it will not. RFC 8725 section 3.2 advises against it because of padding oracle attacks.

Encrypt

encrypter, err := jwe.GetEncrypter(jwa.RSAOAEP256, recipientPublicKey)
token, err := jwe.Encrypt(encrypter, jwa.A256GCM, plaintext, map[string]any{"kid": "recipient-key-1"})

Encrypt sets alg and enc in the header. If your header has an alg or enc that is different, Encrypt refuses it with ErrUnsupportedAlgorithm. Encrypt also refuses a zip header. See Compression.

Each call makes a new random content encryption key and a new random initialization vector.

Decrypt

decrypter, err := jwe.GetDecrypter(jwa.RSAOAEP256, recipientPrivateKey)
head, plaintext, used, err := jwe.Decrypt(ctx, token, []model.Decrypter{decrypter}, opts)

Decrypt tries each decrypter whose Alg is the token's alg. It returns the plaintext from the first decrypter that decrypts the token, and that decrypter as used. An empty plaintext is an empty slice, not nil.

If a decrypter returns an error, or a key of the wrong length, Decrypt uses a random key in its place. The decryption then fails at the authentication tag, as a changed token does. RFC 7516 section 11.5 describes this defence. Thus a wrong key, a changed token and a failed decrypter all give the same ErrDecryptionFailed with the same message, and the error does not tell an attacker which step failed.

One other ErrDecryptionFailed message exists: if no decrypter has the token's alg, the message says so. This message, and the time that Decrypt takes, show which alg values you hold keys for. They show nothing about a key or the plaintext.

Decrypt does not compare the kid header with the decrypter that succeeded. With a shared key or password (A128KW to A256KW, A128GCMKW to A256GCMKW, PBES2 or dir), the key identifies the sender. A sender who holds one of your keys can put the kid of a different key in the header. To identify the sender, compare used with the decrypters that you gave. Do not use kid for this. Every decrypter from GetDecrypter is a pointer, so == is safe. If you write your own model.Decrypter, make it a pointer or another comparable type. Comparing two interface values that hold a struct with a slice or map field panics.

head, plaintext, used, err := jwe.Decrypt(ctx, token, []model.Decrypter{tenantA, tenantB}, opts)
if err == nil && used != tenantA {
	// the token was not encrypted with tenant A's key
}

To read the header before you decrypt, use jwe.ParseHeader. It makes the same checks of the token's shape and header as Decrypt, with the same errors. Use it to select a decrypter by kid, or to log a token that Decrypt refused:

head, err := jwe.ParseHeader(token, opts)
kid, _ := head["kid"].(string)
decrypter, known := decryptersByKid[kid]

CAUTION: The header is not authenticated until Decrypt succeeds. Anyone can write any kid. Use it only to select a decrypter, and identify the sender with used.

A header can name a key with jku, jwk, x5u or x5c. In a JWE, that key is the public key of the recipient, and a public key cannot decrypt. Thus Decrypt does not fetch these keys or use them. It checks only their form: for example, a jwk that holds a private key member is refused. Only the decrypters that you give are used.

Decrypt takes a *model.JWEOptions. Its fields:

  • AllowedKeyManagementAlgorithms and AllowedContentEncryptionAlgorithms limit the alg and enc values that a token can name. If a list is empty, all values that this library implements are permitted. A list that names a value this library does not implement, such as a JWS alg, is a configuration fault. Decrypt refuses every call with ErrInvalidOptions until you correct it.
  • MaxKeysTried limits the number of decrypters of each alg. The default is 100. If you give more, every call fails with ErrInvalidOptions, whatever the token. With many keys, select one with ParseHeader and give Decrypt only that one.
  • OnDecrypterError receives each decrypter that fails, and its error. Use it to see a fault such as a hardware module outage, which Decrypt otherwise reports as the same ErrDecryptionFailed as a bad token. What it receives can depend on the token, so log it, and do not send it to the sender.
  • MaxPBES2Count and RequireRecommendedPBES2Count limit the p2c of a PBES2 token. See Passwords (PBES2).
  • MaxDecompressedSize turns on zip and limits the size of the inflated plaintext. See Compression.
  • AllowUnauthenticatedJWT applies only in jwt.Validate. See Encrypted JWTs.
  • AcceptedTypes, RequireKeyIdentifier and UnderstoodCriticalHeaders work as the JoseOptions fields of the same name do for a JWS. The exception is b64: RFC 7797 defines it for JWS only, so a JWE crit that names b64 is refused.
  • StrictKeyOperations applies to GetEncrypterFromJwk and GetDecrypterFromJwk.

The encrypted key of an A128KW to A256KW, ECDH-ES+A128KW to ECDH-ES+A256KW or PBES2 token must be 8 octets longer than the key of its enc. That of an A128GCMKW to A256GCMKW token must be as long as the key of its enc, and that of a dir or ECDH-ES token must be empty. The encrypted key of an RSA-OAEP token is as long as the recipient's modulus, so it must be 256 to 1024 octets. Decrypt refuses any other length with ErrMalformedToken, before any decrypter is tried. Thus a token cannot make each decrypter process a large encrypted key.

Decrypt has no limit on the size of a token. Each decrypter of the token's alg decrypts the full ciphertext. Limit the size of the request body before you call Decrypt.

Decrypt refuses a token with a zip header unless MaxDecompressedSize is set. See Compression. A crit header must not name a parameter that RFC 7516 or RFC 7518 defines for JWE, such as enc or epk.

Keys held outside the process

A model.Decrypter is a crypto.Decrypter. Thus you can give GetDecrypter an RSA key that is held in a hardware module, if its crypto.Decrypter accepts *rsa.OAEPOptions. GetDecrypter cannot test this. If the module refuses the options, every token fails with ErrDecryptionFailed, and OnDecrypterError receives the module's error.

A crypto.Decrypter takes no context, so ctx cannot stop a call that is already running in the module. Decrypt checks ctx before each decrypter and after the last. To limit the time of a module call, build the decrypter for each request around a crypto.Decrypter that holds the request's context.

Encrypted JWTs

To send a signed JWT that only the recipient can read, sign it with jwt.New and then encrypt it with jwt.Encrypt. jwt.Encrypt sets cty to JWT, as RFC 7519 section 5.2 requires of a Nested JWT:

signed, err := jwt.New(signer, nil, claims, jwt.Opts{})
token, err := jwt.Encrypt(encrypter, jwa.A256GCM, *signed, nil)

jwt.Encrypt refuses a signed that Validate would refuse for its shape, whatever the options, with ErrMalformedToken. That is a signed that is not three base64url segments, whose header is not a JSON object that passes the header checks Validate makes whatever the options, or whose payload is not a JSON object. A header with no alg also matches ErrMissingClaim, and one whose alg is not a string also matches ErrMalformedClaim. A JWE passed as signed is a JWT encrypted inside a JWE, which this library does not implement, so it is refused with ErrUnsupportedAlgorithm. A header whose cty names JWT signs a JWT, not a claims set, so it is refused with ErrUnsupportedAlgorithm. jwt.Encrypt does not verify the signature. It refuses a cty in the header that does not name JWT, with ErrMalformedClaim. Otherwise its errors are those of jwe.Encrypt.

To read the token, give jwt.Validate your decrypters:

validated, err := jwt.Validate(ctx, token, retriever, decrypters, opts, jweOpts)

Validate decrypts a token of five segments with jwe.Decrypt, and returns its errors. With no decrypters, it refuses the token with ErrUnsupportedAlgorithm. A token of five segments whose protected header is not a JSON object with an enc member is not a JWE (RFC 7516 section 9), so it is refused with ErrMalformedToken. With no decrypters, a JWE that breaks RFC 7516, such as one with no alg or a segment that is not base64url, is refused for that fault first, as jwe.Decrypt would refuse it. The same rule applies to the plaintext of a Nested JWT. The JWE's cty decides what the plaintext is (RFC 7519 section 7.2 step 8). Validate reads it from the protected header before it decrypts, so it can refuse an unauthenticated JWT without running any decrypter. The header is authenticated by the decryption that follows. So a token whose cty was changed in transit is refused either way, though the error names the shape, not ErrDecryptionFailed:

  • If cty names JWT, the plaintext is a Nested JWT. It must be a signed JWT, which Validate verifies with the retriever and opts. A JWE inside the JWE is refused with ErrUnsupportedAlgorithm, as this library does not implement that nesting. Any other plaintext that is not a JWS is refused with ErrMalformedToken.
  • Otherwise the plaintext is the claims set. RFC 7519 allows a JWT that is only encrypted. The plaintext must be a JSON object, else ErrMalformedToken.

CAUTION: Anyone who has your public key can make a JWT that is only encrypted with RSA-OAEP or ECDH-ES. Its claims prove nothing about who wrote them. If you expect signed JWTs, an attacker can also send unsigned claims in a JWE, and the signature check would not run. So Validate refuses such a token with ErrInvalidSignature, before any decrypter runs. It refuses an encrypt-only JWT under every alg except the shared-key and password algorithms below, so an alg added later is refused too. To accept such a token, set AllowUnauthenticatedJWT in jweOpts. The flag applies to every public-key decrypter in the call. So if you accept such tokens from one partner, give that partner its own key and its own call to Validate.

A JWT that is only encrypted with dir, A128KW to A256KW, A128GCMKW to A256GCMKW or PBES2 is accepted, because only a holder of the shared key or password can make it. Token.Decrypter identifies that sender. With RSA-OAEP or ECDH-ES, Token.Decrypter names only your key that decrypted the token, not the sender. The signature of a Nested JWT identifies its issuer.

The claim rules of opts apply to the claims in every case. The header rules of jweOpts apply to the JWE header. For a JWT that is only encrypted, the JWE header is the JWT's own header (RFC 7519 section 5.1), so AcceptedTypes in opts also judges its typ, before any decrypter runs. A JWT that you type explicitly (RFC 8725 section 3.11) is then checked in every shape. For a Nested JWT, opts.AcceptedTypes judges the typ of the inner JWS, and the JWE needs no typ.

To make a JWT that is only encrypted, encrypt the claims set as JSON with jwe.Encrypt, and do not set cty:

plaintext, err := json.Marshal(claims)
token, err := jwe.Encrypt(encrypter, jwa.A256GCM, plaintext, nil)

Not implemented

RFC 7519 allows these, and this library does not implement them. Each is refused with ErrUnsupportedAlgorithm, not ErrMalformedToken:

  • A JWT signed inside another JWS (#174).
  • A JWT encrypted inside another JWE (#175).
  • A JWE signed inside a JWS, that is, encrypted and then signed (#176). The outer JWS names cty JWT, so it is refused as a JWT signed inside a JWS. To nest, sign first and then encrypt, with jwt.Encrypt.

HPKE key management for JWE is planned once draft-ietf-jose-hpke-encrypt is published as an RFC (#166). The JSON Serialization of JWS and JWE is not implemented.

Errors

Sentinel errors live in the joseerror package. Match one with errors.Is:

Sentinel Meaning
ErrInvalidPublicKey The public key given cannot be used for this algorithm
ErrInvalidPrivateKey The private key or secret given cannot be used for this algorithm
ErrInvalidSignature The signature does not verify against the signing input
ErrDecryptionFailed A JWE did not decrypt. The error is the same for a wrong key, a changed token and a decrypter that failed, as RFC 7516 section 11.5 requires. It also covers a call with no decrypter for the token's alg
ErrUnsupportedAlgorithm The algorithm named is not supported, has no validator in this library, or is not permitted by the options given. It also covers a feature that RFC 7519 allows and this library does not implement, such as a JWT signed inside a JWS or encrypted inside a JWE
ErrSigningError Signing failed
ErrEncryptionError Encryption failed. The random source failed, or a custom Encrypter returned a key or header that jwe.Encrypt cannot use, such as an encrypted key of a length that jwe.Decrypt refuses
ErrMalformedClaim A claim is present but its type or value is wrong. This includes a b64 that is not a boolean, and an x5c or x5u chain that is out of order or longer than 16 certificates. An x5u body that holds no PEM certificate block, or a block that is not a certificate, matches it as well as ErrApplicationError
ErrMissingClaim A required claim is absent. This includes a claim named in JoseOptions.RequiredClaims, an aud when ExpectedAudience is set, and an iss when ExpectedIssuer is set
ErrMissingCriticalClaim A header named in crit is absent, or names an extension this library does not understand, or b64 is false
ErrNoKeyIdentifierMatch No key could be selected. The kid matches nothing, your KeySet or a jku set holds no usable key that matches the header, a certificate chain does not reach a configured root, an x5t thumbprint does not match the chain, or a jku or x5u is not in AllowedKeyURLs. It also covers a token that names no key, when you give no retriever and rely on the keys a token names
ErrKeystoreError A model.Jwks lookup or addition failed, or a document decoded into model.Jwks is not a JWK Set
ErrApplicationError Key material a header named could not be obtained, decoded or used. Covers a failed jku or x5u fetch, including a redirect hop that is not https or not in AllowedKeyURLs, a local decode of what one returned (an empty x5u body is a failed decode), and an inline jwk that this library cannot read, such as one whose kty it does not support or whose crv is missing. An inline jwk on a curve the alg does not name is not selected, so it gives ErrNoKeyIdentifierMatch instead. A fetch that ran out of time also matches context.DeadlineExceeded, and one cancelled through ctx matches context.Canceled
ErrMalformedToken The token is not a well formed JOSE object: it breaks RFC 7515 or RFC 7516. A well-formed token that your options refuse, or that names what this library does not implement, does not match it
ErrExpired The current time is not before the token's exp, allowing for ClockSkewLeeway
ErrNotYetValid The token's nbf or iat is after the current time, allowing for ClockSkewLeeway
ErrAudienceMismatch JoseOptions.ExpectedAudience is set and the token's aud names none of its values
ErrIssuerMismatch JoseOptions.ExpectedIssuer is set and the token's iss equals none of its values
ErrInvalidOptions The options passed are themselves wrong. Most of these cases are refused before the token is read. jws.Verify and jws.VerifyCompactSerialization refuse a verifier with no retriever and no token key allowed after the header is checked, so a token with a bad header reports that fault first. jwt.Validate refuses it before it reads the token. The cases are: a nil ctx; a JoseOptions.ExpectedAudience, ExpectedIssuer or RequiredClaims that holds an empty string; a JWE allow-list that names a value this library does not implement; an AllowedSigningAlgorithms entry that is not a signature algorithm this library implements; an AcceptedTypes entry that is not a media type name; an AllowedKeyURLs entry that is not an https URL with a host, or that holds a character no URI holds; a nil decrypter, or more decrypters of one alg than JWEOptions.MaxKeysTried allows; a MaxPBES2Count too low for RequireRecommendedPBES2Count to be met; in jws.Verify, a nil retriever with none of KeySet, UseTokenProvidedKeys and X509Roots set; and, in jwt.Validate, RequireEncryptedJWT with no permitted decrypter, or no source of signing keys when no JWT that is only encrypted can pass. See JWTs for the exact rule
ErrTooManyKeys The signature did not verify under as many keys as JoseOptions.MaxKeysTried allows, and more keys or key sources remained.
ErrOutOfBounds A JWE asks for more work than your options allow: a p2c above JWEOptions.MaxPBES2Count, or a plaintext that inflates to more than MaxDecompressedSize. It also covers a p2c below 1000 when RequireRecommendedPBES2Count is set

An error can match more than one sentinel. A header that breaks the specification matches ErrMalformedToken and also the sentinel for the fault, such as ErrMalformedClaim for a kid that is not a string. A header that is well formed but refused matches only the sentinel for the reason:

  • your options refuse it: an alg or enc outside an allow-list, a typ outside AcceptedTypes, no kid when RequireKeyIdentifier is set, or a p2c outside your bounds;
  • it names what this library does not implement: a JWT signed inside a JWS or encrypted inside a JWE, an unknown alg or enc, a zip other than DEF or any zip when MaxDecompressedSize is unset, a crit extension that you have not named in UnderstoodCriticalHeaders, or a b64 of false.

If a header has both kinds of fault, the error reports the fault in the specification.

Errors and HTTP responses

Most errors mean that the token is bad, so the response is a 4xx. A few mean that your server or its configuration has a fault, so the response is a 5xx. Test the errors in this order, because an error can match more than one:

  1. Your request's own context has ended: test ctx.Err() != nil on the ctx that you passed. Send 499 for a client that went away, or 504 for your deadline. Test the context itself, not the error. A jku or x5u fetch that runs out of time also matches context.DeadlineExceeded, and that fault is the peer's, not yours.
  2. ErrInvalidOptions. Your options are wrong, and no token can pass. This is a server fault (500).
  3. The errors of your own retriever. Validate wraps them and adds no sentinel, so test them with errors.Is(err, yourErr). A failed key store is a server fault (500 or 503).
  4. Every other sentinel. The token was refused (401, or 400 for ErrMalformedToken if you separate malformed requests). This includes ErrMissingClaim, ErrAudienceMismatch and ErrIssuerMismatch: your options name what you require, and the token does not meet it.

Four sentinels can also come from your side. Read these before you map them:

  • ErrTooManyKeys means that the signature did not verify under as many keys as JoseOptions.MaxKeysTried allows. This applies to a signed JWT and to the JWS inside a Nested JWT. The keys can come from your retriever, your KeySet or a jku set the peer chose. So set MaxKeysTried above the number of keys that your own retriever returns plus the most members of your KeySet that one token can select. Only a member whose kid, alg and key type match the token is selected. A token with no kid selects every member its alg can use, and a member with no kid is selected for every token. RequireKeyIdentifier refuses a token with no kid, but a member with no kid still matches every kid. Then the error can only come from a token that names too many keys, which is the peer's fault (401). More decrypters of one alg than JWEOptions.MaxKeysTried allows is ErrInvalidOptions, not ErrTooManyKeys.
  • ErrOutOfBounds for a PBES2 token means that p2c, multiplied by the number of your decrypters of the token's alg, is more than MaxPBES2Count. A peer can cause it with a high p2c, which is a 4xx. You can cause it with too many PBES2 decrypters: three decrypters at the default MaxPBES2Count refuse a token at the common p2c of 600,000. So give at most MaxPBES2Count divided by your senders' p2c PBES2 decrypters. Then the error can only come from a token with a higher p2c, which is the peer's fault. A zip that inflates past MaxDecompressedSize is also ErrOutOfBounds, and is the peer's fault.
  • ErrDecryptionFailed is the same for every failure that depends on a key, as RFC 7516 section 11.5 requires. So a hardware module outage looks like a bad token. To tell them apart, record the cause with OnDecrypterError, and decide after the call. A wrong key or a forged token also calls OnDecrypterError, so test for the errors of your own key store only, as here:
var outage error
jweOpts := &model.JWEOptions{OnDecrypterError: func(_ model.Decrypter, err error) {
	if errors.Is(err, errHSMUnavailable) {
		outage = err
	}
}}
validated, err := jwt.Validate(ctx, token, retriever, decrypters, opts, jweOpts)
if err != nil && outage != nil {
	return http.StatusServiceUnavailable
}

Build jweOpts for each request, as above, because the hook writes to a variable of that request. Do not send the cause to the sender.

  • ErrApplicationError means that a key the token names, through jku or x5u, could not be fetched or read. The peer chose that address, so it is the peer's fault (401). A fetch that ran out of time also matches context.DeadlineExceeded, which is why step 1 tests your request's context and not the error.

CAUTION: Do not send an error message to the sender of a token. A message can hold parser detail, Go type names, your configuration and text from the token. Send a fixed message, and log the error on your side.

Printing or logging a signer, validator, encrypter or decrypter never shows its key. fmt, log, the text handler of log/slog and html/template show its algorithm and role, such as HS256 signer, for every verb fmt accepts, %#v included. The JSON handler of log/slog, and html/template inside a script, show {}. fmt prints a value without its methods for a verb it does not accept, such as %w, and for a value in an unexported struct field. Each of these types holds its key behind a pointer, so fmt then prints an address and not the key. encoding/json, encoding/xml and encoding/gob encode none of these types' key material.

A tool that prints a value by reflection, and does not call its methods, follows the pointer and prints the key. So does code that reads the value with reflect, including what Public() returns. The failure output of assert.Equal in github.com/stretchr/testify is one such tool. In a test, do not compare two signers, validators, encrypters or decrypters as whole values. Compare what the test needs, such as Alg().

Three values are the key itself: what Public() returns for a secret key, a jwe.DirectKey and a jwe.PasswordKey.

  • What Public() returns for an HMAC signer or validator, or for an A128KW to A256KW or A128GCMKW to A256GCMKW encrypter or decrypter, prints as secret key and logs as secret key. encoding/json, encoding/xml and encoding/gob refuse to encode it, so encoding a value that holds it fails as a whole. Nested in another value, the JSON handler of log/slog logs that refusal in its place. It holds the secret behind two pointers, so a verb fmt does not accept, or an unexported struct field that holds it, prints an address.
  • A jwe.DirectKey prints and logs as the enc it is bound to, and a jwe.PasswordKey as its type name. Their Key and Password fields are exported, so encoding/json, encoding/xml and encoding/gob encode them, and a verb fmt does not accept, or an unexported struct field that holds one, prints them. The same holds where those encoders run for you: the JSON handler of log/slog encodes one nested in another value, and html/template encodes one inside a script.

Each sentinel carries a prefix terminated by ": ", so wrap one with %w immediately followed by the rest of the message and no space:

fmt.Errorf("%wshould be an instance of *ecdsa.PrivateKey", joseerror.ErrInvalidPrivateKey)

That reads invalid private key: should be an instance of *ecdsa.PrivateKey, and errors.Is still matches.

When an error echoes a value from the token, the value is quoted with Go escaping and cut to its first 64 characters, with ... marking the cut. A peer cannot put a raw line break or kilobytes of text into your logs this way. This applies to header checks and claim checks, such as an iss that ExpectedIssuer refuses. It also applies to the error from the JSON decoder for a header, a claims set or a jku key set, to the error from parsing an x5c or x5u certificate, and to the URL in a failed jku or x5u fetch, redirect hops included. The cause of a failed fetch, such as a DNS error naming the host, is also quoted with Go escaping, and is cut to its first 256 characters.

Upgrading from 0.11.x to 0.12.0

v0.12.0 changes three signatures, one key type and several errors. The changes are listed against v0.11.0.

Changes that break your build

Three changes can break your build:

  • model.Mode, model.JWS and model.JWE are removed. Nothing in the public API took them, so delete any use.
  • jws.GetValidatorFromJwk takes a *model.JoseOptions as a third argument. Pass nil to keep the v0.11.0 behaviour.
  • jwt.Validate takes decrypters and a *model.JWEOptions for the JWE layer, and returns a *jwt.Token. For a signed JWT, pass nil for both, and read Token.SignatureHeader and Token.Claims where you read head and body:
validated, err := jwt.Validate(ctx, token, retriever, nil, opts, nil)
if err != nil {
	return err
}
head, body := validated.SignatureHeader, validated.Claims

A change that breaks your program at run time

This change compiles and passes go vet. jwk.PublicFromJwk and jwk.PrivateFromJwk return an Ed25519 key as an ed25519.PublicKey or ed25519.PrivateKey value. v0.11.0 returned an *ed25519.PublicKey or *ed25519.PrivateKey. The standard library uses the value type: x509.ParsePKIXPublicKey, x509.ParsePKCS8PrivateKey and ed25519.GenerateKey return it, and so does the Public method of this library's Ed25519 signer. The value is a byte slice, so code written for the pointer fails in four ways:

  • A type assertion to the pointer type panics, or its ok is false. Change key.(*ed25519.PublicKey) to key.(ed25519.PublicKey), and key.(*ed25519.PrivateKey) to key.(ed25519.PrivateKey).
  • A case *ed25519.PublicKey: in a type switch no longer matches, so the switch silently takes its default. Change the case to ed25519.PublicKey, and do the same for a private key.
  • == on two such keys panics with comparing uncomparable type ed25519.PublicKey. Compare them with the Equal method that ed25519.PublicKey and ed25519.PrivateKey have.
  • A key used as a map key panics with hash of unhashable type ed25519.PublicKey. Key the map by the jwk's thumbprint from jwk.Thumbprint, or by string(key).

To find the affected code, search it for *ed25519.. Also check each == and each map key whose type is crypto.PublicKey, crypto.PrivateKey or any. Every function that accepts an Ed25519 key still accepts both forms.

Changes to the errors you match

These refusals still happen, but the errors match different sentinels. If you test for the old sentinel with errors.Is or errors.As, test for the new one. If you map errors to HTTP responses as Errors and HTTP responses describes, some responses change too. A missing key source and an option value that no token can meet are now ErrInvalidOptions, a 500. v0.11.0 gave a 400 or a 401. If you send 400 for ErrMalformedToken, an alg outside AllowedSigningAlgorithms and a JWS whose cty is JWT now get a 401, because they no longer match ErrMalformedToken.

A well-formed token that your options refuse, or that names what this library does not implement, no longer matches ErrMalformedToken. It matches only the sentinel for the reason, such as ErrUnsupportedAlgorithm for an alg outside AllowedSigningAlgorithms. If you test errors.Is(err, joseerror.ErrMalformedToken) to catch these refusals, test the specific sentinel instead. See Errors.

A verifier given no retriever, and none of KeySet, UseTokenProvidedKeys and X509Roots, refuses every token with ErrInvalidOptions. v0.11.0 refused it with ErrMalformedToken, which blamed the token for a configuration fault. If token keys are allowed and the token names none, the error is ErrNoKeyIdentifierMatch. If you test for ErrMalformedToken in this case, test for these instead. If you give jwt.Validate decrypters and an encrypt-only JWT can pass, the options are not wrong: a signed JWT that no key verifies is refused with ErrInvalidSignature. An encrypt-only JWT can pass when RequireSignedJWT is off and a decrypter is for dir, an AES key wrap or PBES2, or AllowUnauthenticatedJWT is set. jwt.Validate now makes this check before it reads the token, so a malformed token under such options also gets ErrInvalidOptions.

jwt.Validate refuses a token of five segments whose protected header is not a JSON object with an enc member with ErrMalformedToken. RFC 7516 section 9 says such a token is not a JWE. v0.11.0 refused every token of five segments with ErrUnsupportedAlgorithm. A JWE with no decrypters to decrypt it is still refused with ErrUnsupportedAlgorithm.

Two option values that no token could meet now fail every call with ErrInvalidOptions. One is an AllowedSigningAlgorithms entry that is not a signature algorithm this library implements. v0.11.0 refused every token with ErrUnsupportedAlgorithm and ErrMalformedToken instead. The other is an AcceptedTypes entry that is not a media type name, such as one with stray whitespace. v0.11.0 refused every token with ErrMalformedClaim or ErrMissingClaim, and ErrMalformedToken. Correct the entry. Valid options are not affected.

jws.VerifyCompactSerialization and jwt.Validate refuse a JWS whose cty is JWT, that is a JWT signed inside another JWS, with ErrUnsupportedAlgorithm alone. v0.11.0 refused it with ErrMalformedToken. RFC 7519 allows this nesting, so the token is not malformed, and this library does not implement it. jws.Verify does not read the payload as a JWT, so it accepts such a token, as v0.11.0 did. For the same reason, jwt.Validate refuses a JWE inside a JWE with ErrUnsupportedAlgorithm.

jwk.PublicFromJwk refuses an oct jwk with ErrInvalidPublicKey, because a symmetric key has no public half. v0.11.0 refused it with ErrUnsupportedAlgorithm. If you match the old sentinel for this case, match the new one.

jws.GetValidatorFromJwk refuses an X25519 jwk with ErrInvalidPublicKey, where v0.11.0 gave ErrUnsupportedAlgorithm.

Errors from jwk.PublicFromJwk and jwk.PrivateFromJwk now match more sentinels. For the key types v0.11.0 read, EC, RSA and Ed25519, no sentinel it matched is lost, so you need to change nothing. Every refusal by PublicFromJwk matches ErrInvalidPublicKey, and every refusal by PrivateFromJwk matches ErrInvalidPrivateKey, unless it is ErrUnsupportedAlgorithm. v0.11.0 left the class out for some members, such as an EC x or an RSA p. When PrivateFromJwk refuses a jwk that PublicFromJwk also refuses, the error now matches ErrInvalidPublicKey for every key type but oct. v0.11.0 did this only for an RSA n or e whose value was out of range. A kty, crv or AKP alg that is absent now also matches ErrMissingClaim, and one that is not a string now matches ErrMalformedClaim. An RSA private jwk that carries some of p, q, dp, dq and qi but not all of them now also matches ErrMissingClaim, and the error names the first one it lacks. v0.11.0 did not read an X25519 or oct jwk, so it refused every one with ErrUnsupportedAlgorithm. Both readers now read X25519, and PrivateFromJwk reads oct, so a fault in one of these jwks gives the class sentinel and no longer matches ErrUnsupportedAlgorithm. If you match ErrUnsupportedAlgorithm for these key types, match the class sentinel instead.

The error from a failed jku or x5u fetch no longer matches *url.Error through errors.As. v0.11.0 wrapped the *url.Error from net/http, and its text repeated the URL a peer chose, with no bound. The error now holds the bounded URL and the bounded cause. The cause still unwraps, so errors.As still finds it, such as a *net.DNSError. A fetch that ran out of time still matches context.DeadlineExceeded. If you match *url.Error, match the cause or joseerror.ErrApplicationError instead.

Other behaviour changes

jwk.PublicFromJwk and jwk.PrivateFromJwk now read an X25519 jwk as an *ecdh key. v0.11.0 refused it with ErrUnsupportedAlgorithm.

jwt.New refuses a header whose cty names JWT with ErrMalformedClaim, because it signs a claims set, not a JWT. v0.11.0 signed it. To nest a JWT, sign it with jwt.New and encrypt it with jwt.Encrypt.

A jwk whose key_ops lists a value twice is now refused by jws.GetValidatorFromJwk, and skipped in a jku set or a KeySet. RFC 7517 section 4.3 says this MUST NOT happen. If a key set that you rely on does it, have its publisher remove the repeated value.

A jwk whose use is "sig" and whose key_ops also names encrypt, decrypt, wrapKey, unwrapKey, deriveKey or deriveBits is now refused by jws.GetValidatorFromJwk, and skipped in a jku key set. RFC 7517 section 4.3 says use and key_ops MUST be consistent. v0.11.0 used such a key if its key_ops included verify. If a key set that you rely on does this, have its publisher drop one of the two members. A jwk whose use is "enc" was already refused and skipped, so only error messages change. The message for a skipped jku member always changes. The message from jws.GetValidatorFromJwk changes only when the jwk's key_ops names sign or verify.

With UseTokenProvidedKeys set, a token whose jwk header breaks RFC 7517 is now refused at once, with ErrMalformedToken and ErrMalformedClaim. Some of these tokens verified in v0.11.0, and now they do not:

  • A jwk whose use is "sig" and whose key_ops names verify and also encrypt, decrypt, wrapKey, unwrapKey, deriveKey or deriveBits. v0.11.0 verified the token with it.
  • A jwk whose key_ops lists a value twice, such as ["verify", "verify"]. v0.11.0 verified the token with it.
  • A jwk whose use is "enc" and whose key_ops names sign or verify. v0.11.0 passed over the key, and refused the token with ErrInvalidSignature and ErrNoKeyIdentifierMatch if no other key verified it.
  • A jwk whose kid, alg, use or key_ops has the wrong JSON type, such as a kid of 123. v0.11.0 refused the token with ErrMalformedClaim only.

If you issue such tokens, fix the jwk: drop the conflicting or repeated key_ops value, or drop use. If you cannot change the tokens, give Validate a retriever that holds the key. Your retriever is tried before the token's own jwk, so its key verifies the token first. jwt.New now refuses to sign such a header with ErrMalformedClaim.

jws.GetValidatorFromJwk now refuses a jwk whose kid is not a string with ErrInvalidPublicKey. RFC 7517 section 4.5 makes kid a string. v0.11.0 accepted it.

A jku or x5u that is an https URL with an empty host, such as https:///jwks or https://:443/, is now refused with ErrMalformedToken, even when you do not use that header. RFC 9110 section 4.2.2 says a recipient MUST reject such a URI. v0.11.0 accepted it, and no fetch of it could succeed. The same applies to a jku or x5u that holds a character outside RFC 3986 section 2, such as a trailing space, a raw non-ASCII letter or a malformed percent-encoding. v0.11.0 accepted some of these. Percent-encode such a character. jwt.New refuses both with ErrMalformedClaim.

AcceptedTypes and the cty check now ignore the case of ASCII letters only. v0.11.0 used Unicode case folding, so a typ with a lookalike letter, such as ſecevent+jwt with a long s, matched secevent+jwt. Media type names are ASCII (RFC 6838 section 4.2), so no valid typ or cty is affected, and you need to change nothing.

jws.Verify, jws.VerifyCompactSerialization and jwt.Validate now return the context's error once ctx has ended before a key verifies the token, even when no fetch runs. v0.11.0 could still verify a token after ctx was cancelled, if every key came from your retriever.

jwt.Validate decrypts a JWE when you give it decrypters. See Encrypted JWTs. With no decrypters, it still refuses a JWE with ErrUnsupportedAlgorithm.

A JWE alg cannot sign. jws.GetSigner, jws.GetSignerFromPrivateKey, jws.GetSignerFromJwk, jws.GetValidator, jws.GetValidatorFromJwk and jwt.New refuse one with ErrUnsupportedAlgorithm.

jwa.GetAlgorithm now resolves the JWE names, such as "RSA-OAEP" and "dir". If your code reads jwa.GetAlgorithm(name) != jwa.Unknown as "a signature algorithm", that test is no longer correct. Ask for a signer or validator instead: both refuse a JWE alg.

Printing a signer, validator, encrypter or decrypter now shows its algorithm and role, never its key. In v0.11.0, %v on an HMAC signer or validator printed its secret, and %v on an Ed25519 signer printed its private key. What Public() returns for an HMAC signer or validator now prints as secret key, and encoding/json, encoding/xml and encoding/gob refuse to encode it. v0.11.0 encoded it. Encoding a struct that holds it now fails as a whole. If you printed or encoded one of these to read its key, use jwk.PrivateJwk on a key you hold instead.

What Public() returns for an HMAC signer or validator is now bound to its algorithm, as RFC 8725 section 3.1 requires. jws.GetValidator refuses one made for another HMAC algorithm with ErrInvalidPublicKey. v0.11.0 accepted the Public() of an HS256 signer for an HS384 or HS512 validator when the secret was long enough. Build each validator from the signer of its own algorithm. A retriever is held to the same rule: an HS384 token checked against a retriever that returns only the Public() of an HS256 signer now fails with ErrInvalidSignature, where v0.11.0 verified it. Return the Public() of a signer of the token's algorithm. SecretKey.Equal now also compares the algorithm, so two keys of the same bytes made for different algorithms are not equal.

jwk.PrivateFromJwk and jwk.PrivateJwk refuse an RSA private key whose modulus is over 8192 bits with ErrInvalidPrivateKey, even when the key carries its primes. v0.11.0 refused such a key only when its primes were absent, and read or wrote one that carried them. No signer or decrypter of this library accepts a modulus over 8192 bits, so such a key had no use here.

A token whose jwk header holds a private key member, such as d, is refused with ErrMalformedToken and ErrMalformedClaim, whether or not UseTokenProvidedKeys is set, and even when your retriever's key verifies it. RFC 7515 section 4.1.3 makes the jwk header a public key, so such a header is malformed. v0.11.0 verified the token with your key. jwt.New refuses to sign such a header with ErrMalformedClaim, where v0.11.0 signed it. Remove the private members from the jwk header. See Keys a token carries.

model.Jwks.Add refuses a jwk whose kty is absent, or is not a non-empty string, with ErrKeystoreError. RFC 7517 section 4.1 says kty MUST be present. v0.11.0 added such a jwk. Decoding JSON into a model.Jwks still accepts such a member, and verification passes over it.

New in 0.12.0

These add to the API without changing what you already use:

  • The jwe package, with GetEncrypter, GetDecrypter, GetEncrypterFromJwk, GetDecrypterFromJwk, Encrypt, Decrypt, ParseHeader and DirectKey. See Encrypting and decrypting.
  • oct keys in the jwk package: PrivateFromJwk reads one as a []byte, and PrivateJwk writes one. PrivateJwk also writes what Public() returns for a secret key, with an alg that names the algorithm the key was made for. v0.11.0 refused it.
  • model.Encrypter, model.Decrypter and model.DecrypterOpts.
  • jwa.Encryption with jwa.GetEncryption, and the alg constants jwa.RSAOAEP to jwa.Dir and jwa.ECDHES to jwa.ECDHESA256KW. The integer values of the existing jwa.Algorithm constants do not change.
  • model.JWEOptions, the options of jwe.Decrypt, jwe.ParseHeader, jwe.GetEncrypterFromJwk, jwe.GetDecrypterFromJwk and the JWE layer of jwt.Validate.
  • JoseOptions fields: KeySet, StrictKeyOperations, RequireSignedJWT, RequireEncryptedJWT, RequiredClaims, ExpectedIssuer and AllowedKeyURLs. Each is off when unset. See Verifying with your own key set.
  • jws.GetSignerFromJwk, which builds a signer from a private jwk. See Signers.
  • jwt.Encrypt and jwt.Token, for encrypted JWTs. See Encrypted JWTs.
  • jwt.CheckOptions, jws.CheckOptions and jwe.CheckOptions, which refuse at startup the options that jwt.Validate, jws.Verify and jwe.Decrypt would refuse for every token.
  • jwe.PasswordKey for PBES2, and the alg constants jwa.A128GCMKW to jwa.A256GCMKW and jwa.PBES2HS256A128KW to jwa.PBES2HS512A256KW.
  • The error sentinels ErrEncryptionError, ErrOutOfBounds and ErrIssuerMismatch. ErrDecryptionFailed now has a use.

Upgrading from 0.10.x

Every change below is a compile error or a silent behaviour change for a consumer of v0.10.0. Additions that change nothing you already use are listed in New in 0.11.0. Apply Upgrading from 0.11.x to 0.12.0 as well.

Module and API

  • This module now requires Go 1.27. v0.10.0 declared Go 1.21, which Go no longer supports.
  • jwt.Validate and jws.VerifyCompactSerialization take a context.Context first. It bounds any jku or x5u fetch. A nil ctx is refused with ErrInvalidOptions.
  • Every jwa.Algorithm constant has a new integer value. Unknown is now 0, so a zero Algorithm names no algorithm. In v0.10.0 the zero value was ES256, so an unset jwt.Opts.Algorithm or configuration field meant ES256. v0.10.0's Unknown was 13, which is now EdDSA. If you store or send an Algorithm as an integer, store its String() and read it back with jwa.GetAlgorithm.
  • model.Jwks.RetrieveByKeyID returns []map[string]any, every key carrying the kid in set order, not one map[string]any. It returns an error only when no key carries the kid. To keep the old exactly-one meaning, check len(keys) == 1 and use keys[0].
  • model.Jwks.Add with EnforceUniqueKIDs refuses a kid the set already holds more than once. v0.10.0 added it.
  • json.Marshal of an empty model.Jwks writes {"keys":[]}. v0.10.0 wrote {"keys":null}.
  • Decoding JSON into model.Jwks refuses a document with no keys member, with "keys": null, or that is null, and reads keys only by its exact name. It also refuses an element of the keys array that is null, and a document that is not UTF-8 or holds an unpaired UTF-16 surrogate escape. v0.10.0 refused an element that was a number, string, boolean or array with a plain JSON error. The refusal now matches ErrKeystoreError. See Key sets.
  • Every error sentinel's message now ends in ": ", so it composes with the text that wraps it. A match on an error string breaks. Match with errors.Is instead.
  • A header validation error now wraps its cause with %w. errors.Is matches the inner sentinel, such as ErrMalformedClaim or ErrUnsupportedAlgorithm, as well as ErrMalformedToken. Since v0.12.0, a refusal for your options, or for what this library does not implement, no longer matches ErrMalformedToken. See Changes to the errors you match.
  • Header errors that echo a token value use double quotes, not single quotes, and cut the value at 64 characters. Match errors with errors.Is, not their text.
  • GetSigner, GetSignerFromPrivateKey, GetValidator and GetValidatorFromJwk return a nil interface when they fail. v0.10.0 could return a typed nil beside the error. That value was not == nil, and a call on it panicked. GetSignerFromJwk, new in v0.12.0, also returns a nil interface when it fails.

Signers and validators

  • An HMAC secret must be at least the hash output size. GetSigner for HS256, HS384 or HS512 with no secret returns ErrInvalidPrivateKey. v0.10.0 returned an error that matched no sentinel.
  • HS256, HS384 and HS512 signers refuse a non-zero opts.HashFunc() with ErrSigningError. v0.10.0 ignored opts. See Signing Contract.
  • RS and PS signers and validators refuse a modulus under 2048 bits or over 8192 bits, wherever the key comes from. GetSigner refuses an Opts.BitSize over 8192. An Opts.BitSize under 2048 is now refused with ErrInvalidPrivateKey, so its message gains that error's invalid private key: prefix.
  • RS and PS signers and validators refuse a public exponent that is even, under 3, or over 2^31 - 1, with ErrInvalidPrivateKey or ErrInvalidPublicKey.
  • An ES validator refuses a key on another curve, so GetValidator(jwa.ES384, p256Key) now fails with ErrInvalidPublicKey.
  • A nil key, or one with missing fields, is refused when the signer or validator is built, rather than panicking later.
  • Every signer and validator keeps its own copy of the key, and Public returns a new copy. In v0.10.0 an ES, RS or PS signer or validator used your key in place, so a later change to your key changed it. A validator built from a 2048-bit RSA key could then verify under a smaller one.
  • ES, RS and PS signers refuse a private key whose private half does not belong to its public half. An RS or PS signer refuses such a key when it is built, not at Sign. An RSA private key that lists no primes has them recovered from n, e and d, so the signer signs with them.
  • An ES signer in pre-hashed mode refuses a digest whose length is not the hash's output size with ErrSigningError.
  • An RS or PS signature that does not verify returns false with a nil error, and an ES signature of the wrong length does too. Both used to return an error wrapping ErrInvalidSignature. If you told a forged signature apart by its error, check the boolean.
  • GetValidatorFromJwk refuses a jwk with no kty, a kty that does not fit the algorithm, or an alg member that is not the algorithm you asked for. It also refuses a jwk whose use is present and not "sig", or whose key_ops is present and lacks "verify". To use such a key, read it with jwk.PublicFromJwk and pass it to GetValidator.

jwt.New

  • jwt.New now always calls a model.Signer in JOSE mode, with the whole signing input. v0.10.0 called it in pre-hashed mode whenever Opts.Algorithm named an ES, RS or PS algorithm. That included the zero jwt.Opts{}, whose Algorithm was ES256, so every model.Signer got a SHA-256 digest by default. A model.Signer of your own must accept the whole signing input.
  • jwt.New refuses a head whose alg names a different algorithm from the one that signs, and an alg that is not a string, with ErrUnsupportedAlgorithm. It also refuses Opts.Algorithm naming a different algorithm from a signer of this library. Earlier versions wrote the caller's alg into the header unchecked.
  • jwt.New with a crypto.Signer from outside this library needs an algorithm, from Opts.Algorithm or the head's alg, and a key that suits it. Earlier versions emitted a token with no alg. With a standard library ECDSA or RSA key, they also emitted an ES or PS signature no verifier would accept.
  • jwt.New expects a crypto.Signer from outside this library to follow Go's crypto.Signer contract. For ES256, ES384 and ES512 that means ASN.1 DER output, which New converts to R||S. A signer that already returns raw R||S is now refused with ErrSigningError. Earlier versions passed its output through unchanged, so such a signer worked. Make it return DER, or make it a model.Signer.
  • jwt.New refuses a crypto.Signer from outside this library for HS256, HS384 and HS512 with ErrInvalidPrivateKey. Earlier versions passed it the whole signing input. Build an HMAC signer with jws.GetSigner instead.
  • jwt.New refuses EdDSA with ErrUnsupportedAlgorithm, whether Opts.Algorithm or the head's alg names it. v0.10.0 signed an EdDSA token with an ed25519.PrivateKey when the head named it. Name jwa.Ed25519 instead. A verifier that does not yet know Ed25519 refuses the token, so make sure that your verifiers support it first.
  • jwt.New refuses a nil signer or a nil key with ErrInvalidPrivateKey. v0.10.0 panicked.
  • jwt.New refuses every key that GetSignerFromPrivateKey refuses, such as an RSA key under 2048 bits, and checks the public key of a crypto.Signer from outside this library. v0.10.0 signed with such keys, and v0.11.0 verifiers refuse the token.
  • jwt.New refuses an algorithm with no name, such as jwa.Algorithm(999), with ErrUnsupportedAlgorithm. v0.10.0 wrote "alg":"".
  • jwt.New refuses a head that jwt.Validate would refuse for its shape: a kid that is not a string, a jku or x5u that is not an https URL, a malformed x5c, x5t, x5t#S256 or jwk, a typ or cty that is not a string, a b64 that is not a boolean or is false, and a crit that breaks RFC 7515 section 4.1.11. It also refuses a b64 that crit does not name, as RFC 7797 section 6 requires.
  • jwt.New no longer writes alg and typ into the head map you pass.

Verifying a token

  • JoseOptions.UseTokenProvidedKeys is off unless set, including when opts is nil, and covers only jwk and jku. v0.10.0 used a jwk header key when opts was nil. Pass UseTokenProvidedKeys: true to keep using it.
  • A jwk header key whose use is present and not "sig", or whose key_ops is present and lacks "verify", no longer verifies a token. Set JoseOptions.IgnoreKeyUse to accept such a key.
  • jku and x5u can now supply a key. They are fetched with the client you set in JoseOptions.HttpClient. v0.10.0 passed no client, so neither header could be fetched. When opts was nil or set UseTokenProvidedKeys, a token naming one failed with ErrApplicationError unless your own key verified it first. With no client, both are now ignored. A fetch that fails gives way to the next key source. See jku and x5u need a client.
  • x5c and x5u now work, but only when JoseOptions.X509Roots is set. x5u also needs HttpClient. v0.10.0 refused every token that carried x5c, because it could not read the JSON array, and never fetched x5u. A token with a well-formed x5c now verifies under your retriever's key when no roots are set. A chain must also be in order, hold at most 16 certificates, and pass the usage and encoding checks in x5c and x5u need trust anchors. If your issuer gives signing certificates serverAuth, clientAuth or another purpose, list it in X509ExtKeyUsages.
  • When your retriever returns an error and UseTokenProvidedKeys is set, verification carries on to the keys the token names. v0.10.0 returned your retriever's error at once. If no key verifies, the error wraps every failure, and errors.Is still matches your retriever's error.
  • An alg that AllowedSigningAlgorithms does not allow is refused before any key is sought, with ErrUnsupportedAlgorithm. v0.10.0 refused it with ErrInvalidSignature. In v0.11.0 the error also matched ErrMalformedToken. See Upgrading from 0.11.x to 0.12.0.
  • A token whose alg is EdDSA now verifies under an Ed25519 key. v0.10.0 refused it with ErrInvalidSignature.
  • A crit header naming an extension you have not declared in UnderstoodCriticalHeaders is refused.
  • A token whose segments are not exactly base64url is refused, even when it is correctly signed. This covers line breaks, whitespace, padding and non-zero unused bits in the last character. The same rule applies to the base64url members of a jwk, such as n, e, x, y and d, and to x5t and x5t#S256.
  • A protected header or JWT claims set that is not valid UTF-8 is refused. Previously each invalid byte became U+FFFD.
  • A protected header or JWT claims set with a string that holds an unpaired UTF-16 surrogate escape, such as "\ud800", is refused. Previously the escape became U+FFFD. A U+FFFD that is in the signed bytes, raw or as \ufffd, is still accepted.
  • A JWT claims set of null is refused. jwt.Validate and jws.VerifyCompactSerialization previously returned a nil body and no error.
  • A b64 header of false is refused, even when UnderstoodCriticalHeaders names b64. A b64 that is not a JSON boolean is refused with ErrMalformedClaim.
  • A typ or cty header that is not a string is refused with ErrMalformedClaim, as RFC 7515 sections 4.1.9 and 4.1.10 require.
  • A token whose cty is JWT is refused by jws.VerifyCompactSerialization and jwt.Validate with a message naming nested JWTs. v0.11.0 refused it with ErrMalformedToken, and since v0.12.0 the error is ErrUnsupportedAlgorithm. See Upgrading from 0.11.x to 0.12.0. Media-type parameters on the cty are ignored.
  • A token's signature is checked against at most JoseOptions.MaxKeysTried keys, 100 by default, across every source. A token that would need more is refused with ErrTooManyKeys. If your retriever returns more than 100 keys that suit one alg, raise the limit.

JWKs

  • Every kid that PublicJwk and PrivateJwk produce has changed. It is now the key's RFC 7638 thumbprint, which other implementations compute the same way. The old value was a SHA-256 over the encoded public members with no kty, so keys of different types could share one. An Ed25519 jwk now carries a kid too. Re-derive any kid you stored or pinned.
  • PublicJwk and PrivateJwk refuse a key they cannot encode, rather than panic or produce a malformed jwk.
  • In 0.11.0, an OKP jwk is read only when it is a well-formed Ed25519 key, whose x is the canonical encoding of a point. Since v0.12.0, an X25519 jwk is read too. See Upgrading from 0.11.x to 0.12.0.
  • A jwk with no kty is refused with ErrInvalidPublicKey or ErrInvalidPrivateKey. v0.10.0 returned an error that matched no sentinel. A jwk whose kty is not a string is refused the same way. v0.10.0 panicked.
  • PublicFromJwk and PrivateFromJwk refuse an EC jwk whose x or y is not the full coordinate size of its curve, or whose point is not on the curve. A producer that strips leading zero octets breaks RFC 7518 section 6.2.1.2, and its keys are now refused.
  • PrivateFromJwk refuses an EC jwk with no d. It used to return a key that panicked when used.
  • PrivateFromJwk refuses an EC or RSA jwk whose private members do not belong to its public members. An RSA jwk with no primes has them recovered, as NIST SP 800-56B Rev. 2 Appendix C.1 describes. So the key it returns carries p and q, a d that does not undo e is refused, and a modulus that is not the product of two primes is refused. Such a key, written again with PrivateJwk, now carries p, q, dp, dq and qi.
  • PublicJwk and PrivateJwk refuse every key that PublicFromJwk and PrivateFromJwk refuse, such as an EC key whose d is not the private key of its point, or an RSA key whose e is even.
  • An EC jwk with an unsupported crv is now refused with ErrUnsupportedAlgorithm. Before, the error matched no sentinel. The error text for an unsupported kty or crv no longer repeats the value.
  • PublicFromJwk and PrivateFromJwk refuse an RSA integer member with a leading zero octet, such as e: "AAEAAQ", with ErrMalformedClaim. RFC 7518 section 2 requires the minimum number of octets. A producer that copies a DER integer, sign octet included, into n makes such a member. Have it strip the leading zero octet.
  • PublicFromJwk and PrivateFromJwk refuse an RSA e that is even, below 3 or above 2^31-1. An e of more than 8 octets used to be read as its low 64 bits. They also refuse an RSA integer member with no octets, an n of zero, and a private key with no primes whose modulus is over 8192 bits. Since v0.12.0, they also refuse such a key that carries its primes.
  • PrivateFromJwk reports a bad n or e in an RSA private jwk with ErrInvalidPrivateKey. The error still matches the class of the inner fault, such as ErrInvalidPublicKey for a refused e.

jwt.Validate

  • jwt.Validate refuses a token at the instant its exp names, and judges a fractional iat, nbf or exp without dropping the fraction. Earlier versions cut the current time and each claim to whole seconds. So they accepted a token for up to a second past exp, and up to a second before a fractional nbf or iat.
  • jwt.Validate refuses an iss, sub, jti or aud of the wrong JSON type with ErrMalformedClaim.
  • jwt.Validate refuses a token that does not have three segments with ErrMalformedToken, and one of five segments, a JWE, with ErrUnsupportedAlgorithm. v0.10.0 returned errors that matched no sentinel. Since v0.12.0, jwt.Validate decrypts a JWE when you give it decrypters. See Encrypted JWTs.
  • A time-claim refusal now matches ErrMalformedClaim, ErrExpired or ErrNotYetValid, and its message has changed. If you match on the old text, such as exp claim is before current time, match with errors.Is instead.

New in 0.11.0

These add to the API without changing what you already use:

  • jws.Verify returns the payload as octets, for a JWS whose payload is not a JSON object.
  • jwk.Thumbprint computes the RFC 7638 thumbprint of a jwk.
  • PublicFromJwk, PrivateFromJwk, PublicJwk, PrivateJwk and Thumbprint handle AKP keys.
  • SecretKey.Equal is reachable from Public(), so two HMAC validators can be compared, and the comparison runs in constant time.
  • jwa.Ed25519, jwa.MLDSA44, jwa.MLDSA65 and jwa.MLDSA87, each with a signer and a validator.
  • JoseOptions fields: HttpClient, FetchTimeout, MaxKeysTried, AcceptedTypes, RequireKeyIdentifier, UnderstoodCriticalHeaders, X509Roots, IgnoreKeyUse, X509ExtKeyUsages and ExpectedAudience. Each is off, or the documented default, when unset.
  • Error sentinels: ErrExpired, ErrNotYetValid, ErrAudienceMismatch, ErrInvalidOptions and ErrTooManyKeys.

Upgrading from the pre-0.10 line

Every change below is a compile error or a silent behaviour change for a consumer of the release before v0.10.0. Apply Upgrading from 0.10.x as well.

Packages moved

Was Now
go-jose/error go-jose/joseerror
model.Algorithm, model.ES256 and the rest jwa.Algorithm, jwa.ES256 and the rest

Error sentinels

Every sentinel gained an Err prefix: InvalidPublicKey is now ErrInvalidPublicKey, SigningError is now ErrSigningError, and the same for the rest. v0.10.0 added eight sentinels, and v0.11.0 adds five more. Match a sentinel with errors.Is:

if errors.Is(err, joseerror.ErrInvalidSignature) {
	// the signature does not verify
}

Signatures changed

Function Change
jwa.GetAlgorithm Returns Algorithm, not *Algorithm. Returns jwa.Unknown rather than nil for an unknown name, and the comparison is now case sensitive
jwt.New Takes a fourth parameter, jwt.Opts, naming the algorithm to sign with
jwt.Validate Takes a model.Retriever and *model.JoseOptions after the token. The publicKey parameter is gone: supply key material through the retriever, or turn on UseTokenProvidedKeys to use what the token's header names
jws.GetValidatorFromJwk Takes map[string]any, not []byte

Behaviour changes documented elsewhere in this file

  • A validator for an HMAC algorithm can only be built from a signer.

About

A Go implementation of the JOSE suite of specifications - JWE, JWK, JWS, and JWT

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages