JWT Security Best Practices: From Algorithms to Storage

What this article answers

Three things only: the conditions under which attacks succeed, why common defences fail, and the minimum viable control at each point. For JWT structure and verification order, see the JWT parsing and verification guide; this piece does not repeat them.

1. Algorithms: pin them on the verifying side

Why alg: none works

The JWT header is attacker-controlled JSON, and alg is just one field in it. If the server "reads the header, then picks a verification path from alg", the attacker chooses the lock. An alg:none token has an empty third segment; early libraries accepted it outright. Modern libraries reject it by default, but an explicit allow-list remains the only dependable defence — library defaults change across versions and wrappers, your configuration does not.

// Dangerous: the token decides the algorithm
jwt.verify(token, secret);

// Safe: the server decides
jwt.verify(token, publicKey, { algorithms: ['RS256'] });

Algorithm confusion: the public key becomes an HMAC secret

Two conditions must hold: the verification code accepts multiple algorithms, and the same key material can serve both asymmetric verification and HMAC. The attacker rewrites the header as HS256 and re-signs using the public key bytes as the HMAC secret. If the server complies, it runs an HMAC check keyed with something everyone possesses — any identity can be forged.

Pin the algorithm and the key type together: when verifying RS256, accept only an RSA public key, and never route that key into an HMAC path. The allow-list must also govern key sources: kid is a dictionary lookup only, never concatenated into a file path or SQL; ignore jku / x5u in the token and load keys solely from local config or a pinned JWKS endpoint.

Key strength and rotation

For HS256 the key is the entire defence: at least 256 bits of random bytes, never a passphrase or anything guessable. RS256 needs at least 2048 bits (3072 preferred); EdDSA is fine at 255 bits.

# 32 random bytes
openssl rand -base64 32

# RSA key pair
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem

# Ed25519 key pair
openssl genpkey -algorithm Ed25519 -out private.pem
openssl pkey -in private.pem -pubout -out public.pem

Rotation runs through JWKS: publish the public key set, let kid select one, verify against old and new during the transition, and retire the old key after the longest token lifetime. Swapping keys in one shot invalidates every token in flight.

2. Expiry and revocation

A short lifetime is the only cheap containment

exp is not optional. After issuance there is no built-in revocation before expiry, so a leak's blast radius equals its remaining lifetime: keep access tokens around 15 minutes, refresh tokens at 7–30 days, ID tokens at 5–10 minutes.

Three revocation strategies

Strategy Implementation Effect delay Cost
Short lifetime Config change ≤ access-token lifetime More refresh traffic
Deny-list (jti) Redis holding revoked, not-yet-expired ids Immediate Reintroduces state
Version number (token_version) A user column embedded in the payload and compared on verify Immediate One lookup per verification (cacheable)

A deny-list stores only unexpired jti values with a TTL of exp - now, so entries disappear on their own and storage tracks active revocations rather than lifetime history. Compliance scenarios that need "log this person out now" justify it; everything else is fine with short lifetimes plus a version column.

The version-column approach has a hidden cost: if you cache the version to skip a lookup, revocation latency equals the cache TTL. Either accept that delay or invalidate the relevant cache entry on password change and account suspension — otherwise "instant revocation" exists only in the design doc.

3. Refresh token rotation and reuse detection

Every refresh exchange issues a new refresh token and retires the old one. The value is not a vague "more secure" but reuse detection: a retired refresh token showing up again means it was copied — revoke the whole token family and force re-authentication.

async function refresh(refreshToken) {
  // 1. Verify the Refresh Token signature and expiry
  const payload = jwt.verify(refreshToken, publicKey, {
    algorithms: ['RS256']
  });

  // 2. Check the revocation list (needs Redis or similar)
  const isRevoked = await redis.get(`revoked:${payload.jti}`);
  if (isRevoked) {
    // Reuse detected -> revoke the entire token family
    await revokeTokenFamily(payload.family_id);
    throw new Error('Token reuse detected');
  }

  // 3. Add the current Refresh Token to the revocation list
  await redis.setex(`revoked:${payload.jti}`, payload.exp - now, '1');

  // 4. Issue a new Access Token and Refresh Token
  const newAccess = signAccessToken(payload.sub);
  const newRefresh = signRefreshToken(payload.sub, payload.family_id);

  return { accessToken: newAccess, refreshToken: newRefresh };
}

Concurrency is where this breaks. Two browser tabs refreshing at once will spend the same refresh token twice. If "check revoked" and "mark revoked" are not atomic, you either raise a false leak alarm or let both requests succeed with two live tokens. Guarantee a single winner with Redis SET NX, a Lua script, or a database row lock.

family_id groups every refresh token derived from one login; on reuse, revoke the group rather than the single token.

Know its limit too: reuse detection is after-the-fact discovery, not prevention. An attacker who spends a stolen refresh token before the legitimate user gets one exchange succeeds; containment still depends on short access lifetimes and family revocation.

Proactive revocation: on logout, password change, or anomaly detection, write the refresh token's jti to the deny-list. The allow-list alternative (tracking each user's valid tokens) costs more storage; deny-lists are the usual choice.

4. Storage: how each option fails

Option How an attacker gets it Cost
localStorage Any same-origin script reads it; one XSS takes it whole None
HttpOnly cookie Script cannot read it, but the browser attaches it automatically; CSRF defence required An over-broad domain exposes it to subdomains
In-memory variable Gone on reload, so the window is tiny An extra exchange on every reload

Recommended split: access token in memory, refresh token in an HttpOnly + Secure + SameSite cookie. XSS reaches only the short-lived access token and never the refresh token; SameSite plus a CSRF token covers forgery.

Set-Cookie: refresh_token=...; HttpOnly; Secure; SameSite=Strict; Path=/refresh; Max-Age=2592000

Native apps are outside the same-origin model: keep tokens in the iOS Keychain or Android Keystore and protect the refresh token with biometrics. Never use UserDefaults or SharedPreferences — plaintext on disk.

Cookies carry another frequently missed failure point: setting Domain to .example.com sends the token to every subdomain, so one compromised subdomain leaks it. Omit Domain and let the cookie stay on its own host.

5. XSS / CSRF: how they amplify JWT risk

XSS decides whether the storage choice still matters: a token in localStorage is read by any injection; in an HttpOnly cookie it cannot be read, but the attacker can still act as the user, rewrite the DOM, and phish. HttpOnly downgrades theft to impersonation — output encoding and CSP are still mandatory, covered in the XSS prevention guide.

CSRF threatens only cookie schemes that carry credentials automatically. SameSite=Strict is safest but drops login state when users arrive from external links; Lax is the common compromise. SameSite does not cover everything: a compromised sibling subdomain is still same-site, so state-changing endpoints still need a CSRF token or double-submit check.

6. Everything else

Minimise claims

Put only what is necessary in the payload. It is Base64-encoded, readable by anyone:

// Dangerous
{ sub: '123', password: 'abc123', creditCard: '4111...' }

// Safe
{ sub: '123', role: 'user' }

Verify every claim

Checking the signature but not iss / aud accepts tokens issued elsewhere for another service that shares the same key; with multi-tenancy or a shared key pool, that is a direct privilege bypass.

jwt.verify(token, publicKey, {
  algorithms: ['RS256'],
  issuer: 'https://auth.example.com',
  audience: 'https://api.example.com'
});
// The library checks exp, nbf, and iat for you

jti against replay

Give every token a unique jti; record consumed ids for sensitive operations (again, only until exp), and a captured request can no longer be replayed.

Redact tokens from logs

A full token in a log writes credentials to disk and to every log aggregator downstream:

console.log(`Auth: ${token}`);                    // Wrong
console.log(`Auth: jti=${payload.jti}, sub=${payload.sub}`); // Right

Reproducible results

The alg=none token, hand-built in thirty seconds — seeing it explains why an allow-list is mandatory:

import base64, json
def b64url(o): return base64.urlsafe_b64encode(json.dumps(o, separators=(',', ':')).encode()).decode().rstrip('=')
header, payload = b64url({"alg": "none"}), b64url({"sub": "1", "role": "admin"})
token = f"{header}.{payload}."
print(token)
# → eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIiwicm9sZSI6ImFkbWluIn0.

The header decodes to {"alg":"none"} with no signature segment at all. A server that "reads alg from the header and follows it" accepts this token and grants admin. To experiment safely, mint test tokens with the token generator; to inspect any token, paste it into the JWT parser and check its alg against your allow-list first.

Frequently Asked Questions

Where should I store a JWT? Is localStorage acceptable?

Do not use localStorage. Any same-origin JavaScript can read it, so a single XSS hole hands the token straight to an attacker. The recommended split: keep the Access Token in memory (a JS variable) and the Refresh Token in an HttpOnly + Secure + SameSite=Strict cookie. XSS can then only reach the short-lived Access Token and never the Refresh Token, while SameSite blocks CSRF. Native apps should use the iOS Keychain or Android Keystore — never UserDefaults or SharedPreferences, which store values in plaintext.

Why can't a JWT be revoked after issuance, and what do I do about it?

JWTs are stateless: the server keeps no record of what it issued, and verification relies only on the signature plus exp. There is therefore no built-in revocation before expiry — maintaining a denylist defeats the point of statelessness by reintroducing server-side state. The standard answer is short lifetimes plus a Refresh Token: the Access Token lives 15 minutes so a leak is contained, while the Refresh Token is server-side and can be denylisted on demand (logout, password change, anomaly detection writes its jti to Redis). For genuinely high-risk operations that need instant invalidation, add an extra server-side check on top.

What is refresh token rotation, and why bother?

Every time a Refresh Token is exchanged for a new Access Token, also issue a fresh Refresh Token and immediately invalidate the old one, so each Refresh Token is single-use. The payoff is reuse detection: if an attacker steals a Refresh Token that has already been used, their attempt to reuse it tells the server the token was compromised, so it can revoke that user's entire token family and force re-authentication. Without rotation, a stolen Refresh Token keeps working silently for its whole lifetime.

What are the alg: none and algorithm confusion attacks?

Both come from the same root cause: the server trusting the alg field in the token header. With alg: none, the attacker crafts a token declaring that it is unsigned (early libraries accepted these outright). With algorithm confusion, they rewrite an RS256 token as HS256 and re-sign it using the public key as the HMAC secret — if the server does not pin the algorithm, it runs an HMAC check with a key that is public by definition, so any identity can be forged. One fix covers both: state the expected algorithm explicitly at verification time and never trust alg from the header.

← Back to Blog