Skip to content
bughra.dev
Go back

Session Management and Cookie Security

Introduction to Session Management

Session management is the process of securely maintaining a user’s state and identity across multiple requests in web applications. Since HTTP is stateless by design, sessions provide continuity for user interactions by associating requests with specific users.

Session Security Fundamentals

Key Security Components

Cookies Overview

Cookies are small pieces of data stored by the browser and sent with HTTP requests to the same domain. They’re commonly used for:

  1. Session Cookies: Temporary, deleted when browser closes
  2. Persistent Cookies: Long-lived with specific expiration date
  3. First-party Cookies: Set by the current domain
  4. Third-party Cookies: Set by domains other than the current one

Cookie attributes like HttpOnly, Secure, and SameSite are defined by the server, but it’s the browser (client) that enforces them. {: .prompt-info }

Secure Attribute

Set-Cookie: sessionid=abc123; Secure

HttpOnly Attribute

Set-Cookie: sessionid=abc123; HttpOnly

SameSite Attribute

Set-Cookie: sessionid=abc123; SameSite=Strict

Path Attribute

Set-Cookie: sessionid=abc123; Path=/app

Domain Attribute

Set-Cookie: sessionid=abc123; Domain=example.com

Secure Session Implementation

Setting Secure Cookies

Node.js Example

res.cookie('sessionid', 'abc123', {
  httpOnly: true,
  secure: true,
  sameSite: 'strict',
  path: '/',
  maxAge: 3600000 // 1 hour
});

PHP Example

setcookie("sessionid", "abc123", [
  'expires' => time() + 3600,
  'path' => '/',
  'domain' => 'example.com',
  'secure' => true,
  'httponly' => true,
  'samesite' => 'Strict'
]);

Python (Django) Example

response.set_cookie(
  'sessionid', 
  'abc123', 
  httponly=True,
  secure=True,
  samesite='Strict',
  max_age=3600,
  path='/'
)

Best Practices Summary

  1. Always use HttpOnly and Secure flags for authentication cookies
  2. Implement proper SameSite restrictions (preferably Strict or Lax)
  3. Use specific Path and Domain restrictions when possible
  4. Set appropriate expiration times based on sensitivity
  5. Regenerate session IDs after authentication or privilege changes
  6. Implement proper session termination on logout
  7. Use session timeouts for both idle and absolute time
  8. Consider cookie encryption for sensitive data
  9. Implement CSRF protections alongside cookie security
  1. Session Hijacking: Stealing session cookies to impersonate users
  2. Cross-Site Scripting (XSS): Stealing cookies via malicious JavaScript
  3. Cross-Site Request Forgery (CSRF): Making unauthorized requests using valid sessions
  4. Session Fixation: Forcing users to use attacker-controlled session IDs
  5. Cookie Tossing: Exploiting subdomain cookie handling

References


Share this post on:

Previous Post
Generators in Python
Next Post
Session Fixation Attack