1. What Problem Does JWT Solve?
In traditional monolithic web architectures, user authentication relied on stateful sessions. When a user logged in, the server created a session entry in a shared memory store (such as Redis or a database) and sent a randomized cookie ID to the browser. On every request, the server queried the database to verify the session.
In modern distributed microservices, stateful sessions introduce significant database bottlenecks. JSON Web Tokens (JWT) introduce a stateless authentication model. The user's identity, roles, and expiration dates are cryptographically signed directly into the token itself. Any microservice with the corresponding cryptographic key can instantly verify the user's identity without contacting a central session database.
The Three Components of a JWT
Every JWT string is composed of three Base64URL-encoded strings separated by dots:
2. Symmetric (HS256) vs Asymmetric (RS256) Signing
How the cryptographic signature is produced defines the security boundary of your backend:
- HMAC with SHA-256 (HS256 - Symmetric): Uses one single secret key to both create signatures and verify them. If any microservice needs to verify the token, it must possess the shared secret. If one service is compromised, attackers can mint counterfeit tokens.
- RSA Signature with SHA-256 (RS256 - Asymmetric): Uses an asymmetric keypair. The authentication server holds the private key (to mint tokens), while all client microservices and external gateways only need the public key (often published via a JWKS endpoint) to verify validity.
3. Crucial Security Pitfalls & Defense in Depth
Browser window.localStorage is fully accessible to any JavaScript executing on the origin. If a third-party npm package, analytics script, or compromised CDN injects an XSS payload, they can read your token and impersonate users indefinitely. Always store tokens in HttpOnly; Secure; SameSite=Strict cookies.
Because stateless tokens cannot be easily revoked before expiration, set the exp claim to a short duration (e.g. 15 minutes) and implement a secure Refresh Token rotation flow stored in an HttpOnly cookie to issue fresh access tokens.