Theory
JWT (JSON Web Token): Stateless Authentication
📋 Overview
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs are the industry standard for stateless authentication in modern microservices and single-page applications (SPAs).
🏗️ Core Principles & Characteristics
- Anatomy: Consists of three parts separated by dots:
Header.Payload.Signature.- Header: Alg (HS256/RS256) and Type (JWT).
- Payload: Claims (User ID, Roles, Expiration).
- Signature: Verification hash of the header + payload using a secret or private key.
- Statelessness: The server does not need to store the session in a database. All the information required to identify the user is contained within the token itself.
- Signing Algorithms:
- HS256: Symmetric key (Shared secret).
- RS256: Asymmetric keys (Private to sign, Public to verify).
⚖️ Trade-offs: Pros & Cons
- Pros:
- Scalability: No session database needed; ideal for distributed systems.
- Cross-Domain: Works across different domains/services easily.
- Compact: Small size allows it to be sent in HTTP headers (
Authorization: Bearer <token>).
- Cons:
- Revocation: Extremely difficult to "log out" or invalidate a JWT before it expires without introducing state (e.g., a blacklist).
- Payload Exposure: The payload is only Base64 encoded, not encrypted. Anyone can read the contents.
- Overhead: If the payload is large, it adds bytes to every single network request.
🌍 Real-World Implementation
- Auth0 / Okta: Use JWTs for OIDC/OAuth2 flows.
- Microservice Auth: An Auth service signs the JWT, and all other services verify it using a shared public key (RS256).
- Refresh Tokens: Use a short-lived JWT (Access Token) for API calls and a long-lived, stateful Refresh Token in a secure cookie to get new Access Tokens.
💡 Interview "Gotchas" & Tips
- JWT is NOT Encryption: Never store passwords, SSNs, or sensitive secrets in a JWT.
- The "alg: none" Vulnerability: Mention how older libraries could be tricked into skipping signature verification if the header was changed to
{ "alg": "none" }. - XSS vs. CSRF: Storing a JWT in
localStoragemakes it vulnerable to XSS. Storing it in anHttpOnlycookie makes it vulnerable to CSRF. The industry consensus isHttpOnlycookies + CSRF tokens.
📐 Suggested Architecture Primitives
- Authorization Server: To issue tokens.
- Public Key Endpoint (.well-known/jwks.json): For services to fetch the latest verification keys.
- Redis Blacklist: For emergency token revocation.
- Access + Refresh Token Pattern: For balancing security and UX.
Canvas