Context & Why: Six Months of JWT Incidents
We rolled out JWT authentication for our REST API about six months ago. The initial implementation looked fine on paper — tokens, signatures, expiry. What I didn’t appreciate at the time was how many ways JWT can go wrong if you don’t explicitly lock down the library’s defaults.
Three incidents shaped how I think about JWT security now:
- A penetration tester on our team bypassed authentication entirely using the None Algorithm trick — just changing
algin the header and stripping the signature. - We discovered our RSA-signed tokens were vulnerable to Key Confusion because the verification code didn’t enforce the expected algorithm.
- Stolen refresh tokens were being reused for days after a user “logged out” because we had no token invalidation mechanism.
None of these are exotic vulnerabilities. They’re well-documented, they’ve been around for years, and they’re all preventable. Twenty lines of carefully placed configuration closed all three. Here’s exactly what changed.
Installation: Setting Up a Hardened JWT Stack
Library choice matters here. Some older JWT libraries accept alg: none by default or don’t enforce algorithm whitelisting. For Python, use PyJWT version 2.x — the API changed significantly from 1.x, and the new version has better defaults:
pip install PyJWT[crypto]==2.9.0
On the Node.js side, jsonwebtoken is the standard choice — but pair it with jose for stricter algorithm enforcement:
npm install jose@5
Secret and key quality matters as much as library choice. I use the password generator at toolcraft.app/en/tools/security/password-generator for server secrets — it runs entirely in the browser, so no data is ever sent over the network. For HS256, generate at least 256 bits (32 bytes of random hex). For RS256, generate a 2048-bit RSA key pair:
# Generate RSA key pair for RS256
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem
Store private keys outside the web root with permissions set to 600. If you’re on Linux, run the service under a dedicated user and restrict key access with filesystem ACLs.
Configuration: Closing the Three Main Attack Vectors
Blocking the None Algorithm Attack
The None Algorithm attack works because the JWT spec originally permitted alg: none for “unsecured” tokens. An attacker modifies the header to {"alg": "none"}, strips the signature completely, and some libraries accept the result as valid.
Fix this with explicit algorithm whitelisting on the decode side. Never let the token’s own header dictate which algorithm the server should use to verify it:
import jwt
SECRET_KEY = "your-256-bit-secret"
ALLOWED_ALGORITHMS = ["HS256"] # Explicit whitelist — never accept 'none'
def decode_token(token: str) -> dict:
try:
payload = jwt.decode(
token,
SECRET_KEY,
algorithms=ALLOWED_ALGORITHMS, # Enforce this — no exceptions
options={
"require": ["exp", "iat", "sub"], # Mandatory claims
"verify_exp": True,
}
)
return payload
except jwt.InvalidAlgorithmError:
raise ValueError("Token uses disallowed algorithm")
except jwt.ExpiredSignatureError:
raise ValueError("Token has expired")
except jwt.InvalidTokenError as e:
raise ValueError(f"Invalid token: {e}")
Even if an attacker constructs a token with alg: none, PyJWT 2.x raises InvalidAlgorithmError because none isn’t in the whitelist. That’s the entire defense — explicit, fail-closed.
Preventing Key Confusion (Algorithm Substitution Attack)
Key Confusion is more subtle. If your API uses RS256 (RSA signatures), the public key is — by definition — public. An attacker can download your public key, switch the token header to alg: HS256, and sign the forged token using your public key as the HMAC secret. A naive verifier using HS256 with the public key as its secret will accept this as valid.
Whitelisting alone won’t save you here. You also need dedicated verification paths for symmetric and asymmetric algorithms. Don’t build a single generic verify(token, key, algorithm=None) helper where the algorithm is an input parameter:
from cryptography.hazmat.primitives import serialization
import jwt
import time
with open("public.pem", "rb") as f:
PUBLIC_KEY = serialization.load_pem_public_key(f.read())
with open("private.pem", "rb") as f:
PRIVATE_KEY = serialization.load_pem_private_key(f.read(), password=None)
def create_rs256_token(user_id: str, expires_in: int = 900) -> str:
payload = {
"sub": user_id,
"iat": int(time.time()),
"exp": int(time.time()) + expires_in,
}
return jwt.encode(payload, PRIVATE_KEY, algorithm="RS256")
def verify_rs256_token(token: str) -> dict:
# ONLY "RS256" in the list — HS256 is not permitted here
return jwt.decode(token, PUBLIC_KEY, algorithms=["RS256"])
Separate functions for separate algorithms. The signing function uses the private key with algorithm="RS256" hardcoded. The verification function uses the public key with algorithms=["RS256"] hardcoded. There’s no code path where these get mixed.
Implementing Safe Token Rotation
Access tokens should be short-lived — 15 minutes is a reasonable default for most APIs. Refresh tokens can live longer, but every use must rotate them. When a refresh token is exchanged for a new access token, the old one is immediately invalidated and a fresh one is issued. If a stolen token gets replayed, the legitimate user’s next refresh attempt fails. That failure is your signal.
Here’s a minimal rotation store using Redis with an atomic delete to prevent race conditions:
import redis
import secrets
import time
import jwt
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
REFRESH_TOKEN_TTL = 7 * 24 * 3600 # 7 days
ACCESS_TOKEN_TTL = 900 # 15 minutes
SECRET_KEY = "your-256-bit-secret"
def issue_token_pair(user_id: str) -> dict:
refresh_token = secrets.token_urlsafe(64)
access_token = jwt.encode(
{"sub": user_id, "exp": int(time.time()) + ACCESS_TOKEN_TTL},
SECRET_KEY,
algorithm="HS256"
)
r.setex(f"refresh:{refresh_token}", REFRESH_TOKEN_TTL, user_id)
return {"access_token": access_token, "refresh_token": refresh_token}
def rotate_refresh_token(old_token: str) -> dict:
user_id = r.get(f"refresh:{old_token}")
if not user_id:
# Token not found — could be reuse of an already-rotated token
raise ValueError("Refresh token invalid or already used")
# Delete old token atomically before issuing new one
deleted = r.delete(f"refresh:{old_token}")
if deleted == 0:
raise ValueError("Token rotation race condition detected")
return issue_token_pair(user_id)
One critical detail: r.delete() returns the number of keys deleted. If two requests race to rotate the same token, only one gets deleted == 1. The second gets 0 and fails — no double-use, no silent bypass.
Verification & Monitoring: Knowing When Something Goes Wrong
Configuration alone isn’t enough. After six months, what actually caught attack attempts was logging and anomaly detection around token-related errors. Most JWT exploits fail fast and loud if you’re watching the right events.
Log these at minimum:
- Algorithm mismatch errors — someone is actively probing for None Algorithm or Key Confusion
- Expired token usage — could be clock drift, could be a replay attempt
- Refresh token reuse — the clearest signal of a stolen token being replayed
- Unexpected audience claims — tokens crossing service boundaries they shouldn’t
import logging
security_log = logging.getLogger("security.jwt")
def verify_with_audit(token: str, request_ip: str) -> dict:
try:
payload = decode_token(token)
return payload
except ValueError as e:
msg = str(e)
if "disallowed algorithm" in msg:
security_log.warning("Algorithm attack attempt from %s", request_ip)
elif "has expired" in msg:
security_log.info("Expired token submitted from %s", request_ip)
elif "already used" in msg:
security_log.critical(
"Refresh token reuse from %s — possible token theft",
request_ip
)
raise
Pipe these logs into Elasticsearch, Loki, or CloudWatch — wherever your team monitors. Set an alert for more than 3 algorithm mismatch events from the same IP in 10 minutes. That’s not a misconfigured client, that’s a deliberate probe.
One more thing before you ship: the aud (audience) claim. If your tokens cross service boundaries, a token issued for your user-facing API shouldn’t be accepted by your internal admin API:
payload = jwt.decode(
token,
SECRET_KEY,
algorithms=["HS256"],
audience="user-api" # Reject tokens meant for other services
)
After six months running this setup — explicit algorithm whitelisting, RS256/HS256 separation, rotation with atomic Redis invalidation, and security event logging — we’ve had zero successful JWT-based authentication bypasses. The same pen tester who originally flagged the None Algorithm issue confirmed all three vectors are now closed.
The vulnerabilities aren’t clever. The fixes aren’t either. What matters is being explicit about every assumption your verification code makes, and logging loudly when those assumptions are violated.

