Authentication and sessions basics
Proving who you are, and staying signed in.
Two words get mixed up constantly. Authentication answers who are you?. Authorization answers what are you allowed to do?. A user who logs in is authenticated. Whether they may view a particular order or issue a refund is a separate check. You must do both on the server, on every request.
Passwords are the classic proof. The server must never store them as plain text, because a database leak would then expose every account, and people reuse passwords. Instead it stores a hash: the result of a deliberately slow one-way function (such as bcrypt, scrypt or Argon2) mixed with a random salt per user. At login it hashes the typed password and compares. A fast general hash like plain SHA-256 is the wrong choice here, because attackers can try billions of guesses per second.
HTTP is stateless, so after login the server needs a way to recognise you on the next request without a password every time. The common answer is a session. The server creates a random, unguessable session id, stores what it needs under that id (say, the user id and an expiry time) and hands the id to the client, usually in a cookie. The client sends it back on every request. A fast key-value store is a natural home for sessions.
HTTP/1.1 200 OK
Set-Cookie: session=9f3c...a1; HttpOnly; Secure; SameSite=Lax; Max-Age=86400An alternative is a token that carries its own proof, such as a signed JSON Web Token. The server checks the signature instead of looking anything up, which avoids a lookup per request and is handy when many separate services must verify the user. The price is that you cannot easily revoke one before it expires, since no central record exists. Short expiry times and refresh tokens soften this. Server-side sessions are simpler to revoke and a good default for a first system.
Your turn
A logged-in user changes the order id in the URL to see someone else's order. Which check was missing and where does it belong?
Stuck? Authentication was fine; what about permission?
What to remember
Authentication = who; authorization = what they may do. Check both on the server.
Store salted slow hashes, never plain passwords.
Sessions give a stateless protocol memory via an unguessable id.
Tokens avoid lookups but are hard to revoke.
Use HTTPS and secure cookie flags.