JWT Token Validation Testing: Strategies That Actually Catch Bugs
JWT validation failures are responsible for some of the worst auth security incidents in recent memory. The alg: none attack. Algorithm confusion. Missing claim checks. Each one a JWT implementation that "worked" but was never properly tested.
This guide covers comprehensive JWT validation testing—the happy paths, the edge cases, and the attacks that exploit gaps in validation.
How JWT Validation Works (And Where It Breaks)
A JWT has three parts: header, payload, signature. Each part can be wrong in ways that break security.
Header — specifies the algorithm (alg) and often the key ID (kid). An attacker can manipulate these.
Payload — contains claims: iss (issuer), sub (subject), aud (audience), exp (expiry), iat (issued at), jti (JWT ID), plus custom claims. Each claim that your code doesn't validate is a potential bypass.
Signature — proves the token wasn't tampered with. Invalid if the payload was modified, the wrong key was used, or the algorithm doesn't match.
Most JWT bugs fall into one of four categories:
- Signature not verified at all
- Algorithm confusion (RS256 vs HS256)
- Claims not checked (expiry, audience, issuer)
alg: noneaccepted
Your tests need to cover all of them.
Setting Up JWT Test Infrastructure
You need to generate test tokens with specific properties—valid, expired, malformed, wrong signature, etc. Do this with a test helper, not by copying tokens from logs.
import jwt
import time
from datetime import datetime, timedelta
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
# Generate RSA key pair for tests
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
VALID_CLAIMS = {
"iss": "https://auth.example.com",
"aud": "api.example.com",
"sub": "user123",
"exp": int((datetime.utcnow() + timedelta(hours=1)).timestamp()),
"iat": int(datetime.utcnow().timestamp()),
"jti": "unique-token-id-001",
}
def make_token(claims=None, key=None, algorithm="RS256"):
payload = {**VALID_CLAIMS, **(claims or {})}
signing_key = key or private_key
return jwt.encode(payload, signing_key, algorithm=algorithm)Testing Signature Validation
Tampered Payload Rejected
def test_tampered_payload_rejected():
# Create a valid token
token = make_token()
# Decode parts
header, payload, signature = token.split(".")
# Modify the payload (change user to admin)
import base64, json
decoded = json.loads(base64.urlsafe_b64decode(payload + "=="))
decoded["sub"] = "admin"
decoded["role"] = "superadmin"
modified_payload = base64.urlsafe_b64encode(
json.dumps(decoded).encode()
).rstrip(b"=").decode()
# Reassemble with original signature (invalid)
forged_token = f"{header}.{modified_payload}.{signature}"
response = client.get(
"/api/me",
headers={"Authorization": f"Bearer {forged_token}"}
)
assert response.status_code == 401Wrong Signing Key
def test_token_signed_with_wrong_key_rejected():
# Generate a different key pair
wrong_private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
# Sign token with wrong key
token = make_token(key=wrong_private_key)
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 401No Signature (alg: none Attack)
This is the classic JWT vulnerability. Some libraries accept tokens where the algorithm is none and there's no signature.
def test_alg_none_rejected():
# Craft a token with alg: none
import base64, json
header = base64.urlsafe_b64encode(
json.dumps({"alg": "none", "typ": "JWT"}).encode()
).rstrip(b"=").decode()
payload = base64.urlsafe_b64encode(
json.dumps(VALID_CLAIMS).encode()
).rstrip(b"=").decode()
# No signature
unsigned_token = f"{header}.{payload}."
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {unsigned_token}"}
)
assert response.status_code == 401
def test_alg_NONE_uppercase_rejected():
# Some bypasses use uppercase or mixed case
header = base64.urlsafe_b64encode(
json.dumps({"alg": "NONE", "typ": "JWT"}).encode()
).rstrip(b"=").decode()
# ... same as above
assert response.status_code == 401Algorithm Confusion Attack
This is subtle but critical when using asymmetric keys. If your server uses RS256 (RSA), the public key is... public. An attacker can take your RS256 public key and use it as an HS256 secret to sign their own tokens. If your server accepts both RS256 and HS256, it might verify the HS256 token using the public key as the HMAC secret—and it'll succeed.
def test_algorithm_confusion_attack_rejected():
# Get the public key (as an attacker would—it's public)
pubkey_bytes = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# Attacker signs a token using the public key as HS256 secret
forged_token = jwt.encode(
{**VALID_CLAIMS, "sub": "admin"},
pubkey_bytes,
algorithm="HS256"
)
response = client.get(
"/api/admin",
headers={"Authorization": f"Bearer {forged_token}"}
)
# Must reject—server should only accept RS256
assert response.status_code == 401Mitigation: Always explicitly specify which algorithms your server accepts. Never accept a list that includes both symmetric and asymmetric algorithms for the same key material.
Testing Claim Validation
Expiry (exp)
def test_expired_token_rejected():
# Token that expired 1 hour ago
expired_token = make_token(claims={
"exp": int((datetime.utcnow() - timedelta(hours=1)).timestamp())
})
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {expired_token}"}
)
assert response.status_code == 401
# Check error is descriptive (helps debugging, not a security concern)
body = response.json()
assert "expired" in body.get("error", "").lower() or response.headers.get("WWW-Authenticate", "").startswith("Bearer")
def test_token_expiring_soon_still_valid():
# Token with 10 seconds left
nearly_expired = make_token(claims={
"exp": int((datetime.utcnow() + timedelta(seconds=10)).timestamp())
})
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {nearly_expired}"}
)
assert response.status_code == 200Issued At (iat) — Clock Skew
def test_future_issued_at_rejected():
# Token issued 5 minutes in the future (clock skew attack)
future_token = make_token(claims={
"iat": int((datetime.utcnow() + timedelta(minutes=5)).timestamp())
})
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {future_token}"}
)
# Depends on your policy—most servers allow small clock skew (< 60s)
# but should reject 5 minutes
assert response.status_code == 401Issuer (iss)
def test_wrong_issuer_rejected():
token = make_token(claims={"iss": "https://evil-auth.attacker.com"})
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 401
def test_correct_issuer_accepted():
token = make_token(claims={"iss": "https://auth.example.com"})
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 200Audience (aud)
Audience prevents a token issued for one service from being used at another:
def test_wrong_audience_rejected():
# Token meant for a different service
token = make_token(claims={"aud": "other-service.example.com"})
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 401
def test_missing_audience_rejected():
claims = {k: v for k, v in VALID_CLAIMS.items() if k != "aud"}
token = jwt.encode(claims, private_key, algorithm="RS256")
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {token}"}
)
# Depends on your strictness — if aud is required, this should fail
assert response.status_code == 401Testing JWT ID (jti) — Replay Prevention
For high-security operations, each JWT should be single-use:
def test_jwt_replay_rejected():
# Single-use token
token = make_token(claims={"jti": "unique-id-12345"})
# First use
response1 = client.post(
"/api/sensitive-operation",
headers={"Authorization": f"Bearer {token}"}
)
assert response1.status_code == 200
# Replay attempt
response2 = client.post(
"/api/sensitive-operation",
headers={"Authorization": f"Bearer {token}"}
)
assert response2.status_code == 401This requires your server to store used jti values (in Redis, a database, etc.). Test that storage and lookup too.
Testing Key Rotation
JWT public keys rotate. If your server can't handle rotation, you'll have 401s every time a key rotates.
def test_token_validated_after_key_rotation():
# Issue token with key 1
old_token = make_token_with_key(key_id="key-1")
# Rotate keys — key 2 is now active, key 1 still trusted
rotate_keys()
# Old token still valid (key 1 still in JWKS)
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {old_token}"}
)
assert response.status_code == 200
def test_token_with_removed_key_rejected():
old_token = make_token_with_key(key_id="key-1")
# Remove key 1 entirely
remove_key("key-1")
# Old token now invalid
response = client.get(
"/api/protected",
headers={"Authorization": f"Bearer {old_token}"}
)
assert response.status_code == 401Testing Custom Claims and Authorization
JWTs often carry roles, permissions, and other application-specific claims:
def test_admin_role_grants_access():
token = make_token(claims={"roles": ["admin"]})
response = client.get(
"/api/admin/users",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 200
def test_missing_role_denies_access():
token = make_token(claims={"roles": ["user"]})
response = client.get(
"/api/admin/users",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 403
def test_empty_roles_denies_access():
token = make_token(claims={"roles": []})
response = client.get(
"/api/admin/users",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 403
def test_missing_roles_claim_denies_access():
# Token with no roles claim at all
claims = {k: v for k, v in VALID_CLAIMS.items()}
# Don't add roles
token = jwt.encode(claims, private_key, algorithm="RS256")
response = client.get(
"/api/admin/users",
headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 403Common Mistakes to Test Against
Mistake 1: Accepting JWTs without verifying signature Test by sending a token with a modified payload and a valid-looking (but wrong) signature.
Mistake 2: Not checking exp Test by sending an obviously expired token (exp = 1970).
Mistake 3: Not checking aud Test by sending a token meant for a different service.
Mistake 4: Accepting any algorithm the token header specifies Test the algorithm confusion attack above.
Mistake 5: Not checking iss Test by sending a token from a different issuer.
Mistake 6: Logging full tokens Check your logs after a test run—full JWTs should never appear in application logs.
JWT Validation Checklist
- Malformed token rejected (not 3 parts)
- Wrong signature rejected
alg: nonerejected (both lowercase and uppercase)- Algorithm confusion (RS256 key used for HS256) rejected
- Expired token rejected
- Future
iatrejected - Wrong issuer rejected
- Wrong audience rejected
- Insufficient roles returns 403 (not 401)
- Replay attack rejected (if
jtiis used) - Key rotation handled gracefully
- Full tokens NOT logged
JWT validation is not "does the library return true or false." It's a checklist of things your code must explicitly verify. These tests make that checklist executable.