Skip to content
Back to CurriculumLesson 05 of 30
sessions-cookiesIntermediate

The Session Lifecycle: Creation, Hijacking, Fixation, Idle/Absolute Expiration & Logout

A session represents authenticated state between client and server. Robust session management enforces cryptographic ID generation, regenerates session IDs upon privilege change (neutralizing Session Fixation), tracks both idle and absolute timeouts, and ensures complete server-side destruction on logout.

Interactive Visual Concept ExplainerStep-by-Step Educational Simulation
Visual Step-by-Step Concept Explainersessions-cookies
The Session Lifecycle: Creation, Hijacking, Fixation, Idle/Absolute Expiration & Logout
Steps:
Session Fixation DefenseRegeneration
Attacker Pre-Set ID: SESS_TRAP_001
Post-Login Minted ID: [ Waiting for login ]
On authentication, old session identifier is instantly destroyed. Attacker cookie points to dead session.
Dual Timeout MatrixRFC 6265
Idle Timeout
15 Minutes
Sliding: resets on user activity
Absolute Lifetime
8 Hours Max
Hard stop: forces re-authentication
Step 1 of 6
Auto-stepping (1x)

Step 1: Client submits valid authentication credentials to /login.

Security Guarantee: Always regenerate the session ID immediately upon login and privilege elevation to defeat Session Fixation.
Why This Architectural Concept Exists

HTTP is a stateless protocol. Applications need a mechanism to remember who is making requests. If session management is flawed, attackers can fixate, steal, or indefinitely replay session credentials.

Intuitive Mental Model

The Hotel Keycard with Auto-Deactivation: When you check in, you receive a keycard. If you upgrade from standard to the penthouse suite, the front desk cancels the old keycard and burns a new one (Session Regeneration). If you leave your room door closed for 30 minutes, the lock auto-engages (Idle Timeout). Even if you keep using the card, it stops working after 11:00 AM on checkout day (Absolute Timeout).

Architectural System TopologyProtocol Diagram
[ Client ]                                      [ CosmosApp Server ]      [ Redis Session Store ]
    │                                                      │                         │
    ├── (1) POST /login (credentials) ────────────────────►│                         │
    │                                                      ├── Generate sess_101 ────►│ SET sess_101 { user: 42 }
    │◄── (2) Set-Cookie: sid=sess_101; HttpOnly; SameSite ─┤                          │     (TTL: 15m idle)
    │                                                      │                         │
    ├── (3) GET /dashboard (Cookie: sid=sess_101) ────────►│── Check & Refresh TTL ──►│ EXPIRE sess_101 900
    │                                                      │                         │
    ├── (4) Privilege Change (Standard -> Admin) ──────────►│── Destroy sess_101 ────►│ DEL sess_101
    │                                                      ├── Create sess_202 ─────►│ SET sess_202 { admin: true }
    │◄── (5) Set-Cookie: sid=sess_202 (Session Regen) ─────┤                         │
    │                                                      │                         │
    ├── (6) POST /logout ─────────────────────────────────►│── Delete from Redis ───►│ DEL sess_202
    │◄── (7) Set-Cookie: sid=; Max-Age=0 (Cookie Clear) ───┤                         │
CosmosApp Production Milestone

CosmosApp authenticates users and issues high-entropy session IDs stored in Redis. To prevent Session Fixation (where an attacker gives a victim a pre-generated session ID), CosmosApp regenerates the session ID immediately upon login. It sets a 15-minute sliding idle timeout and an 8-hour absolute maximum session lifetime.

Step-by-Step Execution Sequence
01

Step 1: Client submits valid authentication credentials to /login.

02

Step 2: Server regenerates the session ID to neutralize Session Fixation attacks.

03

Step 3: Server stores the session payload in Redis with an idle TTL (e.g., 15 minutes) and absolute expiration timestamp (e.g., 8 hours).

04

Step 4: Server sends the session ID in a Set-Cookie header with HttpOnly, Secure, and SameSite=Lax/Strict flags.

05

Step 5: On each incoming request, the server verifies the session and extends the idle TTL (sliding window) as long as absolute expiration has not passed.

06

Step 6: On /logout, the server deletes the session key from Redis and sends Set-Cookie with Max-Age=0 to clear client state.

Production Architecture Blueprint
// CosmosApp Session Lifecycle Implementation:
export async function handleRequest(req: Request) {
  const sessionId = getCookie(req, 'sid');
  if (!sessionId) return { authenticated: false };

  const session = await redis.get(`session:${sessionId}`);
  if (!session) return { authenticated: false };

  const parsed = JSON.parse(session);
  const now = Date.now();

  # 1. Check Absolute Expiration (8 hours max lifetime)
  if (now > parsed.absoluteExpiresAt) {
    await redis.del(`session:${sessionId}`);
    return { authenticated: false, reason: "Absolute session lifetime expired" };
  }

  # 2. Extend Sliding Idle Timeout (15 minutes of inactivity)
  await redis.expire(`session:${sessionId}`, 15 * 60);

  return { authenticated: true, user: parsed.user };
}
Common Architectural Misconceptions
  • ✕Sliding idle timeouts alone are enough (Without an absolute timeout, a session can remain alive perpetually if kept active).
  • ✕Deleting the cookie on the client side logs the user out (The session remains completely valid on the server unless explicitly purged from storage).

Key Architectural Takeaways

  • ✓Always regenerate the session ID immediately upon login and privilege elevation to defeat Session Fixation.
  • ✓Enforce two distinct timeouts: a sliding idle timeout (15–30 mins) and an absolute ceiling (8–12 hours).
  • ✓Ensure /logout destroys server-side session state and explicitly clears the client cookie.
Common Architectural Pitfall

Failing to regenerate session IDs upon login. An attacker tricks the victim into using a known session ID, and gains access once the victim logs in.

Production Best Practice Fix

Regenerate the session identifier immediately upon successful authentication.

Interactive Knowledge Check

Why must a secure session system enforce an absolute timeout in addition to an idle timeout?