JWT Authentication: A Backend Engineer's Mental Model
Introduction Imagine you arrive at a hotel. At the reception, you show your ID and prove who you are. The receptionist then gives you a room key card. You don't need to show your ID every time you enter your room. Instead, you simply present the key card. The hotel doesn't need to ask your name again because the card itself proves that you already authenticated. JWT (JSON Web Token) works exactly like that. Username and password = Your ID JWT = Hotel key card Server = Receptionist What is JWT? JWT stands for JSON Web Token . It is a compact string that proves a user has already logged in successfully. Instead of storing login sessions on the server, the server gives the client a signed token. The client sends this token with every request. Example: Authorization: Bearer eyJhbGciOiJIUzI1NiIs... The server verifies the token and allows access. Why Do We Need JWT? Without JWT, every request would require sending the username and password repeatedly. Browser | Username Password | Server That would be inefficient and insecure. Instead: Login once ↓ Receive JWT ↓ Reuse JWT for every request Stateless Authentication JWT enables stateless authentication . Stateful Authentication Server | |-- Session #12345 |-- Session #91821 |-- Session #44211 The server stores every user's session. Stateless Authentication (JWT) Server (No session storage) ↓ Only verifies token signature The server doesn't remember users. The token remembers. JWT Structure A JWT consists of three parts separated by periods. Header.Payload.Signature Example eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiIxMjMiLCJuYW1lIjoiRXZhbnMiLCJyb2xlIjoiYWRtaW4ifQ . K6L6GQX.... Think of it like Envelope Letter Wax Seal Part 1 — Header Example { "alg" : "HS256" , "typ" : "JWT" } The header tells us: Which algorithm signed the token. What type of token it is. Fields: alg → Signing algorithm typ → JWT Common algorithms: HS256 RS256 ES256 Part 2 — Payload The payload contains claims . Example: { "user_id" : 42 , "name" :