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).
- Go 1.27 or higher
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
)go get github.com/MichaelFraser99/go-joseThis 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
algisEdDSAverifies under an Ed25519 key, as RFC 8037 defines it. GetSigner,GetSignerFromPrivateKey,GetSignerFromJwkandjwt.NewrefuseEdDSAwithErrUnsupportedAlgorithm. Sign withEd25519.EdDSAandEd25519are separate values ofjwa.Algorithm. To refuseEdDSAtokens, setAllowedSigningAlgorithmstojwa.Ed25519withoutjwa.EdDSA. While your issuers move fromEdDSAtoEd25519, 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 intIts zero value is jwa.Unknown, so a variable you forgot to set names no algorithm rather than ES256.
func (a Algorithm) String() stringString returns the name of the algorithm, such as "RS256". It returns the empty string for Unknown.
func GetAlgorithm(alg string) AlgorithmGetAlgorithm 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.
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)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/tlsputs on a peer's RSA key.Opts.BitSizetakes 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/rsarefuses 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
dmust be the private key of its point. - ML-DSA: the key must be an
*mldsa.PrivateKeyor*mldsa.PublicKeyof 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.PrivateKeyored25519.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 fromN,EandD, as NIST SP 800-56B Rev. 2 Appendix C.1 describes, and signs with them. IfDdoes not undoE, or the modulus is not the product of two primes, the key is refused. With primes, the key must passrsa.PrivateKey.Validate. The signer and validator keep their own copy of the key, so a later change to your key does not affect them.Publicreturns a new copy each time, so a change to that copy does not affect them either.
The Sign method follows JOSE conventions per RFC 7518 rather than Go's crypto.Signer contract. It supports two modes:
- JOSE mode (
opts == niloropts.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'scrypto.Signerconvention. ES, RS and PS implement this mode. They refuse aHashthat is not the algorithm's own, and a digest whose length is not that hash's output size, withErrSigningError.
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()withErrSigningError. Pass the signing input whole and leaveoptsnil.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 overcrypto.Signerand passes a non-zeroHashalongside the raw signing input — that worked, becauseoptswas ignored, and it no longer does. Such a caller passesnilfor an HS algorithm, or a zeroHash.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/ed25519signs with Ed25519ph, which is a different algorithm. So the Ed25519 signer refuses a non-zeroopts.HashFunc()withErrSigningError. An*ed25519.Optionswith a non-emptyContextis refused the same way: RFC 8032 section 5.1 gives Ed25519 no context, and a context askscrypto/ed25519for 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()withErrSigningError, includingcrypto.MLDSAMu, which askscrypto/mldsato sign an externally computed mu. RFC 9964 section 5 also requires an empty context, so an*mldsa.Optionswith a non-emptyContextis 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.
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()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 thealga token names. - With a retriever, set
JoseOptions.AllowedSigningAlgorithmsto 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.
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 outsideA-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.
VerifyCompactSerializationholds 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.VerifyCompactSerializationholds the payload to the same rule. - An
algthis library has no validator for is refused withErrUnsupportedAlgorithmbefore any key is sought, so nojkuorx5uis fetched for it. - A
b64header offalseis refused withErrMissingCriticalClaim, even when you nameb64inUnderstoodCriticalHeaders. RFC 7797 section 3 says such a payload is not base64url-encoded, and this library always decodes it. Ab64header that is not a JSON boolean is refused withErrMalformedClaim, as RFC 7797 section 3 requires. - A
typorctyheader that is not a string is refused withErrMalformedClaim, whether or not you setAcceptedTypes. 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.
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.
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.
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
ctxis ending still verifies it. Endingctxstops further work, but a signature already checked stays valid.jwe.Decryptdoes 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.
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
kidis absent or equals the header'skid. RFC 7515 section 4.1.4 calls the header'skida hint, and RFC 7517 section 4.5 makes a jwk'skidoptional, so a key that names nokidstays a candidate. - Its
algis absent or equals the header'salg. RFC 8725 section 3.1 says "each key MUST be used with exactly one algorithm".EdDSAandEd25519count as equal, because with an Ed25519 key they name the same algorithm. A key that names noalgstays a candidate, since RFC 7517 section 4.4 makesalgoptional. Such a key verifies under any algorithm its key type allows, so pinAllowedSigningAlgorithmsto bind it to one. - Its
kty, and itscrvwhere the key type has one, can serve the header'salg. RFC 7518 sections 3.2 to 3.5 giveocttoHS256toHS512,RSAto the RS and PS families, andECtoES256,ES384andES512on P-256, P-384 and P-521. RFC 9864 givesOKPwithcrvEd25519toEd25519. This library implementsEdDSA(RFC 8037 section 3.1) withEd25519only, so it givesEdDSAthe same key. RFC 9964 givesAKPto the ML-DSA algorithms, and itsalgnames the parameter set. Any othercrvstring is not selected, such assecp256k1,X25519orEd448. A key with nocrv, or acrvthat is not a string, is left to the key reader, which refuses it. - Its
useis absent or"sig", and itskey_opsis 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.
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.
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.
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
digitalSignatureornonRepudiation(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 onlykeyCertSignis refused, as is a key agreement certificate. An intermediate whose key usage extension is present must assertkeyCertSign, 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 nameanyExtendedKeyUsage. 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.
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()orP521(); 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
dis outside[1, n-1], wherenis the order of the curve. - An EC private key whose
dis 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
yof 2^255-19 or more, and a set sign bit whenxis 0. - An RSA key whose
eis not an odd integer from 3 to 2^31-1. - An RSA private key whose
dis not between 0 andn, or does not undoe. - 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
PrivateFromJwkrefuses a jwk that carriesoth. - An RSA private key with a prime that is not positive. RFC 8017 section 3.2 makes
pandqpositive integers. - A two-prime RSA private key that
rsa.PrivateKey.Validaterejects, such as one whose primes do not multiply ton.
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.
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.
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
Newwrites that algorithm intoalg.Optsmay leaveAlgorithmunset.Newcalls it in JOSE mode, with the whole signing input. So does any othermodel.Signer. - Any other
crypto.Signertakes its algorithm fromOpts.Algorithm, or from analgthe head names. With neither,Newreturns an error. - If the head's
algorOpts.Algorithmnames a different algorithm,NewreturnsErrUnsupportedAlgorithm. So does analgthat 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,
Newconverts 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 withErrSigningError. -
For PS256, PS384 and PS512,
Newasks 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.
Newpasses the whole signing input with a zero hash, socrypto/mldsasigns it with an empty context. -
A key that does not suit the algorithm, and any HS algorithm, is refused with
ErrInvalidPrivateKey. -
Newpasses an*ecdsa.PrivateKey,*rsa.PrivateKey,ed25519.PrivateKeyor*ed25519.PrivateKeytoGetSignerFromPrivateKey, and refuses each key thatGetSignerFromPrivateKeyrefuses. So an RS or PS key needs a modulus of 2048 to 8192 bits. For any othercrypto.Signer,Newchecks the public key thatPublicreturns, the same way a validator does. -
Newrefuses a nil signer, or a nil pointer, withErrInvalidPrivateKey. It does not panic. -
Newrefuses analgoutsidejwa, such asjwa.Algorithm(999), withErrUnsupportedAlgorithm. RFC 7515 section 4.1.1 saysalgmust be present and understood. -
Newchecks the header it will sign with the same rulesValidateapplies. So it does not sign a header that its ownValidaterefuses for its shape:jkuandx5umust 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
httpsURI with an empty host, such ashttps:///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. jwkmust be a JSON object, and must not hold a private key member:d,p,q,dp,dq,qi,oth,korpriv(section 4.1.3 names a public key). Itskid,algandusemust be strings, itskey_opsan array of distinct strings, and itsuseandkey_opsconsistent (RFC 7517 sections 4.2 to 4.5).Validaterefuses ajwkheader that breaks these rules.kid,typandctymust be strings (sections 4.1.4, 4.1.9 and 4.1.10).x5cmust be a non-empty array of base64 DER certificates (section 4.1.6).x5tandx5t#S256must be base64url (sections 4.1.7 and 4.1.8).critmust 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).b64must be a JSON boolean (RFC 7797 section 3).
A fault is
ErrMalformedClaim. Acritname that the header does not hold isErrMissingCriticalClaim. -
Newrefuses ab64offalsewithErrMissingCriticalClaim, because it always encodes the payload. -
Newrefuses ab64thatcritdoes not name withErrMissingCriticalClaim. RFC 7797 section 6 sayscritMUST includeb64whenb64is used. To sign with"b64": true, also set"crit": ["b64"]. A verifier must then nameb64inUnderstoodCriticalHeaders.
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:
RequireEncryptedJWTwith no decrypter whosealgthe 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,UseTokenProvidedKeysandX509Roots. Those three supply no HMAC key, so they do not count whenAllowedSigningAlgorithmsnames only HMAC algorithms. A JWT that is only encrypted can pass whenRequireSignedJWTis off, and a decrypter is fordir, an AES key wrap or PBES2, orAllowUnauthenticatedJWTis 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:
RequireSignedJWTrefuses a JWT that is only encrypted, under any key, withErrInvalidSignature. Set it if every JWT must carry an issuer's signature. It needs a source of signing keys: with no retriever and none ofKeySet,UseTokenProvidedKeysandX509Roots, every call fails withErrInvalidOptions. If you also hold a shared key, its other holders then cannot write claims of their own.RequireEncryptedJWTrefuses a JWT that is not encrypted, withErrUnsupportedAlgorithm. Set it if your peers encrypt every JWT to you. It needs a decrypter whosealgthe JWE options permit. Without one, every call fails withErrInvalidOptions.
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.
The jwe package encrypts and decrypts the JWE Compact Serialization of RFC 7516. It does not implement the JWE JSON Serialization.
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
algis present, it must name the algorithm that you give. - If
useis present, it must beenc. - If
key_opsis present, it must includewrapKeyfor an encrypter andunwrapKeyfor a decrypter, and it must not list a value twice. For anECDH-ESdecrypter, it must includederiveKeyorderiveBitsinstead. AnECDH-ESencrypter has no required value, because nokey_opsvalue names a public key that is used for key agreement. But if itskey_opsincludessignorverify, it must also includederiveKeyorderiveBits. Otherwise the values mark a signing key. - If
useis present,key_opsmust not includesignorverify, 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.
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.
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.
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
MaxDecompressedSizeoctets is refused withErrOutOfBounds.Decryptstops 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
zipother thanDEFis refused withErrUnsupportedAlgorithm, and azipthat is not a string withErrMalformedToken.
This library does not implement RSA1_5, and it will not. RFC 8725 section 3.2 advises against it because of padding oracle attacks.
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.
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:
AllowedKeyManagementAlgorithmsandAllowedContentEncryptionAlgorithmslimit thealgandencvalues 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 JWSalg, is a configuration fault.Decryptrefuses every call withErrInvalidOptionsuntil you correct it.MaxKeysTriedlimits the number of decrypters of eachalg. The default is 100. If you give more, every call fails withErrInvalidOptions, whatever the token. With many keys, select one withParseHeaderand giveDecryptonly that one.OnDecrypterErrorreceives each decrypter that fails, and its error. Use it to see a fault such as a hardware module outage, whichDecryptotherwise reports as the sameErrDecryptionFailedas a bad token. What it receives can depend on the token, so log it, and do not send it to the sender.MaxPBES2CountandRequireRecommendedPBES2Countlimit thep2cof a PBES2 token. See Passwords (PBES2).MaxDecompressedSizeturns onzipand limits the size of the inflated plaintext. See Compression.AllowUnauthenticatedJWTapplies only injwt.Validate. See Encrypted JWTs.AcceptedTypes,RequireKeyIdentifierandUnderstoodCriticalHeaderswork as theJoseOptionsfields of the same name do for a JWS. The exception isb64: RFC 7797 defines it for JWS only, so a JWEcritthat namesb64is refused.StrictKeyOperationsapplies toGetEncrypterFromJwkandGetDecrypterFromJwk.
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.
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.
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
ctynamesJWT, the plaintext is a Nested JWT. It must be a signed JWT, whichValidateverifies with the retriever andopts. A JWE inside the JWE is refused withErrUnsupportedAlgorithm, as this library does not implement that nesting. Any other plaintext that is not a JWS is refused withErrMalformedToken. - 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)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
ctyJWT, so it is refused as a JWT signed inside a JWS. To nest, sign first and then encrypt, withjwt.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.
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
algorencoutside an allow-list, atypoutsideAcceptedTypes, nokidwhenRequireKeyIdentifieris set, or ap2coutside your bounds; - it names what this library does not implement: a JWT signed inside a JWS or encrypted inside a JWE, an unknown
algorenc, azipother thanDEFor anyzipwhenMaxDecompressedSizeis unset, acritextension that you have not named inUnderstoodCriticalHeaders, or ab64offalse.
If a header has both kinds of fault, the error reports the fault in the specification.
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:
- Your request's own context has ended: test
ctx.Err() != nilon thectxthat you passed. Send 499 for a client that went away, or 504 for your deadline. Test the context itself, not the error. Ajkuorx5ufetch that runs out of time also matchescontext.DeadlineExceeded, and that fault is the peer's, not yours. ErrInvalidOptions. Your options are wrong, and no token can pass. This is a server fault (500).- The errors of your own retriever.
Validatewraps them and adds no sentinel, so test them witherrors.Is(err, yourErr). A failed key store is a server fault (500 or 503). - Every other sentinel. The token was refused (401, or 400 for
ErrMalformedTokenif you separate malformed requests). This includesErrMissingClaim,ErrAudienceMismatchandErrIssuerMismatch: 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:
ErrTooManyKeysmeans that the signature did not verify under as many keys asJoseOptions.MaxKeysTriedallows. This applies to a signed JWT and to the JWS inside a Nested JWT. The keys can come from your retriever, yourKeySetor ajkuset the peer chose. So setMaxKeysTriedabove the number of keys that your own retriever returns plus the most members of yourKeySetthat one token can select. Only a member whosekid,algand key type match the token is selected. A token with nokidselects every member itsalgcan use, and a member with nokidis selected for every token.RequireKeyIdentifierrefuses a token with nokid, but a member with nokidstill matches everykid. Then the error can only come from a token that names too many keys, which is the peer's fault (401). More decrypters of onealgthanJWEOptions.MaxKeysTriedallows isErrInvalidOptions, notErrTooManyKeys.ErrOutOfBoundsfor a PBES2 token means thatp2c, multiplied by the number of your decrypters of the token'salg, is more thanMaxPBES2Count. A peer can cause it with a highp2c, which is a 4xx. You can cause it with too many PBES2 decrypters: three decrypters at the defaultMaxPBES2Countrefuse a token at the commonp2cof 600,000. So give at mostMaxPBES2Countdivided by your senders'p2cPBES2 decrypters. Then the error can only come from a token with a higherp2c, which is the peer's fault. Azipthat inflates pastMaxDecompressedSizeis alsoErrOutOfBounds, and is the peer's fault.ErrDecryptionFailedis 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 withOnDecrypterError, and decide after the call. A wrong key or a forged token also callsOnDecrypterError, 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.
ErrApplicationErrormeans that a key the token names, throughjkuorx5u, 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 matchescontext.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 anA128KWtoA256KWorA128GCMKWtoA256GCMKWencrypter or decrypter, prints assecret keyand logs assecret key.encoding/json,encoding/xmlandencoding/gobrefuse to encode it, so encoding a value that holds it fails as a whole. Nested in another value, the JSON handler oflog/sloglogs that refusal in its place. It holds the secret behind two pointers, so a verbfmtdoes not accept, or an unexported struct field that holds it, prints an address. - A
jwe.DirectKeyprints and logs as theencit is bound to, and ajwe.PasswordKeyas its type name. TheirKeyandPasswordfields are exported, soencoding/json,encoding/xmlandencoding/gobencode them, and a verbfmtdoes not accept, or an unexported struct field that holds one, prints them. The same holds where those encoders run for you: the JSON handler oflog/slogencodes one nested in another value, andhtml/templateencodes 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.
v0.12.0 changes three signatures, one key type and several errors. The changes are listed against v0.11.0.
Three changes can break your build:
model.Mode,model.JWSandmodel.JWEare removed. Nothing in the public API took them, so delete any use.jws.GetValidatorFromJwktakes a*model.JoseOptionsas a third argument. Passnilto keep the v0.11.0 behaviour.jwt.Validatetakes decrypters and a*model.JWEOptionsfor the JWE layer, and returns a*jwt.Token. For a signed JWT, passnilfor both, and readToken.SignatureHeaderandToken.Claimswhere you readheadandbody:
validated, err := jwt.Validate(ctx, token, retriever, nil, opts, nil)
if err != nil {
return err
}
head, body := validated.SignatureHeader, validated.ClaimsThis 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
okis false. Changekey.(*ed25519.PublicKey)tokey.(ed25519.PublicKey), andkey.(*ed25519.PrivateKey)tokey.(ed25519.PrivateKey). - A
case *ed25519.PublicKey:in a type switch no longer matches, so the switch silently takes itsdefault. Change the case toed25519.PublicKey, and do the same for a private key. ==on two such keys panics withcomparing uncomparable type ed25519.PublicKey. Compare them with theEqualmethod thated25519.PublicKeyanded25519.PrivateKeyhave.- A key used as a map key panics with
hash of unhashable type ed25519.PublicKey. Key the map by the jwk's thumbprint fromjwk.Thumbprint, or bystring(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.
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.
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
jwkwhoseuseis"sig"and whosekey_opsnamesverifyand alsoencrypt,decrypt,wrapKey,unwrapKey,deriveKeyorderiveBits. v0.11.0 verified the token with it. - A
jwkwhosekey_opslists a value twice, such as["verify", "verify"]. v0.11.0 verified the token with it. - A
jwkwhoseuseis"enc"and whosekey_opsnamessignorverify. v0.11.0 passed over the key, and refused the token withErrInvalidSignatureandErrNoKeyIdentifierMatchif no other key verified it. - A
jwkwhosekid,alg,useorkey_opshas the wrong JSON type, such as akidof123. v0.11.0 refused the token withErrMalformedClaimonly.
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.
These add to the API without changing what you already use:
- The
jwepackage, withGetEncrypter,GetDecrypter,GetEncrypterFromJwk,GetDecrypterFromJwk,Encrypt,Decrypt,ParseHeaderandDirectKey. See Encrypting and decrypting. octkeys in thejwkpackage:PrivateFromJwkreads one as a[]byte, andPrivateJwkwrites one.PrivateJwkalso writes whatPublic()returns for a secret key, with analgthat names the algorithm the key was made for. v0.11.0 refused it.model.Encrypter,model.Decrypterandmodel.DecrypterOpts.jwa.Encryptionwithjwa.GetEncryption, and thealgconstantsjwa.RSAOAEPtojwa.Dirandjwa.ECDHEStojwa.ECDHESA256KW. The integer values of the existingjwa.Algorithmconstants do not change.model.JWEOptions, the options ofjwe.Decrypt,jwe.ParseHeader,jwe.GetEncrypterFromJwk,jwe.GetDecrypterFromJwkand the JWE layer ofjwt.Validate.JoseOptionsfields:KeySet,StrictKeyOperations,RequireSignedJWT,RequireEncryptedJWT,RequiredClaims,ExpectedIssuerandAllowedKeyURLs. 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.Encryptandjwt.Token, for encrypted JWTs. See Encrypted JWTs.jwt.CheckOptions,jws.CheckOptionsandjwe.CheckOptions, which refuse at startup the options thatjwt.Validate,jws.Verifyandjwe.Decryptwould refuse for every token.jwe.PasswordKeyfor PBES2, and thealgconstantsjwa.A128GCMKWtojwa.A256GCMKWandjwa.PBES2HS256A128KWtojwa.PBES2HS512A256KW.- The error sentinels
ErrEncryptionError,ErrOutOfBoundsandErrIssuerMismatch.ErrDecryptionFailednow has a use.
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.
- This module now requires Go 1.27. v0.10.0 declared Go 1.21, which Go no longer supports.
jwt.Validateandjws.VerifyCompactSerializationtake acontext.Contextfirst. It bounds anyjkuorx5ufetch. A nilctxis refused withErrInvalidOptions.- Every
jwa.Algorithmconstant has a new integer value.Unknownis now 0, so a zeroAlgorithmnames no algorithm. In v0.10.0 the zero value wasES256, so an unsetjwt.Opts.Algorithmor configuration field meant ES256. v0.10.0'sUnknownwas 13, which is nowEdDSA. If you store or send anAlgorithmas an integer, store itsString()and read it back withjwa.GetAlgorithm. model.Jwks.RetrieveByKeyIDreturns[]map[string]any, every key carrying thekidin set order, not onemap[string]any. It returns an error only when no key carries thekid. To keep the old exactly-one meaning, checklen(keys) == 1and usekeys[0].model.Jwks.AddwithEnforceUniqueKIDsrefuses akidthe set already holds more than once. v0.10.0 added it.json.Marshalof an emptymodel.Jwkswrites{"keys":[]}. v0.10.0 wrote{"keys":null}.- Decoding JSON into
model.Jwksrefuses a document with nokeysmember, with"keys": null, or that isnull, and readskeysonly by its exact name. It also refuses an element of thekeysarray that isnull, 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 matchesErrKeystoreError. 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 witherrors.Isinstead. - A header validation error now wraps its cause with
%w.errors.Ismatches the inner sentinel, such asErrMalformedClaimorErrUnsupportedAlgorithm, as well asErrMalformedToken. Since v0.12.0, a refusal for your options, or for what this library does not implement, no longer matchesErrMalformedToken. 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,GetValidatorandGetValidatorFromJwkreturn 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.
- An HMAC secret must be at least the hash output size.
GetSignerfor HS256, HS384 or HS512 with no secret returnsErrInvalidPrivateKey. v0.10.0 returned an error that matched no sentinel. - HS256, HS384 and HS512 signers refuse a non-zero
opts.HashFunc()withErrSigningError. v0.10.0 ignoredopts. See Signing Contract. - RS and PS signers and validators refuse a modulus under 2048 bits or over 8192 bits, wherever the key comes from.
GetSignerrefuses anOpts.BitSizeover 8192. AnOpts.BitSizeunder 2048 is now refused withErrInvalidPrivateKey, so its message gains that error'sinvalid private key:prefix. - RS and PS signers and validators refuse a public exponent that is even, under 3, or over 2^31 - 1, with
ErrInvalidPrivateKeyorErrInvalidPublicKey. - An ES validator refuses a key on another curve, so
GetValidator(jwa.ES384, p256Key)now fails withErrInvalidPublicKey. - 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
Publicreturns 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 fromn,eandd, 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
falsewith a nil error, and an ES signature of the wrong length does too. Both used to return an error wrappingErrInvalidSignature. If you told a forged signature apart by its error, check the boolean. GetValidatorFromJwkrefuses a jwk with nokty, aktythat does not fit the algorithm, or analgmember that is not the algorithm you asked for. It also refuses a jwk whoseuseis present and not"sig", or whosekey_opsis present and lacks"verify". To use such a key, read it withjwk.PublicFromJwkand pass it toGetValidator.
jwt.Newnow always calls amodel.Signerin JOSE mode, with the whole signing input. v0.10.0 called it in pre-hashed mode wheneverOpts.Algorithmnamed an ES, RS or PS algorithm. That included the zerojwt.Opts{}, whoseAlgorithmwas ES256, so everymodel.Signergot a SHA-256 digest by default. Amodel.Signerof your own must accept the whole signing input.jwt.Newrefuses a head whosealgnames a different algorithm from the one that signs, and analgthat is not a string, withErrUnsupportedAlgorithm. It also refusesOpts.Algorithmnaming a different algorithm from a signer of this library. Earlier versions wrote the caller'salginto the header unchecked.jwt.Newwith acrypto.Signerfrom outside this library needs an algorithm, fromOpts.Algorithmor the head'salg, and a key that suits it. Earlier versions emitted a token with noalg. With a standard library ECDSA or RSA key, they also emitted an ES or PS signature no verifier would accept.jwt.Newexpects acrypto.Signerfrom outside this library to follow Go'scrypto.Signercontract. For ES256, ES384 and ES512 that means ASN.1 DER output, whichNewconverts to R||S. A signer that already returns raw R||S is now refused withErrSigningError. Earlier versions passed its output through unchanged, so such a signer worked. Make it return DER, or make it amodel.Signer.jwt.Newrefuses acrypto.Signerfrom outside this library for HS256, HS384 and HS512 withErrInvalidPrivateKey. Earlier versions passed it the whole signing input. Build an HMAC signer withjws.GetSignerinstead.jwt.NewrefusesEdDSAwithErrUnsupportedAlgorithm, whetherOpts.Algorithmor the head'salgnames it. v0.10.0 signed anEdDSAtoken with aned25519.PrivateKeywhen the head named it. Namejwa.Ed25519instead. A verifier that does not yet knowEd25519refuses the token, so make sure that your verifiers support it first.jwt.Newrefuses a nil signer or a nil key withErrInvalidPrivateKey. v0.10.0 panicked.jwt.Newrefuses every key thatGetSignerFromPrivateKeyrefuses, such as an RSA key under 2048 bits, and checks the public key of acrypto.Signerfrom outside this library. v0.10.0 signed with such keys, and v0.11.0 verifiers refuse the token.jwt.Newrefuses an algorithm with no name, such asjwa.Algorithm(999), withErrUnsupportedAlgorithm. v0.10.0 wrote"alg":"".jwt.Newrefuses a head thatjwt.Validatewould refuse for its shape: akidthat is not a string, ajkuorx5uthat is not anhttpsURL, a malformedx5c,x5t,x5t#S256orjwk, atyporctythat is not a string, ab64that is not a boolean or isfalse, and acritthat breaks RFC 7515 section 4.1.11. It also refuses ab64thatcritdoes not name, as RFC 7797 section 6 requires.jwt.Newno longer writesalgandtypinto the head map you pass.
JoseOptions.UseTokenProvidedKeysis off unless set, including whenoptsisnil, and covers onlyjwkandjku. v0.10.0 used ajwkheader key whenoptswasnil. PassUseTokenProvidedKeys: trueto keep using it.- A
jwkheader key whoseuseis present and not"sig", or whosekey_opsis present and lacks"verify", no longer verifies a token. SetJoseOptions.IgnoreKeyUseto accept such a key. jkuandx5ucan now supply a key. They are fetched with the client you set inJoseOptions.HttpClient. v0.10.0 passed no client, so neither header could be fetched. Whenoptswas nil or setUseTokenProvidedKeys, a token naming one failed withErrApplicationErrorunless 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.x5candx5unow work, but only whenJoseOptions.X509Rootsis set.x5ualso needsHttpClient. v0.10.0 refused every token that carriedx5c, because it could not read the JSON array, and never fetchedx5u. A token with a well-formedx5cnow 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 certificatesserverAuth,clientAuthor another purpose, list it inX509ExtKeyUsages.- When your retriever returns an error and
UseTokenProvidedKeysis 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, anderrors.Isstill matches your retriever's error. - An
algthatAllowedSigningAlgorithmsdoes not allow is refused before any key is sought, withErrUnsupportedAlgorithm. v0.10.0 refused it withErrInvalidSignature. In v0.11.0 the error also matchedErrMalformedToken. See Upgrading from 0.11.x to 0.12.0. - A token whose
algisEdDSAnow verifies under an Ed25519 key. v0.10.0 refused it withErrInvalidSignature. - A
critheader naming an extension you have not declared inUnderstoodCriticalHeadersis 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,yandd, and tox5tandx5t#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
nullis refused.jwt.Validateandjws.VerifyCompactSerializationpreviously returned a nil body and no error. - A
b64header offalseis refused, even whenUnderstoodCriticalHeadersnamesb64. Ab64that is not a JSON boolean is refused withErrMalformedClaim. - A
typorctyheader that is not a string is refused withErrMalformedClaim, as RFC 7515 sections 4.1.9 and 4.1.10 require. - A token whose
ctyisJWTis refused byjws.VerifyCompactSerializationandjwt.Validatewith a message naming nested JWTs. v0.11.0 refused it withErrMalformedToken, and since v0.12.0 the error isErrUnsupportedAlgorithm. See Upgrading from 0.11.x to 0.12.0. Media-type parameters on thectyare ignored. - A token's signature is checked against at most
JoseOptions.MaxKeysTriedkeys, 100 by default, across every source. A token that would need more is refused withErrTooManyKeys. If your retriever returns more than 100 keys that suit onealg, raise the limit.
- Every
kidthatPublicJwkandPrivateJwkproduce 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 nokty, so keys of different types could share one. An Ed25519 jwk now carries akidtoo. Re-derive anykidyou stored or pinned. PublicJwkandPrivateJwkrefuse a key they cannot encode, rather than panic or produce a malformed jwk.- In 0.11.0, an
OKPjwk is read only when it is a well-formed Ed25519 key, whosexis 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
ktyis refused withErrInvalidPublicKeyorErrInvalidPrivateKey. v0.10.0 returned an error that matched no sentinel. A jwk whosektyis not a string is refused the same way. v0.10.0 panicked. PublicFromJwkandPrivateFromJwkrefuse an EC jwk whosexoryis 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.PrivateFromJwkrefuses an EC jwk with nod. It used to return a key that panicked when used.PrivateFromJwkrefuses 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 carriespandq, adthat does not undoeis refused, and a modulus that is not the product of two primes is refused. Such a key, written again withPrivateJwk, now carriesp,q,dp,dqandqi.PublicJwkandPrivateJwkrefuse every key thatPublicFromJwkandPrivateFromJwkrefuse, such as an EC key whosedis not the private key of its point, or an RSA key whoseeis even.- An EC jwk with an unsupported
crvis now refused withErrUnsupportedAlgorithm. Before, the error matched no sentinel. The error text for an unsupportedktyorcrvno longer repeats the value. PublicFromJwkandPrivateFromJwkrefuse an RSA integer member with a leading zero octet, such ase: "AAEAAQ", withErrMalformedClaim. RFC 7518 section 2 requires the minimum number of octets. A producer that copies a DER integer, sign octet included, intonmakes such a member. Have it strip the leading zero octet.PublicFromJwkandPrivateFromJwkrefuse an RSAethat is even, below 3 or above 2^31-1. Aneof more than 8 octets used to be read as its low 64 bits. They also refuse an RSA integer member with no octets, annof 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.PrivateFromJwkreports a badnorein an RSA private jwk withErrInvalidPrivateKey. The error still matches the class of the inner fault, such asErrInvalidPublicKeyfor a refusede.
jwt.Validaterefuses a token at the instant itsexpnames, and judges a fractionaliat,nbforexpwithout 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 pastexp, and up to a second before a fractionalnbforiat.jwt.Validaterefuses aniss,sub,jtioraudof the wrong JSON type withErrMalformedClaim.jwt.Validaterefuses a token that does not have three segments withErrMalformedToken, and one of five segments, a JWE, withErrUnsupportedAlgorithm. v0.10.0 returned errors that matched no sentinel. Since v0.12.0,jwt.Validatedecrypts a JWE when you give it decrypters. See Encrypted JWTs.- A time-claim refusal now matches
ErrMalformedClaim,ErrExpiredorErrNotYetValid, and its message has changed. If you match on the old text, such asexp claim is before current time, match witherrors.Isinstead.
These add to the API without changing what you already use:
jws.Verifyreturns the payload as octets, for a JWS whose payload is not a JSON object.jwk.Thumbprintcomputes the RFC 7638 thumbprint of a jwk.PublicFromJwk,PrivateFromJwk,PublicJwk,PrivateJwkandThumbprinthandleAKPkeys.SecretKey.Equalis reachable fromPublic(), so two HMAC validators can be compared, and the comparison runs in constant time.jwa.Ed25519,jwa.MLDSA44,jwa.MLDSA65andjwa.MLDSA87, each with a signer and a validator.JoseOptionsfields:HttpClient,FetchTimeout,MaxKeysTried,AcceptedTypes,RequireKeyIdentifier,UnderstoodCriticalHeaders,X509Roots,IgnoreKeyUse,X509ExtKeyUsagesandExpectedAudience. Each is off, or the documented default, when unset.- Error sentinels:
ErrExpired,ErrNotYetValid,ErrAudienceMismatch,ErrInvalidOptionsandErrTooManyKeys.
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.
| Was | Now |
|---|---|
go-jose/error |
go-jose/joseerror |
model.Algorithm, model.ES256 and the rest |
jwa.Algorithm, jwa.ES256 and the rest |
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
}| 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 |
- A validator for an HMAC algorithm can only be built from a signer.