Stage 3 · Build
Authentication & Authorization
Sessions & Cookies
Implement server-side sessions, secure cookies, SameSite, CSRF protection, and session rotation.
How Sessions Work
HTTP is stateless. Sessions solve this by storing a session ID in a cookie. The server maps the session ID to user data. On each request, the server reads the cookie, looks up the session, and attaches the user context.
Cookie Attributes
Cookie attributes control how the browser handles the cookie. Setting them correctly is critical for security.
| Attribute | Purpose | Recommended Value |
|---|---|---|
| HttpOnly | Prevents JavaScript access | true |
| Secure | Only sent over HTTPS | true |
| SameSite | CSRF protection | Lax or Strict |
| Path | Cookie scope | / |
| MaxAge | Cookie lifetime | 86400 (1 day) |
HttpOnly prevents XSS attacks from stealing session cookies. Secure prevents cookies from being sent over HTTP. Missing either one is a security vulnerability.
Server-Side Sessions
Server-side sessions store data on the server, not in the cookie. The cookie only contains the session ID. This keeps sensitive data off the client and lets you invalidate sessions by removing the server-side data.
CSRF Protection
Cross-Site Request Forgery tricks a logged-in user's browser into making requests to your API. SameSite cookies prevent this for most cases. For additional protection, use the double-submit cookie pattern.
Session Rotation
After login, generate a new session ID and invalidate the old one. This prevents session fixation attacks where an attacker sets a session ID before the user logs in.
Session Security
- Invalidate sessions on logout (delete from Redis).
- Rotate session IDs on login and privilege changes.
- Set short MaxAge for sensitive applications.
- Use HttpOnly and Secure flags on all session cookies.
- Store sessions in Redis with automatic TTL expiration.
- Log session creation and destruction for audit trails.
- Implement session revocation for security incidents.
Clearing the cookie on the client is not enough. The attacker may have already captured the session ID. Always delete the server-side session data on logout.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.