Authentication

Session cookies vs JWTs (and why sessions usually win), OAuth 2.0/OIDC flows, password hashing with bcrypt/argon2, CSRF protection.

About 27 min read3-question knowledge check

The mental model

Authentication answers one question — "who is making this request?" — and it has to answer it on *every single request*, because HTTP is stateless: the server forgets you the instant it sends the response. So authentication is really the design of a credential the browser presents on every request that the server can trust and, crucially, revoke.

The mental model that untangles the whole topic: there are two families of credential, and they trade the same thing.

  • A session is a reference. The server stores the real state ("session abc123 belongs to user 42, expires at 5pm") in a database or Redis, and the browser holds only an opaque id in a cookie. Every request, the server looks up the id. The truth lives on the server.
  • A token (JWT) is a bearer of its own claims. The server signs a blob that says "user 42, expires at 5pm" and hands it over; the browser presents it, the server verifies the signature, and trusts the contents without a lookup. The truth travels with the request.

The trade is revocation vs. statelessness. Sessions can be revoked instantly — delete the row and the next request fails — but cost a lookup per request. JWTs need no lookup but cannot be un-issued: until it expires, a stolen or should-be-invalid token is still valid, because the server does not consult any store. This is why, for a normal web app, sessions usually win: the ability to log someone out right now (password change, role revoked, account compromised) is worth a sub-millisecond lookup, and "we can't actually revoke that token for 15 minutes" is a bad sentence to say in a security incident.

The analogy: a session cookie is a coat-check ticket — the ticket is meaningless on its own, the coat (your identity) is held at the desk, and the desk can refuse a ticket at any moment. A JWT is a signed festival wristband — it carries its own proof and needs no desk lookup, which is fast and scales across gates, but you cannot un-issue a wristband already on someone's wrist; you can only wait for the festival to end.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision