Course outline · 0% complete

0/25 lessons0%

Course overview →

Sessions: how login stays logged in

lesson 6-2 · ~9 min · 19/25

The session pattern

Here is the standard login flow, built entirely from pieces you already know:

  1. You submit the login form: a POST /login (lesson 5-3) with your email and password in the body.
  2. The server checks the password. If it is right, it invents a random session ID like abc123 and stores a record on its side: "abc123 = user 42, logged in at 14:02".
  3. The response carries Set-Cookie: session=abc123; HttpOnly; Secure.
  4. Every later request from your browser automatically includes Cookie: session=abc123. The server looks up abc123 in its session store, finds user 42, and treats the request as yours.
  5. Logging out deletes the server-side record and clears the cookie. The ID means nothing anymore.

Notice what is not in the cookie: your password, your name, anything readable. The cookie is only a claim ticket. All the real information stays on the server, and the random ID is the key to it. Anyone who steals the ticket can impersonate you though, which is why the attributes matter: HttpOnly keeps scripts from reading it, and Secure means "only send this over encrypted HTTPS", which is one of the reasons unit 7 exists.

BrowserServerPOST /login (email + password)200 OK + Set-Cookie: session=abc123(server stores: abc123 → user 42)GET /inbox + Cookie: session=abc123200 OK, "here is YOUR inbox"
The session pattern: log in once, get a claim ticket in a cookie, and every later request presents the ticket. The server's lookup table does the remembering.

Code exercise · python

Your turn, be the server's session check — step 4 of the flow above. The sessions dict is the server-side store. For each incoming Cookie value, print who it belongs to if the session ID exists, or a 401 line if it does not. (The "deleted" one has no entry: maybe the user logged out, maybe the ID expired — either way, the server has nothing to look up.)

Quiz

Why do session cookies use the HttpOnly attribute?

Problem

You are logged into a site, then you clear all your browser's cookies and refresh the page. From the server's point of view, what are you now? (Two words: logged ___.)