CodePark/ questions / Sessions vs tokens
START PRACTICINGPRACTICE
Backend question · Auth & security › Sessions vs tokens

Walk through how cookie-based session authentication works, from login to logout.

Login. The server checks the credentials. Then it creates a session record in its store, with the user id and an expiry. The record's key is a long random session id. The server sends that id to the browser in a cookie with these settings:

  • HttpOnly, so JavaScript can't read it.
  • Secure, so it travels only over HTTPS.
  • A SameSite setting, which limits sending it from other sites.

Each request. The browser sends the cookie automatically. The server looks up the id, loads the user and treats the request as authenticated. The id has no meaning by itself, so decoding it gives an attacker nothing.

Logout. The server deletes the session record and clears the cookie. Deleting the record on the server is the important part. If you only clear the cookie, a stolen id still works.

Sessions also end after an idle timeout (no activity for a while) and an absolute timeout (a maximum total age).

  • The server creates a session record keyed by a random id.
  • The id is sent in an HttpOnly, Secure cookie.
  • On each request, the server looks up the id in the store.
  • Logout deletes the record on the server, not just the cookie.
  • Sessions end after an idle timeout and an absolute timeout.