Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Session-Based Authentication

Session-based authentication is a stateful mechanism for verifying identity. It relies on three main components:

  • Session Storage: Active session data is stored server-side (typically in memory, or a database like Redis).
  • Session Cookie: The client stores a unique, opaque identifier in a cookie. This is automatically attached to every request by the browser.
  • Server-Side Validation: The server identifies the user by matching the incoming ID against its internal store.

The Authentication Workflow

  1. Handshake: The user sends credentials (e.g., username/password) to the server.
  2. Creation: Upon successful login, the server generates a unique Session ID, stores it in a database/cache, and maps it to the user’s profile.
  3. Delivery: The server sends back a Set-Cookie header containing the ID.
  4. Verification: For every subsequent request, the browser sends the cookie. The server performs a lookup to retrieve the associated user data.

Advantages

  • Granular Control: You can instantly invalidate a session (log a user out) by deleting the ID from your server-side store.
  • Security: Since the ID is an opaque token, no sensitive user data is exposed in the token itself.
  • Efficiency: The payload is extremely small (just a random string), minimizing bandwidth.

Disadvantages

  • Scalability (The “State” Problem): In distributed systems with multiple servers, you must use a centralized session store (like Redis) so all servers can recognize the same ID.
  • Resource Overhead: Every request requires an I/O operation (database or cache lookup) to verify the session.
  • CSRF Risk: Because browsers send cookies automatically, you must implement anti-CSRF measures (like SameSite cookie attributes or CSRF tokens).