Appearance
JWT Explained | JWT vs SessionID | JSON Web Token Architecture and Security
The Airline Boarding Pass Analogy
Imagine arriving at an international airport to board a commercial flight. You check in at the airline counter. The airline agent verifies your identity, looks up your reservation in their database, and prints a physical paper boarding pass.
On that paper boarding pass, several key details are printed in plain text: your name (Alice), your flight number (FL-402), your departure gate (Gate 28), and your seat assignment (Seat 14B). Crucially, at the bottom of the pass sits an encrypted, cryptographically signed two dimensional barcode.
When you walk to the departure gate two hours later, the gate agent does not call the central booking database over the phone to verify your seat assignment. The gate agent simply scans the barcode. The scanner uses the airline's public cryptographic key to verify the barcode signature. If the signature is valid, the scanner knows with mathematical certainty that this boarding pass was issued by the airline, that none of the text fields were tampered with, and that Alice is authorized to board flight 402. The boarding pass is self contained.
In modern distributed web architecture, JWT (JSON Web Token) is that airline boarding pass. Instead of storing user state in server side memory and looking up session IDs on every request, the server issues a cryptographically signed, self contained token. Any microservice in your cluster can verify the token independently using a shared cryptographic key, reading user claims directly with zero database queries.
This lecture covers stateful session IDs versus stateless JWTs, the three part structure of a JWT (Header, Payload, Signature), symmetric versus asymmetric signing algorithms, and handling critical security challenges like token revocation and token theft.
Session ID vs JWT: Why Microservices Abandoned Sessions
Understanding why the industry transitioned from session IDs to JWTs is a cornerstone system design topic:
[ Traditional Session-Based Authentication (Stateful) ]
Client ---> [ Server 1: Memory (Session: 101 -> Alice) ]
Client ---> [ Server 2: NO SESSION! Fails or requires Sticky Sessions / Redis ]
[ Modern JWT Authentication (Stateless) ]
Client ---> [ Server 1: Validates JWT signature with secret key -> Alice ]
Client ---> [ Server 2: Validates JWT signature with secret key -> Alice ]
Client ---> [ Server 3: Validates JWT signature with secret key -> Alice ]| Dimension | Session ID (JSESSIONID) | JSON Web Token (JWT) |
|---|---|---|
| Storage Location | Server side memory (HttpSession or Redis cache) | Stored exclusively by the client (local storage or cookie) |
| Scalability | Difficult to scale horizontally; requires sticky sessions or central Redis cluster | Trivially scalable: any service with the secret key can verify |
| Payload Content | Opaque random string (e.g. JSESSIONID=7B91A2) | Self contained: holds user ID, username, roles, expiration |
| Database Overhead | Server must query session store on every single HTTP request | Zero database queries: validity verified via cryptographic math |
| Revocation | Instant: server deletes session from memory | Difficult: token remains valid until its expiration timestamp (exp) |
| Token Size | Tiny (around 32 bytes) | Larger (typically 500 to 1,500 bytes) |
The Three Part Structure of a JWT
A JSON Web Token (RFC 7519) consists of three sections separated by dots (.):
header.payload.signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTYiLCJuYW1lIjoiQWxpY2UiLCJyb2xlIjoiQURNSU4iLCJleHAiOjE3ODg2MjAwMDB9.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c1. Header (Red)
Contains metadata describing the token type and the hashing algorithm used to generate the signature:
json
{
"alg": "HS256",
"typ": "JWT"
}This JSON object is encoded using standard Base64Url encoding.
2. Payload (Claims — Green)
Contains the actual identity data and permissions, known as claims:
json
{
"sub": "123456",
"name": "Alice",
"role": "ROLE_ADMIN",
"iat": 1788616400,
"exp": 1788620000
}Standard Reserved Claims:
sub(Subject): The principal identifier (user ID or username).exp(Expiration Time): Unix timestamp after which the token is invalid.iat(Issued At): Unix timestamp when the token was created.iss(Issuer): Authority that generated the token.
This JSON object is also Base64Url encoded.
3. Signature (Blue)
The signature is the cryptographic seal that guarantees the token has not been altered:
Signature = HMACSHA256(
Base64Url(header) + "." + Base64Url(payload),
secretKey
)If an attacker decodes the payload, changes "role": "USER" to "role": "ADMIN", and re encodes it, the signature will no longer match the secret key calculation. The server rejects the forged token immediately.
The Critical Security Misconception: Base64 Is Not Encryption
The payload of a JWT is NOT encrypted. Base64Url is open encoding, not encryption.
Anyone who intercepts a JWT can paste it into jwt.io or run base64 --decode and read every single field in plain text in one millisecond.
Non Negotiable Rule:
Never store sensitive private data inside a JWT payload.
- Safe to store: User ID, username, public roles, permissions, expiration.
- NEVER store: Passwords, credit card numbers, social security numbers, API secrets.
Symmetric vs Asymmetric Signing
How should services sign and verify tokens?
1. Symmetric Signing (HMAC with Shared Secret — HS256)
A single shared secret key is used to both create the signature and verify the signature:
- Pros: Fast, computationally lightweight, simple to configure.
- Cons: Every microservice that needs to verify the token must know the secret key. If one downstream service is compromised, an attacker gains the ability to forge valid tokens for the entire platform.
2. Asymmetric Signing (Public / Private Key Pair — RS256)
Uses asymmetric public key cryptography (RSA / ECDSA):
- The Authorization Server holds the Private Key (kept strictly secret) and uses it to sign tokens upon login.
- All downstream microservices hold only the Public Key. They can verify that tokens are authentic, but they can never forge new tokens.
- Industry Standard for Microservices: Ideal for zero trust multi service architectures.
Security Challenges and Mitigations
1. The Revocation Problem
Because JWTs are stateless, once issued, a token is valid until its exp timestamp arrives. If a user logs out, or if an administrator bans an account, a stolen token can still be used until expiration.
Mitigations:
- Short Lived Access Tokens + Refresh Tokens: Issue access tokens with very short lifetimes (e.g. 10 to 15 minutes). Issue long lived refresh tokens (e.g. 7 days) stored securely in an HTTP only cookie and recorded in a database. When the short access token expires, the client uses the refresh token to obtain a fresh one. If an account is compromised, revoking the refresh token in the database halts access within fifteen minutes.
- Token Blacklist in Redis: When a user clicks logout, add their active token ID (
jticlaim) to an in memory Redis blacklist with a TTL matching the token's remaining lifetime. Gateway filters check Redis for blacklisted IDs.
2. Storing Tokens in the Browser: LocalStorage vs HTTP Only Cookies
localStorage: Vulnerable to XSS (Cross Site Scripting) attacks. If an attacker injects malicious JavaScript, they can executelocalStorage.getItem("token")and exfiltrate credentials.HttpOnly; Secure; SameSite=StrictCookies: Immune to JavaScript access, protecting tokens from XSS. Must be paired with CSRF protection for mutating requests.
Interview Questions & Pitfalls
Q1: What are the three parts of a JSON Web Token, and what separates them?
A JWT consists of three parts separated by period dots (.): the Header (declares token type and hashing algorithm), the Payload (contains identity claims and expiration), and the Signature (cryptographic hash validating data integrity).
Q2: Can anyone read the contents of a JWT payload?
Yes. The payload is Base64Url encoded, which is open and reversible by design. Anyone with access to the token string can decode and read all claims. Sensitive data (passwords, encryption keys) must never be stored in a JWT payload.
Q3: What is the difference between symmetric (HS256) and asymmetric (RS256) token signing?
Symmetric signing (HS256) uses a single shared secret key for both signing and verification; all participating services must know the secret key. Asymmetric signing (RS256) uses a private key held exclusively by the authentication server to sign tokens, while resource services use a corresponding public key to verify signatures without having the ability to forge tokens.
Q4: How do you invalidate or revoke a JWT before its expiration time?
Because JWT verification is stateless, immediate revocation requires either maintaining a fast in memory blacklist (e.g. in Redis) storing revoked token IDs until their natural expiration, or relying on short lived access tokens (10 to 15 minutes) paired with stateful refresh tokens that can be revoked in a central database.
Q5: What are standard reserved claims in a JWT specification?
Standard reserved claims include sub (subject/user identifier), iss (issuer), exp (expiration Unix timestamp), iat (issued at timestamp), nbf (not before timestamp), and jti (unique JWT identifier for replay protection).