Skip to content

Authentication with JWT

Beginning of the lesson

Authentication with JWT

Prove who a user is on a stateless server — sign tokens, hash passwords, guard routes

Big Idea: HTTP forgets you between requests. A JSON Web Token (JWT) is a small, digitally signed pass the server hands out at login. The client sends it back on every request, and the server can trust it without storing anything — because it can verify the signature it created.
By the end you will be able to:
  • explain the difference between authentication and authorization,
  • hash and verify passwords with bcrypt (never store plaintext),
  • sign and verify JWTs with the jsonwebtoken library,
  • 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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers