Course contents

12. Security and Identity Lesson 2 of 8

Session-Based Authentication

Server-side sessions end to end: login, hardened cookies, the per-request session lookup and its store, instant logout, and CSRF defences.

16 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A session is server-side state keyed by an unguessable random id; the browser holds only the id, in a cookie.
  • Harden the cookie: HttpOnly, Secure, SameSite=Lax or Strict, __Host- prefix; issue a new id at login.
  • Every authenticated request costs a session lookup, so size the store for the request rate, not the login rate.
  • The store is on every request’s critical path: keep it fast (in memory, TTLs) and highly available.
  • Revocation is a delete that takes effect on the next request; cookies need CSRF defences because browsers send them automatically.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

In session-based authentication the server remembers who is logged in. At login it creates a session record (user id, creation time, expiry, maybe roles and a CSRF secret) in a store, and gives the browser only a random session id in a cookie. Every later request carries the cookie; the server looks the id up and knows the user.

Why it exists

HTTP is stateless: each request stands alone. Asking for the password on every request is impossible, and putting the user id in a cookie the client can edit is insecure. A random, unguessable id that points at state only the server can change solves both: the browser can present it, but cannot forge or alter it.

How it works

Login. The server verifies the password against a slow, salted hash (Argon2id, scrypt or bcrypt) or verifies a passkey assertion. It then generates a new session id from a cryptographically secure random generator (128 bits is common practice; OWASP’s minimum is 64 bits of entropy), stores the session, and answers with Set-Cookie. Issuing a fresh id at login, and again when privileges change, prevents session fixation, where an attacker plants a known id before the victim logs in.

The cookie. A typical header:

Set-Cookie: __Host-sid=k3Jq…; Path=/; Secure; HttpOnly; SameSite=Lax
  • HttpOnly: invisible to JavaScript, so an XSS bug cannot read and exfiltrate it (it can still make requests from the page while the user is there).
  • Secure: only sent over HTTPS.
  • SameSite=Lax: not sent on cross-site subrequests or cross-site POSTs, still sent on top-level GET navigations. Strict also withholds it on cross-site navigations (users arriving from a link appear logged out on the first page). None needs Secure and turns the protection off.
  • __Host- prefix: the browser accepts the cookie only if it is Secure, has Path=/ and no Domain, so other subdomains cannot set or overwrite it.
  • Without Expires/Max-Age it is a session cookie (dropped when the browser decides the session ends); with one it persists. Server-side expiry is what actually counts.

Every request. The app reads the cookie, fetches the session from the store and proceeds, or answers 401 if there is none. With several app servers the store must be shared (or the load balancer must pin each user to one server: sticky sessions).

Expiry and logout. An idle timeout (for example 15–30 minutes for sensitive apps) and an absolute lifetime (for example 8–24 hours) bound forgotten sessions. Logout deletes the record server-side and clears the cookie. “Log out everywhere” deletes all of a user’s sessions, which needs an index from user to sessions.

CSRF. Because the browser attaches cookies automatically, another site can make the browser send a request to yours with the user’s cookie. Defences, in layers: SameSite cookies; a CSRF token (a per-session secret that the page includes in a hidden field or header, which another origin cannot read); checking Origin or Sec-Fetch-Site on state-changing requests; and never changing state on GET.

When to use it

Browser applications served from one site (or a site and its own API), especially when you need instant logout, account suspension or “sign out other devices”. It is also the standard back-end-for-frontend pattern: the browser holds a session cookie and the server holds any OAuth tokens.

When not to

  • Third-party API clients and machine-to-machine calls, which do not have cookie jars: use OAuth access tokens.
  • Many independent services that would each need access to the session store; there, a gateway or BFF typically converts the session into short-lived tokens for internal calls.
  • Native mobile apps can use sessions, but token-based flows with platform secure storage are the usual fit.

Trade-offs

Choice You gain You pay
Server-side sessions vs self-contained tokens Instant revocation, nothing sensitive in the client, small cookie A store lookup per request; a store to run highly available
Sessions in the main relational database No new infrastructure, durable Session reads compete with business queries; easy to saturate
In-memory store (Redis, Valkey, Memcached) Sub-millisecond lookups, built-in TTLs Another stateful system; data loss on restart unless persisted or replicated
Sessions in app server memory + sticky sessions No store at all Uneven load; restarts and deploys log users out
SameSite=Strict vs Lax Stronger CSRF protection Users following a link from elsewhere arrive logged out

Alternatives

  • Self-contained tokens (JWT): the server verifies a signature instead of looking anything up. No store on the hot path; revocation becomes the hard part.
  • Signed or encrypted cookies holding the session data (as some web frameworks offer): no store, but the same revocation problem as tokens and a 4 KB cookie limit.
  • OAuth 2.0 / OpenID Connect with an external identity provider: hands login to a dedicated service; your app usually still keeps its own session afterwards.

Failure modes

  • Store saturation: every request reads the store, so a store sized for logins collapses at peak traffic and takes every authenticated page with it.
  • Store outage: nobody can be identified. An empty restart logs out every user.
  • Session fixation: reusing a pre-login id after login.
  • Predictable ids: ids from counters or weak random generators can be guessed.
  • Missing CSRF defences on state-changing endpoints, or state changes on GET.
  • Cookie scope too broad: a Domain=example.com cookie is sent to, and can be overwritten by, every subdomain.
  • Sessions that never expire: stolen cookies stay useful indefinitely.

In production

Use your framework’s session middleware rather than rolling your own. Keep sessions in a replicated in-memory store with TTLs and a failover plan, or in a database table with an index on the id if traffic is modest. Monitor store latency and hit rate alongside request latency. Rotate the id on login and privilege changes. Offer “sign out other devices”. Store as little as possible in the session (ids and flags, not whole user profiles), so the record stays small and changes to user data do not leave stale copies.

Common misconceptions

  • “HttpOnly cookies make XSS harmless.” They stop the cookie being stolen; injected script can still act as the user while the page is open.
  • “SameSite solves CSRF completely.” It stops most cross-site sends, but same-site subdomains are not cross-site, and Lax still sends cookies on top-level GETs. Keep tokens or Origin checks for state-changing requests.
  • “Sessions don’t scale.” A key lookup in an in-memory store is cheap; large sites run sessions. The real requirement is that the store is sized and replicated like any other critical dependency.
  • “Logging out in the browser ends the session.” Only deleting it on the server does. Clearing the cookie alone leaves any copy valid.

Interview angle

Expect to compare sessions with JWTs: lookup per request versus local verification, instant revocation versus waiting for expiry. Mention the cookie flags by name, a shared store for horizontally scaled app servers (and why sticky sessions are a weaker option), sizing the store by request rate, replication of the store, and CSRF. A strong answer lands on a hybrid: sessions at the browser edge (often via a BFF), short-lived tokens between internal services.

Model assumptions

Login, cookies, logout and CSRF are a scripted illustration: packets are placed by hand with illustrative durations (10 ms between browser and load balancer, 3 ms inside the data centre). The engine has no model of cookies, passwords or browser same-site rules. The per-request lookup is simulated: Poisson arrivals, a load balancer with 1 ms of work, two app servers with 32 workers and 3 ms mean service time (lognormal, cv 0.3) and room for 60 waiting requests each, then the session store, then an app database with 32 connections and 4 ms reads. The session store is modelled as a lookup service with a connection pool: first a sessions table with 4 connections reserved and 6 ms per lookup (cv 0.4) to stand for a relational database under contention, then an in-memory store with 16 connections and 0.5 ms per lookup. A failed store refuses connections and the request fails. Numbers are illustrative orders of magnitude, not benchmarks of any database.

The lesson as textEvery step of the simulation, written out.
  1. 1. Log in once, get a session

    Alice posts her email and password. App 1 loads her account, verifies the password against its slow, salted hash (Argon2id or bcrypt), then creates a session: a new random id (128 bits from a cryptographic random generator) stored server-side with her user id and an expiry. The browser only gets the id, in a cookie.

    The server issues a fresh id at login rather than reusing one the browser already had; otherwise an attacker who planted an id before login would share the logged-in session (*session fixation*). This step is a scripted illustration.

    Scene: The browser sends login credentials through the load balancer to App 1, which checks the password hash in the app database, stores a new session in the sessions table and returns a session cookie.

    Key idea: A session is server-side state keyed by an unguessable random id; the browser holds only the id.

  2. 2. The cookie rides along on every request

    The browser attaches the cookie to every request to the site, with no JavaScript involved. Here the next request lands on App 2, which has never seen Alice; it reads the session from the shared store, so any server can serve any user.

    The cookie’s attributes do the security work: HttpOnly (scripts cannot read it, so an XSS bug cannot copy it out), Secure (only over HTTPS), SameSite=Lax (not sent on most cross-site requests), and the __Host- prefix (the browser accepts it only with Secure, Path=/ and no Domain, so a subdomain cannot overwrite it).

    Scene: The browser sends a request with its session cookie; the load balancer picks App 2, which looks the session up in the shared sessions table, then reads the app database and answers.

    Key idea: Set session cookies HttpOnly, Secure, SameSite=Lax (or Strict), with the __Host- prefix.

  3. 3. One lookup per request

    Now the simulation runs: 400 requests per second from many browsers. Every one of them first looks up its session, then does its real work. The sessions table sits in a relational database with 4 connections reserved for it and about 6 ms per lookup under contention (illustrative), so it can do roughly 660 lookups per second. It is about 60% busy.

    A request takes about 41 ms here; the session lookup and its network hop are about 8 ms of that. Small per request, but it is paid on every request, including the ones that do almost nothing else.

    Scene: Browsers send 400 requests per second. Each app server looks up the session in the sessions table and then queries the app database. The sessions table is about 60 percent busy; latency is about 41 ms.

    Key idea: Stateful sessions cost one store lookup per request: size the store for your total request rate, not your login rate.

  4. 4. The session table becomes the bottleneck

    Traffic doubles to 800 requests per second. The app database has plenty of room, but the sessions table cannot do more than about 660 lookups per second. Lookups queue for its 4 connections. Every app server worker ends up blocked waiting on a lookup, the app servers’ own queues fill, and they reject new requests (503). Latency jumps from about 41 ms to about 300 ms and roughly one request in five fails.

    Users see errors and slow pages, and the cause is not their data: it is the check that runs before any of it.

    Scene: At 800 requests per second the sessions table saturates: lookups wait for connections, app server workers block on them, their queues fill and about one request in five is rejected; latency rises to about 300 ms.

    Key idea: The session store is on the critical path of every request. When it saturates, everything does.

  5. 5. Move sessions to an in-memory store

    Sessions are small, short-lived and read by key, which is exactly what an in-memory key-value store such as Redis or Valkey is good at. A GET sid is answered in well under a millisecond on the server, so most of the cost is now the network round trip. Entries expire on their own with a TTL that matches the session’s idle timeout.

    At the same 800 requests per second, nothing fails and latency drops to about 36 ms. The relational database no longer carries session traffic.

    Scene: The sessions table is replaced by an in-memory session store. At 800 requests per second every lookup is fast, nothing fails and latency is about 36 ms.

    Key idea: Keep sessions in a fast key-value store with TTLs; the per-request cost becomes about one network round trip.

  6. 6. No session store, no logged-in users

    One second in, the session store crashes. The app servers cannot tell who anyone is, so every request fails (an app that treated a missing store as “not logged in” would instead log everyone out at once).

    The store holds state that matters, so treat it like a database: run it replicated with automatic failover, and decide whether sessions must survive a restart (persistence) or whether a mass logout is acceptable. Keeping sessions in app server memory instead avoids the store, but then a server restart logs out its users and the load balancer needs sticky sessions.

    Scene: The session store goes offline after one second. App servers cannot read sessions and every request fails.

    Key idea: A shared session store must be highly available: it is a dependency of every authenticated request.

  7. 7. Logout is instant: delete the session

    The store is back. Alice clicks log out: the app deletes her session from the store and tells the browser to drop the cookie. An attacker who copied her cookie earlier (from a shared computer, say) tries it a second later: the lookup finds nothing, and the answer is 401.

    This is the big strength of server-side sessions: revocation is a delete. “Log out everywhere”, a password reset or an admin disabling an account takes effect on the very next request. Add an idle timeout (for example 30 minutes) and an absolute lifetime (for example 12 hours) so forgotten sessions die too.

    Scene: The browser logs out: App 1 deletes the session from the store and clears the cookie. Then an attacker replays the copied cookie; App 2 finds no session and answers 401.

    Key idea: Server-side sessions can be revoked instantly, because every request checks the store.

  8. 8. Cookies are sent automatically, so attackers try to borrow them

    Alice, still logged in, visits evil.example. Its page contains a hidden form that auto-submits POST /transfer to our site. Browsers used to attach the session cookie to that cross-site request, so the server saw a valid session: cross-site request forgery (CSRF).

    With SameSite=Lax the browser does not send the cookie on a cross-site POST (it still sends it on top-level GET navigations, so state must never change on GET). The request arrives without a session and is rejected. Defence in depth: require a CSRF token (a per-session secret echoed in a form field or header) or check the Origin/Sec-Fetch-Site headers on every state-changing request.

    Scene: The browser loads a page from evil.example, which submits a hidden form to our site. Because the session cookie is SameSite=Lax it is not attached, so App 1 rejects the forged request without consulting the session store.

    Key idea: Cookie auth needs CSRF defences: SameSite cookies plus tokens or Origin checks, and no state changes on GET.

  9. 9. Sessions, done properly

    Browsers send 400 requests per second again, each carrying an HttpOnly, Secure, SameSite cookie, each looked up in a fast, replicated session store.

    Server-side sessions give you instant revocation and keep nothing sensitive in the browser. You pay with a lookup per request, a store that must be fast and highly available, and CSRF defences because cookies are sent automatically. For browser apps on one site, they remain the simplest secure default.

    Scene: Browsers send 400 requests per second; each request looks up its session in the in-memory store, then queries the app database. Nothing fails and latency is about 36 ms.

    Key idea: Random id in a hardened cookie, state in a fast HA store, CSRF defences, timeouts and instant logout.