Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท Tokens, JWT and OAuth

JWT Pitfalls and Best Practices

Avoid the classic JWT mistakes: alg none, algorithm confusion, long expiry and no revocation. Verify RS256 tokens with key pairs and a denylist in Node.js.

JWTs are easy to create and easy to get wrong. Most real-world JWT breaches come from the same handful of mistakes: trusting the token's own header, accepting tokens that never expire, or having no way to cancel a stolen token. Libraries fix many of these by default, but you should understand each one so you can configure them correctly and review code that uses them.

This lesson builds on JSON Web Tokens (JWT) Explained. You will break a naive verifier, switch to asymmetric keys with RS256, and add a revocation list.

Five JWT mistakes

alg none Token picks no signature.
Alg confusion RS256 key used as HS256 secret.
No expiry A leaked token works forever.
No revocation Logout changes nothing.

Each one has a simple fix.

1 / 2

Pitfall 1: trusting the header

The header says which algorithm signed the token. If your verifier believes it, an attacker chooses the rules. The standard includes alg: "none", meaning "unsecured token, no signature". A naive verifier that obeys the header accepts a token the attacker wrote entirely themselves.

Node.js The alg none attack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fix is to give your verification function a fixed list of allowed algorithms and ignore everything the header says about the algorithm. Good libraries make you pass algorithms: ['HS256'] or similar. Always pass it.

Pitfall 2: algorithm confusion

With RS256 the issuer signs with a private key and everyone verifies with the public key, which is not secret. If a verifier accepts both RS256 and HS256 and passes "the key" to whichever algorithm the header names, an attacker can pick HS256 and sign the token using the public key text as the HMAC secret. The verifier then checks it with the same public key and accepts the forgery. Pinning one algorithm per key blocks this attack too.

Asymmetric keys with RS256

Use a key pair when other services verify your tokens. node:crypto can generate one and sign with it. A fresh key pair is random, so the printed token differs on each run, but the results (valid, forged) do not.

Node.js Sign and verify with RS256

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The kid (key ID) header tells verifiers which public key to use. That lets you rotate keys: publish the new key, start signing with it, and keep the old one around until old tokens have expired. Issuers usually publish their public keys as a JSON Web Key Set (JWKS) at a well-known URL.

Pitfall 3: tokens that live too long

Because a JWT is verified without asking anyone, a stolen token is valid until exp. So keep access tokens short, typically 5 to 15 minutes, and renew them with a refresh token (next lessons).

Also validate every claim your API relies on:

  • exp and nbf, with a small leeway (for example 30 seconds) because server clocks drift.
  • iss, so you only accept tokens from your own auth service.
  • aud, so a token meant for the billing API cannot be replayed against the notes API.

Pitfall 4: no revocation

A stateless token cannot be cancelled on logout, password change or account compromise. You have three options, in rising cost:

  1. Rely on short expiry only. Simple, and fine for low-risk APIs.
  2. Keep a denylist of revoked jti values (or a per-user "tokens valid after" timestamp) in a fast store such as Redis. Entries need to live only until the token's exp.
  3. Use opaque tokens that are looked up in a database on every request. You give up statelessness and gain instant control.
Node.js Revocation with a jti denylist

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The denylist only needs to remember a token until it would have expired anyway. That keeps it small.

Where the client stores a token

Place Risk Notes
localStorage Any script on the page (XSS) can read it Convenient, but exposed
JavaScript memory Lost on reload Safest from theft, needs a refresh on load
HttpOnly; Secure; SameSite cookie Scripts cannot read it; needs CSRF thought Common choice for browser apps and refresh tokens

For mobile apps use the platform's secure storage (Keychain, Keystore). The cookie flags are covered in CORS and Security Headers.

A JWT checklist

  • Pin the allowed algorithm; never accept none.
  • Use a long random secret (32+ bytes) for HS256, or a key pair for RS256/ES256.
  • Set exp (minutes), and validate exp, nbf, iss and aud.
  • Keep the payload small and free of secrets.
  • Plan revocation: short life plus a denylist or a "valid after" timestamp.
  • Rotate keys with kid.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes the alg none attack work?

    If the verifier obeys the header, an attacker can declare that no signature is needed. Pin the algorithm on the server.
  2. 2. Which key does an API need to verify RS256 tokens?

    The private key signs and stays with the issuer. The public key verifies and can be shared widely.
  3. 3. Why check the aud claim?

    Audience says which service the token is meant for. Services should reject tokens addressed to someone else.
  4. 4. What is the cheapest way to limit the damage of a stolen access token?

    A short exp means a stolen token stops working after minutes. Combine it with refresh tokens and a denylist where needed.
  5. 5. How long does a revoked jti need to stay in the denylist?

    After exp the token is rejected anyway, so the entry can be removed.

Summary

  • Never let the token's header choose the algorithm; pin it on the server and reject none.
  • Algorithm confusion is avoided by one algorithm per key.
  • RS256 or ES256 let many services verify tokens without being able to forge them; use kid to rotate keys.
  • Keep access tokens short-lived and validate exp, nbf, iss and aud with a small leeway.
  • Stateless tokens cannot be cancelled by themselves; use short life, a jti denylist, or opaque tokens.
  • Store tokens where scripts cannot easily steal them.

Next: Access Tokens and Refresh Tokens