Design Session Management
Issue cryptographically random session tokens, transmit them exclusively over HTTPS with HttpOnly/Secure/SameSite cookie attributes, and enforce idle and absolute timeouts — eliminating fixation, hijacking, and token prediction attacks.
Why This Is Best Practice
Adopted by: Codified in OWASP Top 10 2021 A07 (Identification and Authentication Failures) and NIST SP 800-63B (Digital Identity Guidelines). Django, Rails, Laravel, Spring Session, and ASP.NET Core all implement these defaults. PCI DSS v4.0 Requirement 8.2 mandates session controls. NIST 800-63B is the authoritative federal standard for session management in US government applications.
Impact: Session hijacking is among the most common post-authentication attack vectors — Verizon DBIR 2023 identifies stolen session tokens as a top initial access technique in web application breaches. Proper session invalidation on logout prevents 100% of fixation attacks. HttpOnly cookies prevent JavaScript from reading session tokens even when XSS occurs, limiting the blast radius.
Why best: JWTs stored in localStorage are the common alternative — they lack server-side revocation, persist after logout, and are readable by XSS. Server-side sessions with HttpOnly cookies give developers full control over validity and are immune to JavaScript-based theft.
Sources: OWASP Session Management Cheat Sheet; NIST SP 800-63B; Verizon DBIR 2023; CWE-613
Steps
Generate cryptographically random session IDs — at least 128 bits of entropy from a CSPRNG. Never use sequential IDs, timestamps, or user-derived values.
import secrets
session_id = secrets.token_urlsafe(32) # 256-bit URL-safe token
// Java
SecureRandom sr = new SecureRandom();
byte[] token = new byte[32];
sr.nextBytes(token);
String sessionId = Base64.getUrlEncoder().withoutPadding().encodeToString(token);
Set all four protective cookie attributes:
Set-Cookie: session=<token>; HttpOnly; Secure; SameSite=Lax; Path=/
HttpOnly — JavaScript cannot read the cookie (blocks XSS-based token theft)
Secure — cookie only sent over HTTPS
SameSite=Lax — blocks CSRF from cross-site form POST (see prevent-csrf)
Path=/ — restrict to your app path, not subpaths of shared hosts
Rotate session ID on privilege escalation — generate a NEW session ID after login, role changes, or permission grants to prevent session fixation:
# After successful login
old_data = session.get_data()
session.invalidate()
new_session = session.create_new()
new_session.set_data(old_data)
new_session.set('user_id', authenticated_user.id)
Enforce idle and absolute timeouts:
IDLE_TIMEOUT = 30 * 60 # 30 minutes of inactivity
ABSOLUTE_TIMEOUT = 8 * 3600 # 8 hours regardless of activity
last_activity = session['last_activity']
created_at = session['created_at']
if time.time() - last_activity > IDLE_TIMEOUT:
session.invalidate()
if time.time() - created_at > ABSOLUTE_TIMEOUT:
session.invalidate()
PCI DSS requires ≤15 minutes idle timeout for cardholder data environments.
Invalidate server-side on logout — delete the session record from the server, not just the client cookie:
@app.route('/logout', methods=['POST'])
def logout():
session_id = request.cookies.get('session')
session_store.delete(session_id) # server-side deletion
response = redirect('/login')
response.delete_cookie('session')
return response
Client-only logout (clearing the cookie without server deletion) leaves the token valid for hijacking.
Use framework session management — don't implement from scratch. Use Django's django.contrib.sessions, Spring's HttpSession, or Rails' ActionDispatch::Session. They handle storage, rotation, and timeout correctly.
For high-security actions, re-authenticate — prompt for password before account deletion, fund transfers, or email/password changes. Don't rely solely on session validity for irreversible operations.
Rules
- Never store session IDs in URLs (
?sessionid=...) — they appear in logs, referrer headers, and browser history.
- Session tokens must not contain user data (user ID, role) — store a random ID that maps server-side to user state.
- Concurrent session control (invalidate old sessions on new login) prevents credential-sharing; implement where security requirements demand it.
- Session fixation: always rotate ID on login; never accept a session ID set by the client pre-login.
Common Mistakes
- Using userID + timestamp as session token — predictable, brute-forceable.
- Deleting the cookie but not the server-side session on logout — the token remains valid if captured.
- Setting long absolute timeouts for convenience — 30-day sessions mean a stolen token is valid for 30 days.
- HttpOnly cookies + JWT in localStorage — mixing models: choose one. HttpOnly cookies handle both transport and XSS protection.
1---2name: design-session-management3description: Use when implementing user authentication state — creating, storing, transmitting, and expiring session tokens or cookies in a web application.4source: 'OWASP Session Management Cheat Sheet (owasp.org/www-project-cheat-sheets); OWASP Top 10 2021 A07; CWE-613; NIST SP 800-63B'5tags: [security, owasp, sessions, cookies, authentication, web, developer]6metadata:7 source: https://skillmd.com/skills/jeffreytse/design-session-management8---910# Design Session Management1112Issue cryptographically random session tokens, transmit them exclusively over HTTPS with `HttpOnly`/`Secure`/`SameSite` cookie attributes, and enforce idle and absolute timeouts — eliminating fixation, hijacking, and token prediction attacks.1314## Why This Is Best Practice1516**Adopted by:** Codified in OWASP Top 10 2021 A07 (Identification and Authentication Failures) and NIST SP 800-63B (Digital Identity Guidelines). Django, Rails, Laravel, Spring Session, and ASP.NET Core all implement these defaults. PCI DSS v4.0 Requirement 8.2 mandates session controls. NIST 800-63B is the authoritative federal standard for session management in US government applications.17**Impact:** Session hijacking is among the most common post-authentication attack vectors — Verizon DBIR 2023 identifies stolen session tokens as a top initial access technique in web application breaches. Proper session invalidation on logout prevents 100% of fixation attacks. HttpOnly cookies prevent JavaScript from reading session tokens even when XSS occurs, limiting the blast radius.18**Why best:** JWTs stored in localStorage are the common alternative — they lack server-side revocation, persist after logout, and are readable by XSS. Server-side sessions with `HttpOnly` cookies give developers full control over validity and are immune to JavaScript-based theft.1920Sources: OWASP Session Management Cheat Sheet; NIST SP 800-63B; Verizon DBIR 2023; CWE-6132122## Steps23241. **Generate cryptographically random session IDs** — at least 128 bits of entropy from a CSPRNG. Never use sequential IDs, timestamps, or user-derived values.2526 ```python27 import secrets28 session_id = secrets.token_urlsafe(32) # 256-bit URL-safe token29 ```3031 ```java32 // Java33 SecureRandom sr = new SecureRandom();34 byte[] token = new byte[32];35 sr.nextBytes(token);36 String sessionId = Base64.getUrlEncoder().withoutPadding().encodeToString(token);37 ```38392. **Set all four protective cookie attributes**:4041 ```http42 Set-Cookie: session=<token>; HttpOnly; Secure; SameSite=Lax; Path=/43 ```4445 - `HttpOnly` — JavaScript cannot read the cookie (blocks XSS-based token theft)46 - `Secure` — cookie only sent over HTTPS47 - `SameSite=Lax` — blocks CSRF from cross-site form POST (see `prevent-csrf`)48 - `Path=/` — restrict to your app path, not subpaths of shared hosts49503. **Rotate session ID on privilege escalation** — generate a NEW session ID after login, role changes, or permission grants to prevent session fixation:5152 ```python53 # After successful login54 old_data = session.get_data()55 session.invalidate()56 new_session = session.create_new()57 new_session.set_data(old_data)58 new_session.set('user_id', authenticated_user.id)59 ```60614. **Enforce idle and absolute timeouts**:6263 ```python64 IDLE_TIMEOUT = 30 * 60 # 30 minutes of inactivity65 ABSOLUTE_TIMEOUT = 8 * 3600 # 8 hours regardless of activity6667 last_activity = session['last_activity']68 created_at = session['created_at']6970 if time.time() - last_activity > IDLE_TIMEOUT:71 session.invalidate()72 if time.time() - created_at > ABSOLUTE_TIMEOUT:73 session.invalidate()74 ```7576 PCI DSS requires ≤15 minutes idle timeout for cardholder data environments.77785. **Invalidate server-side on logout** — delete the session record from the server, not just the client cookie:7980 ```python81 @app.route('/logout', methods=['POST'])82 def logout():83 session_id = request.cookies.get('session')84 session_store.delete(session_id) # server-side deletion85 response = redirect('/login')86 response.delete_cookie('session')87 return response88 ```8990 Client-only logout (clearing the cookie without server deletion) leaves the token valid for hijacking.91926. **Use framework session management** — don't implement from scratch. Use Django's `django.contrib.sessions`, Spring's `HttpSession`, or Rails' `ActionDispatch::Session`. They handle storage, rotation, and timeout correctly.93947. **For high-security actions, re-authenticate** — prompt for password before account deletion, fund transfers, or email/password changes. Don't rely solely on session validity for irreversible operations.9596## Rules9798- Never store session IDs in URLs (`?sessionid=...`) — they appear in logs, referrer headers, and browser history.99- Session tokens must not contain user data (user ID, role) — store a random ID that maps server-side to user state.100- Concurrent session control (invalidate old sessions on new login) prevents credential-sharing; implement where security requirements demand it.101- Session fixation: always rotate ID on login; never accept a session ID set by the client pre-login.102103## Common Mistakes104105- **Using userID + timestamp as session token** — predictable, brute-forceable.106- **Deleting the cookie but not the server-side session on logout** — the token remains valid if captured.107- **Setting long absolute timeouts for convenience** — 30-day sessions mean a stolen token is valid for 30 days.108- **HttpOnly cookies + JWT in localStorage** — mixing models: choose one. HttpOnly cookies handle both transport and XSS protection.