Algorithm confusion happens when a verifier trusts the token header's alg value. An attacker switches RS256 to HS256 and signs with the public key, or sets alg to none, and a permissive library accepts the forgery. Fix it with a server-side algorithm allowlist, key-type binding, full claim validation, and a pinned JWKS.
- The alg header is attacker-controlled input, not a trusted instruction; choose the algorithm from server configuration.
- Allowlist exact algorithms per issuer, reject none, and never pass a public key where an HMAC secret is expected.
- Bind key type to algorithm: RSA for RS and PS, EC P-256 for ES256, OKP Ed25519 for EdDSA, and a random 32-byte secret for HS256.
- Validate iss, aud, exp, nbf, and iat with a small clock skew; decoding a JWT proves nothing about its authenticity.
- Treat kid, jku, x5u, and embedded jwk as untrusted; resolve keys from a pinned JWKS and rotate with an overlap window.
Every JWT vulnerability that matters starts with a verifier believing something the token says about itself. The alg header is the most dangerous example: a one-word instruction inside attacker-controlled data, and too many libraries follow it. Change RS256 to HS256, sign the token with the server's RSA public key, and an old or hand-rolled verifier may accept a token the attacker wrote. Set alg to none, drop the signature, and a smaller but real set of implementations will do the same.
Algorithm confusion is not a break of SHA-256, RSA, or ECDSA. It is a key-type and configuration failure: the verifier lets the token choose the lock, then hands it the wrong key. The fix is unglamorous: choose algorithms on the server, bind key types to them, and validate claims only after the signature passes.
The compact JWS format, byte for byte
A compact JWS has three base64url segments separated by dots: header.payload.signature. The header is JSON with alg, typ, and usually kid. The payload is the JSON claims set. The signature is the base64url encoding of the raw signature bytes.
The signature is computed over the ASCII bytes of BASE64URL(header) + "." + BASE64URL(payload) β the exact text before the second dot, not the parsed JSON. A verifier must not decode, edit, and re-serialize the payload before checking the signature; key order, whitespace, and number formatting all change the bytes. Duplicate JSON keys also create parser differentials, so reject duplicate members or use a strict parser.
Base64url uses - and _ instead of + and /, and omits = padding. Decoders may accept missing padding; encoders must omit it. The JWT decoder shows the header and claims of a token you already have, but it does not verify anything.
Two header parameters deserve suspicion. crit lists extensions the verifier must process; ignoring it lets b64: false (RFC 7797) tokens be interpreted differently. Embedded keys (jwk), key URLs (jku, x5u), and certificate chains (x5c) are attacker-controlled header data. A JWE has five segments, not three; do not feed one to a JWS verifier.
Algorithm families: HMAC, RSA, RSA-PSS, ECDSA, and EdDSA
JWA (RFC 7518) registers a small set of algorithms, and each family has different key material, signature encoding, and failure modes.
| Family | Algorithms | Key type | Signature form | What verification requires |
|---|---|---|---|---|
| HMAC | HS256, HS384, HS512 | Shared secret (oct) | Raw MAC, 32/48/64 bytes | The same secret on both sides; at least as many key bits as the hash output |
| RSA PKCS#1 v1.5 | RS256, RS384, RS512 | RSA private/public | PKCS#1 v1.5, key size at least 2048 bits | The issuer's public key; deterministic padding |
| RSA-PSS | PS256, PS384, PS512 | RSA private/public | PSS with MGF1 and salt length equal to the hash | A PSS-aware verifier; some old stacks only do PKCS#1 v1.5 |
| ECDSA | ES256, ES384, ES512 | EC P-256, P-384, P-521 | Fixed-width `R | |
| EdDSA | EdDSA (Ed25519, Ed448) | OKP | Ed25519 or Ed448 signature | The matching OKP key; no separate hash parameter |
| None | none | No key | Empty signature | Nothing β which is exactly why it must be rejected |
Three details cause incidents. HS256 needs at least 256 bits of entropy; a passphrase is not a key. ES256 signatures in JWS are the fixed-width concatenation R || S, while many crypto libraries output DER, so careless converters either reject valid tokens or accept malformed ones. PS256 uses a salt length equal to the hash length; a verifier configured differently rejects valid tokens, which tempts teams to disable checks.
Why trusting the token's alg enables confusion
The verifier must answer one question: was this exact byte string signed by the key I trust for this issuer? The algorithm belongs to that trust decision, not to the token's identity. When a library reads alg from the header and selects a primitive, the attacker chooses the lock; when the same key material is passed to that primitive, the attacker also chooses how the key is interpreted.
The classic exploit targets RS256 verification with an RSA public key. The attacker decodes the header, replaces RS256 with HS256, computes HMAC-SHA256 over the new signing input using the issuer's public key bytes as the secret, and appends the MAC. Public keys are published in JWKS, TLS certificates, and source repositories; they are not secrets. If the verifier feeds the public key to an HMAC implementation, the MAC matches and the forgery is accepted. The same trick works with PS256 or ES256 replaced by HS256, and with the key supplied as a JWK string or DER buffer instead of PEM.
import jwt from "jsonwebtoken";
// Vulnerable: no algorithms allowlist. The library is free to follow the
// token's alg header, and the same PEM key is handed to every verifier.
// An HS256 token HMAC-signed with the public key text can be accepted.
export function verifyVulnerable(token, publicKeyPem, issuer) {
return jwt.verify(token, publicKeyPem, { issuer });
}
Modern releases narrowed this behavior, but the pattern survives in older versions, other ecosystems, and wrappers that map header.alg to a crypto call. Keep one regression test in every repository: sign an HS256 token with the text of your RSA public key and assert that verification fails.
alg:none and key-type confusion in practice
alg: none is the unsecured JWS mode: the signature segment is empty. A verifier that accepts it verifies nothing, which is correct only in a test harness that deliberately wants an unsigned token. Implementations have accepted none, None, NONE, and mixed-case variants, sometimes only when no key was configured, sometimes when a wrapper mapped unknown algorithms to a no-op. Do not blacklist spellings; require the header algorithm to be a member of a small allowlist that never contains none.
Key-type confusion is broader than HS256 versus RS256. An RSA key presented to an ECDSA verifier should fail, but code that catches the exception and continues, or falls back to another key source, can turn a type error into an authentication bypass. The same risk appears when kid selects one key while the algorithm expects another: a resolver that returns "the key with this ID" without checking kty and crv has broken the binding.
History is clear. CVE-2015-9235 covered algorithm confusion in Node.js jsonwebtoken; CVE-2016-5431 covered php-jwt; CVE-2018-0114 covered node-jose accepting a key embedded in the token header. CVE-2022-21449, the Java "psychic signatures" bug, was different β ECDSA verification accepted r = 0, s = 0 β but it reinforces that verification code needs tests and updates. Use the JWT signer to generate tokens for both valid and forged fixtures.
Key selection: kid, JWKS, and algorithm binding
kid is a hint for choosing among keys, chosen by whoever created the token. It is not a trust anchor. Two issuers can use the same kid for different keys, so lookups must be scoped by issuer. A safe design loads a JWKS from a configured, allowlisted HTTPS URL per issuer, indexes keys by kid, and selects only from that set. The token never supplies the URL.
A JWK carries kty (RSA, EC, OKP, oct), optional use, key_ops, and alg, plus key material such as n/e, crv/x/y, or k. Enforce use and key_ops when present: a key marked for encryption must not verify signatures. Check kty and crv against the algorithm β RSA for RS and PS, EC with P-256 for ES256, OKP with Ed25519 for EdDSA, oct for HS256 β and if the JWK names alg, require equality with the token's algorithm.
Never trust jku, x5u, jwk, or x5c as key sources. The first two are token-supplied URLs, which makes them an SSRF and key-substitution primitive at once; the last two let the token carry its own key or chain. A general-purpose API should ignore all four unless the issuer documents and pins them. If you use x5c, validate the chain to a pinned trust root and check key usage.
kid also reaches logs and errors. Validate its length and character set, never concatenate it into a path, SQL, shell command, or URL, and never let an unknown value trigger an unbounded search.
Safe verification with an explicit allowlist
Safe verification is explicit. The server decides which algorithms it accepts per issuer, which key types are legal for each, and which claims are required. The token supplies data, never policy.
- One allowlist per issuer and token type, for example
["RS256"]or["ES256", "EdDSA"]. During a migration, allow old and new values for a bounded window. - Never include
none, and never compute the allowlist from the header. - Check key type before verification, not after.
- Verify the signature first, then validate claims. Never authorize on claims from an unverified token.
- Return a generic 401 to clients and a detailed reason code to logs.
The example below uses jose, a maintained JavaScript library that applies the allowlist before verification, resolves keys through a cached JWKS, and validates registered claims.
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";
const issuer = "https://auth.example.com/";
const audience = "https://api.example.com/orders";
const jwks = createRemoteJWKSet(new URL(`${issuer}.well-known/jwks.json`), {
timeoutDuration: 3_000, // never let a slow JWKS host hang a request
cooldownDuration: 30_000, // rate-limit refetches after an unknown kid
cacheMaxAge: 600_000
});
export async function verifyAccessToken(token: string): Promise<JWTPayload> {
const { payload, protectedHeader } = await jwtVerify(token, jwks, {
issuer,
audience,
algorithms: ["RS256", "ES256"], // explicit allowlist: never "none"
clockTolerance: 30,
maxTokenAge: "15m",
requiredClaims: ["sub", "exp", "iat", "iss", "aud"]
});
// The library has verified the signature and the claims above.
// Authorization still belongs here: scopes, roles, tenant, resource.
if (typeof payload.sub !== "string" || payload.sub.length === 0) {
throw new Error("missing subject");
}
return payload;
}
If you resolve keys yourself, implement assertKeyType(jwk, alg) and refuse mismatches with the same error used for an unknown key. If a library accepts a key callback, return exactly one key type and let exceptions fail closed. Never catch a verification error and try a weaker path.
Claims validation: iss, aud, exp, nbf, iat, and skew
A valid signature proves who signed the token, not that the token is for you. Claim validation turns a signed assertion into an authorization decision.
Issuer (iss). Compare against a configured string for the tenant, not against a value from the token. A trailing slash is a different issuer. In multi-tenant systems, resolve the tenant from a trusted route or host, then compare iss to that tenant's expected issuer; never let the token choose which tenant's keys to use.
Audience (aud). Require your own audience. aud may be a string or an array, and the check must handle both. A token minted for https://api.example.com/billing must not be accepted by the orders API. This is the main defense against token reuse across services.
Expiration (exp). Require exp for access tokens; a token without it never expires. It is a NumericDate in seconds, not milliseconds, compared with the verifier's clock. Reject when now >= exp + tolerance.
Not before (nbf) and issued at (iat). Reject a token used before nbf minus tolerance. Treat iat in the future beyond tolerance as suspicious. With exp, iat also supports a maximum age check.
Clock skew. Allow 30 to 60 seconds, apply it to exp and nbf, keep it bounded, and monitor observed drift. A tolerance of hours is equivalent to disabling expiry.
Token type. ID tokens, access tokens, and refresh tokens are not interchangeable. Check typ when set (RFC 9068 defines at+jwt) and purpose claims such as token_use or scope. Cross-token confusion turns a benign login flow into an authorization bypass.
Authorization comes after all of this: scopes, roles, tenant ownership, and resource checks. A valid JWT is an identity assertion, not a permission slip.
Decode is not verify: weak secrets, kid injection, and JWKS SSRF
Decoding is a parser operation. It proves nothing. Any three-segment base64url string can decode into plausible JSON, and anyone can edit the payload and re-encode it. A debug endpoint that returns decoded claims is fine; an authorization decision based on them is not. The HMAC generator reproduces an HS256 signature during debugging and shows how quickly a weak secret can be tested offline.
That offline test is the other half of the HMAC problem. If HS256 uses a human-chosen secret, one captured token lets an attacker brute-force the key without touching your servers. Hashcat mode 16500 (hashcat -m 16500 -a 0 token.txt wordlist.txt) tests candidate secrets against a JWT. Secrets based on passwords, product names, or short random strings fall quickly. Use at least 32 bytes from a CSPRNG, store them in a KMS or secret manager, use one secret per environment, and rotate on a schedule.
kid injection has the same root cause: untrusted data used as an instruction. If code builds keys/${kid}.pem, a kid of ../../etc/passwd is path traversal. If kid is concatenated into SQL, it is SQL injection; if passed to a shell, command injection. Use kid only as a lookup key in a preloaded in-memory map, cap its length, restrict its character set, and reject unknown values.
JWKS fetching adds a network attack surface. If the server fetches a URL from jku, x5u, or a kid-derived path, an attacker can target http://169.254.169.254/latest/meta-data/, an internal admin panel, or a database port; even a failed fetch leaks timing and errors. Fetch only allowlisted issuer hosts over HTTPS, block redirects to non-allowlisted hosts, resolve DNS with checks for loopback, private, link-local, and unique-local addresses, and add a short timeout, a size cap, and an egress firewall.
Finally, a JWS is signed, not encrypted. Its header and payload are readable by anyone who sees the token: browsers, proxies, logs, crash reports, and support tickets. Never put passwords, API keys, full personal records, or internal identifiers into a JWT. If claims must stay confidential, use JWE or an opaque token backed by a server-side lookup.
JWKS rotation, caching, and failure modes
Key rotation is where algorithm choices meet operations. A safe rotation publishes the new public key before the first token signed with it, keeps the old key until every token signed with it has expired, then removes it. The overlap must cover the maximum token lifetime plus clock skew plus the JWKS cache TTL; a one-hour access token with a ten-minute cache needs more than seventy minutes.
Emergency rotation is different. If a private key leaks, remove the public key immediately, but understand that JWKS only affects future verification. Tokens already issued with the compromised key remain valid until they expire unless you also maintain a token version, a jti deny list, or short lifetimes that bound the damage.
Cache JWKS boundedly. Honor Cache-Control and enforce a maximum TTL, such as ten minutes. On an unknown kid, refetch at most once per cooldown, such as thirty seconds; otherwise random kid values force a fetch per request. Negative-cache unknown keys briefly, and never let a refresh block every request: refresh in the background or shed load.
Failure behavior must be explicit. If the endpoint is unavailable and the key is not cached, fail closed with 503 or 401 rather than falling back to decode-only. If the key is cached, keep verifying until expiry, then fail closed. Alert on fetch errors, unknown-kid rate, key age, and verification failure reasons; a sudden rise in unknown-kid errors is a bot or a botched rotation.
Namespace cached keys by issuer and kid; never share a key cache between tenants. Log the issuer, kid, and algorithm on failures, but not the token.
Verification checklist and pass criteria
Use this list as a code-review checklist and a test plan. Each item has an automatable pass criterion.
| Check | Pass criterion |
|---|---|
| Algorithm allowlist | Verification accepts only the exact algorithms configured for the issuer; none is never allowed |
| Public key used as HMAC secret | An HS256 token signed with the RSA public key text is rejected with a signature or key-type error |
| Unsecured token | Tokens with alg set to none, None, or NONE, and an empty signature, are rejected |
| Key-type binding | A key whose kty or crv does not match the algorithm is rejected before verification |
| Unknown kid | Returns 401; at most one JWKS refetch per cooldown; malformed or oversized kid is rejected |
| Claims | iss and aud match configuration exactly; exp, nbf, and iat are enforced with bounded skew |
| Weak secrets | HS256 secrets are at least 32 random bytes, stored outside source control, and rotated |
| JWKS egress | Only allowlisted HTTPS hosts are fetched; redirects, private IPs, and metadata endpoints are blocked |
| Decode-only paths | No authorization decision is made from decoded but unverified claims |
| Rotation drill | New key verifies new tokens; old key verifies old tokens during overlap; removed key fails |
A verifier passes when every forged token above returns 401, the error response leaks no key material or token contents, and a valid token from the expected issuer and audience still authenticates. Run the forged-token suite in CI, not just before a release, because library upgrades and small refactors are exactly when the allowlist disappears.
The final rule is simple: the token may describe who the user is, but it never gets to choose how it is verified.
Frequently asked questions
What is a JWT algorithm confusion attack?
The verifier reads alg from the untrusted header and uses the same key material for a different algorithm. The classic exploit changes RS256 to HS256 and HMAC-signs the token with the public key, which the server then accepts as a valid HMAC secret.
Does alg:none still work against modern libraries?
Rarely by default, but it survives in hand-rolled verifiers, older releases, and wrappers that pass the header's algorithm to a generic crypto call. Always pass an explicit allowlist and keep a negative test with an empty signature.
Can I use HS256 for an API that many services verify?
Only if every verifier is trusted with the same secret. Prefer RS256, PS256, ES256, or EdDSA when multiple parties verify tokens, because they hold only the public key. If you use HS256, generate at least 32 random bytes and store the secret in a KMS or secret manager.
Is a JWT encrypted?
No. A JWS JWT is only signed: the header and payload are base64url-encoded and readable by anyone who holds the token. Use JWE or opaque tokens when the claims must stay confidential, and never put secrets or unnecessary personal data in a JWT.
How should I rotate JWT signing keys?
Publish the new public key in JWKS before signing with it, keep the old key until every token it signed has expired plus clock skew, then remove it. Cache JWKS with a bounded TTL and rate-limit refetches triggered by unknown kid values.
JsonMind guides are written and reviewed by the engineering team. We check each guide against the relevant RFC or vendor documentation, link the primary sources, and update the guide when behavior changes.
Primary sources are linked at the end of each guide.