System Design · 07. Security · 10 min · Beginner

Authentication

Prove who you are, once, and keep it safe across many requests.

In short

Prove who you are once, with a salted slow-hashed password, a provider (OAuth or SSO) or both, plus a second factor. Then carry a small proof: a session cookie, or a short access token with a refresh token behind it.

Verify every token, keep lifetimes short, limit login tries, and use trusted libraries. Next, authorization decides what the proven user may do.

Key ideas

  • Authentication happens once. After that, a small proof (a cookie or a token) rides along with every request. (step 1)
  • Access token: short, sent everywhere. Refresh token: long, sent only to one endpoint, and stored with care. (step 5)

Good to know

  • HttpOnly hides the cookie from page scripts, Secure sends it over HTTPS only. (step 3)
  • Check the state value you sent, and use PKCE for apps that cannot keep a secret. They block forged logins. (step 6)
  • SMS codes are better than nothing, but SIM swapping can steal them. Prefer an app, a key or a passkey. (step 8)

Watch out

  • Never use a plain fast hash for passwords, and never invent your own scheme. Use a library. (step 2)
  • Always check the signature, the expiry (exp) and the algorithm. A token you do not verify proves nothing. (step 4)
  • The identity provider becomes a single point of failure and a prime target. Protect it, and have a backup way in. (step 7)
  • Do not build your own login system if you can use a trusted library or provider. The details are many and easy to get wrong. (step 9)
BrowserPhone appApp serverDatabase

Key numbers

Factors
2
Access lasts
15 min

Terms

Authentication
Proving who you are; authorization, the next lesson, decides what you may do.
Password hashing
Storing a one-way scramble of the password so a leaked database does not reveal it.
Salt
A random value added per user before hashing, so equal passwords give different hashes.
Session cookie
A random id sent as a cookie, which the server looks up to find the logged-in user.
JWT
A signed token holding claims such as the user id and expiry, checked without a lookup.
Refresh token
A long-lived token used only to get new short-lived access tokens.
OAuth and OpenID Connect
A way to log in through another provider: the app gets a code, swaps it for tokens and learns who the user is.
SSO (single sign-on)
One login at an identity provider that many apps trust.
MFA (multi-factor authentication)
Asking for two or more kinds of proof, such as a password and a code from a phone.
User enumeration
Learning which accounts exist from different error messages; avoid it with one message for both cases.