Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 4 min read

Rotating JWT Secrets Without Logging Everyone Out

Every team that rotates a JWT signing secret for the first time does it the same way: change JWT_SECRET, deploy, and watch the session graph fall off a cliff. New tokens sign fine, but every token issued before the deplo

Every team that rotates a JWT signing secret for the first time does it the same way: change JWT_SECRET, deploy, and watch the session graph fall off a cliff. New tokens sign fine, but every token issued before the deploy was signed with the old key, so verification fails at once. A JWT is only verified with the secret that signed it, so with exactly one secret in the system, changing it invalidates every token in flight. The fix people reach for is "put the old key back", which teaches the team that rotation is dangerous. It is not โ€” it just has an order.

The failure mode: signing before verifying

The way out is to stop having exactly one key. Keep two during a window, give each an id, and put that id in the token header, so a verifier can pick the key that signed the token. That id is the kid header from RFC 7515 (JWS). It travels in plain text and is a label, not a secret: a date such as "2026-11", never the key or its hash.

The four steps, in order

  1. Create the new key and store it next to the old one. Nothing user-visible changes.
  2. Deploy verifiers that accept both keys, so every service can resolve either kid.
  3. Switch signing to the new key. New tokens carry the new kid; older ones still verify.
  4. Retire the old key after the longest token lifetime plus clock skew, once logs show no old-kid traffic.

Flip signing before step 2 and new tokens hit services that only know the old key: the logout wave, spread over one deployment.

Node.js: a key ring instead of one secret

With jsonwebtoken 9, the keyid option writes the kid header:

const KEY_RING = {
  '2026-03': process.env.JWT_SECRET_2026_03,
  '2026-11': process.env.JWT_SECRET_2026_11,
};
const ACTIVE_KID = process.env.JWT_ACTIVE_KID || '2026-11';

const sign = (payload) => jwt.sign(payload, KEY_RING[ACTIVE_KID], {
  algorithm: 'HS256', expiresIn: '15m', keyid: ACTIVE_KID,
});

function verify(token) {
  const { header } = jwt.decode(token, { complete: true }) || {};
  if (!header || !KEY_RING[header.kid]) throw new Error('unknown kid');
  return jwt.verify(token, KEY_RING[header.kid], { algorithms: ['HS256'] });
}

Three details are load-bearing. algorithms: ['HS256'] stops a token from naming a weaker algorithm. Rejecting an unknown kid prevents a fallback loop over every key. And jsonwebtoken validates exp if present but does not require it, so check it exists.

Python: the same shape with PyJWT

KEY_RING = {
    "2026-03": os.environ["JWT_SECRET_2026_03"],
    "2026-11": os.environ["JWT_SECRET_2026_11"],
}

def verify(token):
    kid = jwt.get_unverified_header(token).get("kid")
    if kid not in KEY_RING:
        raise jwt.InvalidTokenError(f"unknown kid: {kid!r}")
    return jwt.decode(token, KEY_RING[kid], algorithms=["HS256"],
                      options={"require": ["exp", "iat", "sub"]})

get_unverified_header is safe because the header only selects a key; decode still checks the signature, and options.require turns a missing claim into a failure. Signing is the mirror image: jwt.encode(claims, KEY_RING[ACTIVE_KID], algorithm="HS256", headers={"kid": ACTIVE_KID}).

Size the new key before you rotate to it

The new secret must still meet RFC 7518 ยง3.2: an HMAC key at least as long as the hash output, so 32 bytes for HS256, 48 for HS384, 64 for HS512 โ€” 64, 96 and 128 hex characters, or 43, 64 and 86 unpadded Base64URL. Generate bytes, then encode; the first 32 characters of a longer hex string are 16 bytes, not 32.

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
python3 -c "import secrets; print(secrets.token_hex(32))"

If you store Base64URL, decode it on every service before signing. A signer that decodes and a verifier that uses the 43-character string as-is are using different keys, and the symptom is invalid signature on tokens that were just issued.

During the window: two variables, one source of truth

The keys are two environment variables plus JWT_ACTIVE_KID, injected like the original. Both stay out of git for the whole window; "temporarily committed" is how keys end up in history.

Pick the overlap from the token lifetime: 15-minute access tokens need roughly 30 to 60 minutes to cover the longest-lived token plus clock skew. Refresh tokens and server-side sessions need their own plan.

One constraint: a JWKS endpoint publishes public keys, and HMAC has no public half. If other teams verify your tokens themselves, sign with RS256 or ES256 and publish both public keys during the overlap. With HS256, only services holding the secret can verify.

Rollout checklist

  • [ ] New key generated at the right size, under a new variable name, never in git.
  • [ ] Key ring and kid handling deployed to every verifier, not just the API.
  • [ ] Both kid values verify in staging, with one token signed under each.
  • [ ] JWT_ACTIVE_KID flipped; new tokens carry the new kid.
  • [ ] 401s watched for one token lifetime; old kid traffic at zero.
  • [ ] Old value deleted everywhere: services, CI variables, secret-manager versions.
  • [ ] Next rotation on the calendar.

The one case with no overlap

If the secret may have leaked, skip the window. Deploy the new key as the only accepted key, accept the forced sign-ins, and rotate every copy of the value, because the old key is already in someone else's hands.

The longer version โ€” Vault and KMS patterns, rotation intervals, leak response โ€” is at Where to store a JWT secret and how often to rotate it. For a new key, the generator shows Hex, Base64 and Base64URL lengths next to the RFC minimum, and the Node walkthrough is at Generate a JWT secret in Node.js.

๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.