Authentication with JWT
Prove who a user is on a stateless server — sign tokens, hash passwords, guard routes
- explain the difference between authentication and authorization,
- hash and verify passwords with
bcrypt(never store plaintext), - sign and verify JWTs with the
jsonwebtokenlibrary, - write middleware that protects private routes, and reason about the real trade-offs of tokens.
1. Authentication vs. authorization, and the stateless problem
Authentication answers "who are you?" — logging in with an email and password. Authorization answers "what are you allowed to do?" — for example, only an admin may delete a user. They are different steps: you authenticate first, then the server authorizes each action.
Here is the hard part. HTTP is stateless: each request stands alone and the server keeps no memory of the previous one. So after a user logs in, how does request number two prove it is the same person? Two classic answers:
- Server-side sessions. On login the server stores a session record and sends the client a random session id in a cookie. Every request the server looks that id up in its store. Simple, but the server must remember every logged-in user, which is harder to scale across many machines.
- Tokens (JWT). On login the server hands the client a signed token that already contains the user's identity. The server stores nothing; it just re-checks the signature each time. This is stateless authentication, and it scales naturally.
Analogy. A session id is like a coat-check ticket: the number means nothing on its own, and the cloakroom must keep a matching list of what belongs to it. A JWT is like a festival wristband with a tamper-proof hologram: the wristband itself says "adult, 3-day pass", and any guard can confirm the hologram is genuine without phoning the box office.