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
- Handshake: The user sends credentials (e.g., username/password) to the server.
- 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.
- Delivery: The server sends back a
Set-Cookieheader containing the ID. - 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
SameSitecookie attributes or CSRF tokens).