Web & Network8 min readLast updated: Mon Mar 18 2024 00:00:00 GMT+0000 (Coordinated Universal Time)

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 (.):

  1. Header: "I am a JWT using HS256 algorithm."
  2. Payload: "My user ID is 123. My name is Alice. I am an Admin."
  3. Signature: A mathematical proof that parts 1 and 2 haven't been touched.

How it works

  1. Login: You send password.
  2. Issue: Server creates a JWT: {"id": 123, "role": "admin"}. It signs it with a Secret Key only the server knows.
  3. Store: Browser saves the JWT.
  4. Request: Browser sends the JWT with every request.
  5. 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.