JSON Web Tokens (JWT) Explained
In traditional authentication (Sessions), when you log in, the server writes your name on a list in its memory (RAM). It gives you a ticket ID (Session ID). Every time you visit, it checks the list.
Problem: If you have 5 servers (Google, Facebook scale), you need to share that list between all of them. This is hard.
Solution: JWT (Stateless Authentication).
What is a JWT?
Instead of keeping a list, the server gives you a badge (Token) with your data written on it.
The badge is signed cryptographically so you can't change the data.
Structure of a JWT
A JWT has three parts separated by dots (.):
- Header: "I am a JWT using HS256 algorithm."
- Payload: "My user ID is 123. My name is Alice. I am an Admin."
- Signature: A mathematical proof that parts 1 and 2 haven't been touched.
How it works
- Login: You send
password. - Issue: Server creates a JWT:
{"id": 123, "role": "admin"}. It signs it with a Secret Key only the server knows. - Store: Browser saves the JWT.
- Request: Browser sends the JWT with every request.
- Verify: Server checks the Signature using its Secret Key. If valid, it trusts the data. It does not need to look up a database.
The Risk
If you steal a JWT, you are that user until the token expires. You cannot simply "log them out" because the server doesn't keep a list of active users.