Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js JWT invalid signature: JWKS Rotation and Clock Skew

One message covers three bugs: the wrong key type for RS256 or ES256, a JWKS cache that never refreshes after a kid rotation, and a clock that drifted.

~5 min readNode.js
#Node.js#JWT#Authentication#Security
3D illustration of a keyring of rotating signing keys above a token slab, one key ghosted as rotated, a clock node showing skew

Introduction & Quick Summary

Symptom. jsonwebtoken throws JsonWebTokenError: invalid signature on tokens that the identity provider itself reports as valid, and it starts suddenly on a Friday with no deploy. Or TokenExpiredError: jwt expired appears for a token whose exp is two minutes in the future. Or verification works for HS256 in development and fails for every RS256 token from the real issuer.

Cause. Three separate mistakes produce the same message. The verification key is wrong for the algorithm — a shared secret for an RS256/ES256 token, a PEM string where a JWKS key object is needed, or a PKCS#1 key where PKCS#8 is expected. The key is stale — providers rotate signing keys, kid changes, and a process that fetched the JWKS once at startup keeps verifying against a key that no longer signs. Or the clock differs — exp and nbf are compared against local time, and a container a few minutes ahead rejects fresh tokens.

Fix. Verify with a remote JWKS that refreshes on an unknown kid instead of caching forever, pin algorithms to exactly what the issuer uses, pass clockTolerance for real-world clock drift, and make sure the key material's format matches the algorithm.

Core Mechanics, Signatures & Reproducible Setup

A JWT carries the key id in its header, and verification must select the key by that id rather than by position.

js
// decoded header of a token that fails with "invalid signature" { alg: "RS256", kid: "d2VpcmQ6a2V5OjE", typ: "JWT" }
js
import { createRemoteJWKSet, jwtVerify } from "jose"; const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json")); export async function verify(token) { const { payload, protectedHeader } = await jwtVerify(token, JWKS, { issuer: "https://auth.example.com/", audience: "https://api.example.com", algorithms: ["RS256"], // pin it; never accept what the header claims clockTolerance: 60, // seconds of allowed skew }); return payload; }

createRemoteJWKSet caches keys, refetches when it sees a kid it does not hold, and applies a cooldown so a burst of unknown tokens triggers one fetch rather than thousands. That is the behaviour that makes rotation invisible; a hand-rolled fetch at boot has none of it.

Reproduce the signature failure with a mismatched key pair:

js
import jwt from "jsonwebtoken"; const token = jwt.sign({ sub: "u1" }, "secret-a", { algorithm: "HS256" }); jwt.verify(token, "secret-b"); // JsonWebTokenError: invalid signature jwt.verify(token, "secret-a", { algorithms: ["HS256"] }); // ok

Same code, one character in the key. The message never says which of the two inputs was wrong, which is why the algorithm and key format have to be checked together.

Key Comparison Table

AlgorithmKey materialCommon wrong inputLibrary support
HS256shared secret, ≥ 32 bytesa public key pasted as a secretjsonwebtoken, jose
RS256RSA public key, PEM SPKIPKCS#1 BEGIN RSA PUBLIC KEYboth
PS256RSA public keyverified as RS256both
ES256EC P-256 public keyDER signature instead of raw R||Sboth
EdDSAEd25519 public keyNode's crypto key object misusejose, jsonwebtoken 9+
SymptomLikely causeCheck
invalid signature on every tokenwrong algorithm familyheader alg vs key type
invalid signature after weeksJWKS cache never refreshedkid in header vs keys held
invalid signature on one issuer onlywrong audience/issueriss and aud claims
jwt expired on a fresh tokenclock skewdate -u in the container
invalid algorithmalgorithms pinned too narrowallow exactly the issuer's set
secretOrPublicKey must be providedenv var empty in that podconfig, not code

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Rotation with jsonwebtoken and jwks-rsa

If you keep jsonwebtoken, the JWKS client is a separate package, and its cache options are where rotation goes wrong:

js
import jwksClient from "jwks-rsa"; import jwt from "jsonwebtoken"; const client = jwksClient({ jwksUri: "https://auth.example.com/.well-known/jwks.json", cache: true, cacheMaxAge: 10 * 60 * 1000, // 10 minutes, not "forever" rateLimit: true, jwksRequestsPerMinute: 10, }); async function getKey(header) { const key = await client.getSigningKey(header.kid); // throws if kid unknown return key.getPublicKey(); } export async function verify(token) { const decoded = jwt.decode(token, { complete: true }); const key = await getKey(decoded.header); // refresh happens here return jwt.verify(token, key, { algorithms: ["RS256"], clockTolerance: 60 }); }

A cache that never expires is the classic cause of "it worked for a month". cacheMaxAge must be finite, and getSigningKey with an unknown kid must be allowed to reach the network.

2. jwt expired from clock skew

exp and nbf are integers of seconds since the epoch, compared with the verifier's clock. A container whose clock drifted 90 seconds ahead rejects every token for 90 seconds after issuance; a token with nbf set by a server behind by a minute is not yet valid anywhere.

js
jwt.verify(token, key, { clockTolerance: 60 }); // jsonwebtoken: seconds // jose: same name, same unit

clockTolerance widens the window in both directions and does not weaken the signature. Verify the skew itself with docker run --rm node:22 date -u against the host, and enable chrony or the platform's time sync — a tolerance is a buffer, not a fix.

3. ES256 signatures are not DER

ECDSA signatures in JOSE are the raw concatenation of R and S as fixed-width big-endian integers (64 bytes for P-256). Most non-JOSE libraries expect DER-encoded SEQUENCE { r, s }. Passing one into the other yields invalid signature with a mathematically valid signature.

js
// correct: let the JWT library do the conversion await jwtVerify(token, publicKey, { algorithms: ["ES256"] }); // wrong: hand-rolling with crypto.verify and DER assumptions crypto.verify("sha256", data, publicKey, signature); // returns false for JOSE sigs

The reverse migration — moving from jsonwebtoken to jose with the same key — also needs the key imported correctly: jose accepts a KeyObject, a PEM string, or a JWK, and silently treats a JWK for the wrong curve as a different key.

4. Rejecting alg: none and algorithm confusion

A verifier that trusts the header's alg can be told to use HS256 with the RSA public key as the HMAC secret — a public value — and forge tokens. algorithms is not optional.

js
jwt.verify(token, publicKey, { algorithms: ["RS256"] }); // reject everything else

The same applies in jose, where passing an array is required for symmetric and asymmetric keys to be distinguished safely. Never jwt.decode for authorisation: it parses without verifying.

5. aud and iss mismatches that read as signature failures

Two environments sharing one signing key but different audiences produce tokens that verify cryptographically and fail authorisation. Pin both, and include the trailing slash precisely.

js
jwt.verify(token, key, { algorithms: ["RS256"], issuer: "https://auth.example.com/", // trailing slash matters audience: "https://api.example.com", });

A token minted for aud: "https://app.example.com" will throw jwt audience invalid. expected: https://api.example.com, not a signature error — but a missing audience option means no check at all, and cross-service token reuse becomes an unnoticed hole.

6. Where to cache and where not to

Verifying a JWT on every request should cost microseconds, which means the JWKS lookup must not be a network call per request. Keep one JWKS client per process, refresh on unknown kid, and cap the cooldown. In serverless, module scope survives between invocations often enough to help, and a cold start pays one fetch.

Common Compilation/Runtime Mistakes & Version Gotchas

  • jsonwebtoken v9 removed implicit algorithm acceptance. A v8 call without algorithms start failing after the upgrade.
  • jwt.decode used for authorisation. It performs no verification and returns payload for anything.
  • secret from process.env that is undefined in one deployment. jsonwebtoken throws secretOrPublicKey must be provided; a spread of the same bug passes an empty string, which is worse.
  • A JWKS cache with no TTL. Rotation appears as a total auth outage on the next deploy.
  • PEM with literal \n from an environment variable. The key parses to garbage and verification fails with the same invalid signature.
  • HS256 secret shorter than the hash output. jose rejects it; jsonwebtoken accepts it, which is a silent weakness.
  • clockTolerance set in milliseconds. The option is seconds in both libraries; 60000 means sixteen hours of tolerance.

Related tools. Paste a failing token into the JWT decoder to read header.kid, alg, exp, and aud without verifying it, compare the JWKS document before and after a rotation with the JSON formatter, and convert the numeric exp to a readable date with the timestamp converter.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.