Cookie-Based Authentication Flow
What you'll learn: How session IDs stored in cookies work with server-side sessions to authenticate requests.
How It Works
In cookie-based authentication, the server maintains a record of active user sessions. When you successfully log in, the server generates a unique session ID, stores session data (like your user ID and permissions) in its memory or database, then sends that session ID back to your browser as a cookie.
On every subsequent request, your browser automatically includes this cookie. The server reads the session ID from the cookie, looks up the corresponding session data, and verifies you're authenticated.
Analogy: Think of it like a coat check. When you arrive at a venue (log in), they give you a numbered ticket (session ID cookie). You keep the ticket, they keep your coat and a record linking that number to your items (session data). Each time you need something, you show your ticket, and they retrieve your belongings from storage.
The Flow Step-by-Step
- Login: User submits credentials
- Server validates: If correct, creates session in storage
- Cookie sent: Server responds with
Set-Cookieheader containing session ID - Browser stores: Cookie saved automatically
- Subsequent requests: Browser includes cookie header
- Server validates: Looks up session ID, confirms validity
- Logout: Server deletes session; cookie expires
Key Characteristics
Since the server stores session data, this is a stateful approach (from lesson 1567). The server must "remember" active sessions. Cookies are automatically included by the browser, making this pattern convenient but tied to same-origin requests unless CORS is configured.
Key Takeaway: Cookie-based authentication uses session IDs stored in cookies as lookup keys, with the server maintaining all session state—your browser holds the ticket, the server holds the data.