JSON Web Tokens (JWT) Explained: RFC 7519 Architecture, Cryptographic Signatures (RS256 vs HS256), and Production Security Pitfalls
A complete 1,200+ word engineering guide to JSON Web Tokens. Understand header structures, registered claims, asymmetric public key verification, refresh token rotation, and vulnerability mitigation.
1. The Architecture of JSON Web Tokens: RFC 7519
A JSON Web Token (JWT), standardized by the IETF in RFC 7519, is a compact, URL-safe container format for securely transmitting claims between two parties. Paired with JSON Web Signature (JWS / RFC 7515) and JSON Web Encryption (JWE / RFC 7516), JWTs represent the foundation of modern decentralized authentication, Single Sign-On (SSO), and microservice API authorization.
Before JWTs gained wide adoption, stateful session cookies dominated web architecture. In stateful systems, the server generated an arbitrary session token, stored all session metadata in an in-memory cache (such as Redis or Memcached), and transmitted the session ID to the client in an HTTP cookie. While stateful sessions provide immediate server-side revocation, they introduce a state bottleneck that hinders horizontal autoscaling across multi-region server clusters.
JWTs introduced stateless authentication: the token itself contains all necessary user identity claims, permission scopes, and cryptographic signatures. Any resource server possessing the verification key can independently validate the token without performing a database lookup.
2. Anatomical Structure of a JWT
A canonical JWT is constructed by concatenating three distinct segments with periods (.):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsZXgiLCJyb2xlcyI6WyJhZG1pbiJdfQ.4z28...
[------------ Header ------------].[------------- Payload -------------].[------------- Signature -------------]Part 1: The Header (JOSE Header)
The header specifies the cryptographic metadata required to verify the token:
{{
"alg": "RS256",
"typ": "JWT",
"kid": "key_2026_q4"
}}alg(Algorithm): The cryptographic signing algorithm (e.g.,HS256,RS256,ES256).typ(Type): The media type, typicallyJWT.kid(Key ID): A unique identifier indicating which public key in a JWKS (JSON Web Key Set) signed the token.
Part 2: The Payload (Claims)
The payload contains the statement of truth (claims) asserted about the authenticated subject. RFC 7519 establishes seven Registered Claims:
iss(Issuer): The URI identifying the identity provider (e.g.,https://auth.devxtool.me).sub(Subject): The unique identifier of the user (e.g.,usr_550e8400).aud(Audience): The intended recipient or resource API (e.g.,https://api.devxtool.me).exp(Expiration Time): Unix epoch timestamp after which the token must be rejected.nbf(Not Before): Unix timestamp before which the token must not be accepted.iat(Issued At): Unix timestamp when the token was created.jti(JWT ID): A unique UUID for the token, used to prevent replay attacks.
Live JWT Token Decoder & Claims Sandbox
Decode JWT headers, parse JSON claims payload, check expiry status, and inspect signature algorithms in local browser memory.
3. Symmetric (HS256) vs Asymmetric (RS256 / ES256) Signing
Choosing between symmetric and asymmetric cryptography is the most critical architectural decision in JWT deployment:
| Feature | HMAC SHA-256 (HS256) | RSA Signature (RS256) | ECDSA (ES256) |
|---|---|---|---|
| Key Model | Shared symmetric secret key (both sides share the same secret) | Private key signs; Public key verifies | Elliptic curve private key signs; Public key verifies |
| Trust Boundary | Internal monoliths only. Any service verifying a token can forge tokens. | Microservices & 3rd-party APIs. Public key can be shared globally. | Zero trust. Optimal for mobile & edge devices. |
| Key Size | 256+ bits (32+ bytes string) | 2048 to 4096 bits | 256 bits (P-256 curve) |
| Token Overhead | Compact (32-byte signature) | Large (256-byte signature) | Compact (64-byte signature) |
4. Lethal JWT Security Vulnerabilities & Prevention
1. The "None" Algorithm Attack
RFC 7515 specifies a none algorithm for unsigned tokens. Early naive libraries read the alg header from incoming tokens without validation. Attackers changed "alg": "HS256" to "alg": "none", deleted the signature segment, and achieved full privilege escalation. Modern libraries automatically reject unsigned tokens unless explicitly commanded otherwise.
2. Algorithm Substitution Attack
If an API server uses asymmetric RS256, an attacker can obtain the server's public key (which is public by design). The attacker signs a forged token using HS256, supplying the public key string as the HMAC secret. If the backend fails to verify the algorithm explicitly, it treats the public key as an HMAC secret and verifies the forged signature.
Remediation: Always specify algorithms: ['RS256'] in verification options.
5. Production Implementation Across Modern Languages
TypeScript / Node.js
import jwt from 'jsonwebtoken';
const payload = {{
sub: "usr_9912",
iss: "https://auth.devxtool.me",
aud: "https://api.devxtool.me",
roles: ["billing_admin"]
}};
// 1. Sign token with 15-minute expiry
const secretKey = process.env.JWT_SECRET!;
const token = jwt.sign(payload, secretKey, {{
algorithm: 'HS256',
expiresIn: '15m'
}});
// 2. Verify token with clock leeway
try {{
const verified = jwt.verify(token, secretKey, {{
algorithms: ['HS256'],
issuer: 'https://auth.devxtool.me',
audience: 'https://api.devxtool.me',
clockTolerance: 30 // 30 seconds leeway
}});
console.log("Verified claims:", verified);
}} catch (err) {{
console.error("JWT verification failed:", err);
}}Python (PyJWT)
import jwt
import datetime
# Sign payload
payload = {{
"sub": "usr_9912",
"iss": "https://auth.devxtool.me",
"exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=15)
}}
token = jwt.encode(payload, "super-secret-key-32-chars-long!", algorithm="HS256")
print("Generated JWT:", token)
# Verify payload
try:
decoded = jwt.decode(
token,
"super-secret-key-32-chars-long!",
algorithms=["HS256"],
issuer="https://auth.devxtool.me"
)
print("Decoded subject:", decoded["sub"])
except jwt.ExpiredSignatureError:
print("Error: Token has expired!")
except jwt.InvalidTokenError:
print("Error: Token signature invalid!")6. Frequently Asked Questions (FAQ)
Is a JWT encrypted?
No. Standard JWTs (JWS) are merely signed and Base64URL-encoded, not encrypted. Anyone holding the token can decode the header and payload to view all claims. Never store sensitive secrets, passwords, or PII inside a standard JWT payload. If encryption is required, use JWE (JSON Web Encryption).
Where should JWTs be stored in the browser?
Never store JWTs in localStorage or sessionStorage, as they are vulnerable to Cross-Site Scripting (XSS) token exfiltration. Store authentication tokens in an HttpOnly; Secure; SameSite=Strict cookie, preventing malicious JavaScript from reading the credential.
7. Token Revocation Strategies in Stateless Architectures
The primary critique of stateless JWTs is the difficulty of immediate revocation. If a user's account is compromised, or an employee is terminated, an issued access token remains mathematically valid until its exp timestamp elapses.
Architectural Mitigations:
- Short-Lived Access Tokens (5 to 15 minutes): Minimize the exposure window by issuing brief access tokens paired with long-lived refresh tokens.
- Distributed Redis Blacklists / Bloom Filters: Store revoked
jtiidentifiers in an in-memory Redis cluster with a TTL equal to the remaining token lifetime. - User Token Version Counters: Store an integer
token_versionon the user's database record. Embed this counter in the JWT payload. Incrementing the database counter immediately invalidates all previously issued tokens during permission checks.
Try the related tool
JWT DecoderTutorials for this tool
More guides
- How to Format and Validate JSON
- Base64 Encoding and Decoding Explained
- URL Encoding: A Practical Guide
- How to Compare Two Text Files
- Regular Expressions for Beginners
- What Is a UUID? Versions, Formats and Best Practices
- Hash Functions Explained: SHA-256, SHA-1 and Beyond
- Unix Timestamps: A Complete Guide
- How to Create Strong Passwords
- HEX, RGB and HSL Colors Explained