Authentication foundations
Choose server-side sessions
Use a random opaque cookie value that maps to server-side session state and understand the tradeoff against self-contained tokens.
8 minute lesson
For a browser-first application, an opaque server-side session is a strong default. The browser stores only a meaningless identifier; the server owns identity and session state.
The cookie might contain 7xK...pQ, but that value carries no user data. On every request, the server uses it to find a record like this:
session hash → user ID, created time, last-used time, expiry, revoked time
Generate identifiers with a cryptographically secure random source or a trusted session library. Store only a hash of the identifier when feasible, plus user ID, creation, expiry, and revocation data.
Hashing limits what a database-only leak reveals. The raw value stays in the cookie. The server hashes the presented value and looks up the matching record, much like a password-reset token.
Server-side sessions cost a database or cache lookup and shared state across application instances. In return, logout, account suspension, password reset, and “sign out every device” can take effect immediately.
Self-contained tokens fit some architectures, but they do not remove security work. You still need key rotation, expiry, audience checks, safe browser storage, and often a revocation strategy. Choose them when the architecture needs those specific properties, not to avoid one lookup.
Design the users and sessions tables without putting passwords, roles, email addresses, or personal data inside the cookie value. Show how deleting one session record invalidates its cookie.
Lesson completed