The session pattern
Here is the standard login flow, built entirely from pieces you already know:
- You submit the login form: a
POST /login(lesson 5-3) with your email and password in the body. - The server checks the password. If it is right, it invents a random session ID like
abc123and stores a record on its side: "abc123 = user 42, logged in at 14:02". - The response carries
Set-Cookie: session=abc123; HttpOnly; Secure. - Every later request from your browser automatically includes
Cookie: session=abc123. The server looks upabc123in its session store, finds user 42, and treats the request as yours. - 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.
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 ___.)