JSON Web Tokens (JWT) Architecture
Understand JWT structure (Header, Payload, Signature), asymmetric signing (RS256), Access vs Refresh tokens, and security best practices.
What is a JSON Web Token (JWT)?
A JSON Web Token (JWT) is an open, industry-standard (RFC 7519) compact and self-contained method for securely transmitting claims between parties as a JSON object.
Anatomy of a JWT
A JWT consists of three parts separated by dots (.): header.payload.signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTYiLCJuYW1lIjoiQWxpY2UiLCJleHAiOjE3Mzg0NTY3ODl9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c1. Header
Contains token type and the cryptographic hashing algorithm used:
{
"alg": "HS256",
"typ": "JWT"
}2. Payload (Claims)
Contains user identity claims and metadata (not encrypted, only Base64URL encoded):
{
"sub": "user_987",
"name": "Alice Developer",
"role": "admin",
"iat": 1727740800,
"exp": 1727744400
}3. Signature
Generated by hashing the encoded header, encoded payload, and a secret key:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secretKey
)Dual Token Architecture (Access + Refresh Token)
Because stateless JWTs cannot be revoked until they naturally expire, production systems pair short-lived Access Tokens with long-lived Refresh Tokens:
+-------------------------------------------------------------+
| 1. Access Token: |
| - Lifetime: 5 to 15 minutes |
| - Sent in Authorization header |
| - Validated statelessly by backend microservices |
+-------------------------------------------------------------+
| 2. Refresh Token: |
| - Lifetime: 7 to 30 days |
| - Stored in an HttpOnly, Secure cookie |
| - Saved in database/Redis; revokable on logout |
| - Exchanged for a new Access Token upon expiration |
+-------------------------------------------------------------+Symmetric (HS256) vs Asymmetric (RS256 / EdDSA)
- HS256 (Shared Secret): Both the token generator and the token validator must know the identical secret key. Suitable for monolithic backends.
- RS256 / EdDSA (Public/Private Keypair): Auth server signs tokens with a private key; API microservices verify tokens with the public key. Essential for microservices and OAuth providers.
Security Warnings
- Never Put Passwords or Secrets in Payload: JWT payloads are Base64URL encoded and can be read by anyone.
- Always Validate
algHeader: Ensure the server explicitly enforces the expected algorithm to prevent thenonealgorithm exploit. - Keep Expirations Short: Never issue access tokens valid for days or weeks.
Server-Side Session Management
Learn stateful session architecture, session store backends (Redis, PostgreSQL), lifecycle invalidation, and session vs token trade-offs.
Authentication vs Authorization
Understand the differences between Authentication (AuthN) and Authorization (AuthZ), RBAC, ABAC, and access control patterns.