Lecture 27: Cookies & Session Tracking

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-11

Lecture 27

Cookies & Session Tracking

Week 9 | Unit III: Servlets
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Explain stateless HTTP and formal need for session tracking
  • Understand complete cookie model: creation, scope, expiry, transport
  • Implement cookie CRUD with robust servlet code patterns
  • Evaluate security and privacy risks in cookie usage
  • Compare cookies with alternative tracking techniques
  • Design secure remember-me style flows

Unit III Topic Traceability


Primary syllabus topic:

  • Session tracking using cookies

Conceptual progression:

  • Lecture 26: request navigation
  • Lecture 27: browser-side tracking
  • Lecture 28: server-side session tracking (HttpSession)

Revisiting Stateless HTTP


HTTP request processing is independent by design.

Implication:

  • server cannot infer user continuity from protocol alone

Tracking is therefore an application-level layer built on top of HTTP.

What Breaks Without Tracking


Without tracking, systems fail in practical use cases:

  • authentication continuity
  • shopping cart persistence
  • multi-step forms and workflow states
  • personalization and preferences
  • activity auditing per user session

Cookie: Formal Definition


Cookie is a small piece of state sent by server and stored by browser, later returned in matching requests.

Important characteristics:

  • client-stored, server-defined metadata
  • scoped by domain/path rules
  • governed by expiry and security flags

HTTP Header-Level View


HTTP/1.1 200 OK
Set-Cookie: lang=en; Path=/; Max-Age=2592000; HttpOnly; Secure; SameSite=Lax
GET /dashboard HTTP/1.1
Cookie: lang=en; theme=dark

Cookie Lifecycle in Browser


flowchart LR
  A[Server emits Set-Cookie] --> B[Browser stores cookie]
  B --> C[User navigates matching URL]
  C --> D[Browser sends Cookie header]
  D --> E[Server interprets state]
  E --> F[Cookie expires/deleted/overwritten]

Cookie Attributes Deep Dive


Attribute Function Design Note
Name/Value core pair keep value compact
Expires/Max-Age lifetime policy use short life for auth-related state
Domain host matching avoid overly broad domain when possible
Path URL prefix scope least privilege path reduces exposure
HttpOnly blocks JS read access strong XSS mitigation layer
Secure HTTPS-only transport mandatory for auth cookies
SameSite cross-site sending policy CSRF risk control

Domain and Path Scope Semantics


Scope controls where browser sends cookie.

Examples:

  • Path=/app -> sent to /app/*, not to /admin/*
  • restrictive scope improves security boundaries
  • broader domain scope can unintentionally share cookie across subdomains

Creating Cookies in Servlet


Cookie preference = new Cookie("theme", "dark");
preference.setPath("/");
preference.setMaxAge(30 * 24 * 60 * 60);
preference.setHttpOnly(true);
preference.setSecure(true);
response.addCookie(preference);

Reading Cookies Safely


Cookie[] cookies = request.getCookies();
String theme = "light";

if (cookies != null) {
  for (Cookie c : cookies) {
    if ("theme".equals(c.getName())) {
      theme = c.getValue();
      break;
    }
  }
}

Always handle null cookie array safely.

Updating Cookie Value Correctly


Cookie updated = new Cookie("theme", "light");
updated.setPath("/");
updated.setMaxAge(30 * 24 * 60 * 60);
response.addCookie(updated);

Update means overwrite with same identity (name + path + domain).

Deleting Cookie Correctly


Cookie remove = new Cookie("theme", "");
remove.setPath("/");
remove.setMaxAge(0);
response.addCookie(remove);

Wrong path/domain is the most common reason cookie deletion appears to fail.

Cookie Types in Practice


Type Lifetime Typical Use
Session cookie browser session only temporary flow state
Persistent cookie until expiry preferences, remember-me token id
First-party cookie same site app-level continuity
Third-party cookie external embedded domains analytics/ads context

Size and Count Constraints


Practical limitations:

  • roughly 4 KB per cookie (implementation dependent)
  • limited number per domain
  • all sent cookies increase request header size

Design implication: keep cookie payload minimal and tokenized.

Cookie Security Threat Model


Threat Risk Mitigation
XSS token theft via JS HttpOnly, output encoding, CSP
MITM on HTTP cookie sniffing Secure + HTTPS everywhere
CSRF cross-site action abuse SameSite, CSRF token
Client tampering modified values server-side validation/signing

SameSite Policy Selection


Policy options:

  • Strict: strongest isolation, may affect UX
  • Lax: practical default for many apps
  • None: cross-site required, must pair with Secure

Selection depends on app navigation model and security posture.

What Must Never Be in Cookies


  • raw password
  • OTP values
  • complete user profile JSON
  • bank or card details
  • unencrypted personally sensitive records

Store opaque identifiers; resolve sensitive state on server.

Remember-Me Architecture Pattern


sequenceDiagram
  participant B as Browser
  participant A as App Server
  participant D as Token Store

  B->>A: Login with remember-me checked
  A->>D: Persist random token hash + user id
  A-->>B: Set rememberToken cookie
  B->>A: Future request with token cookie
  A->>D: Validate token and device context
  A-->>B: Restore authenticated session

Remember-Me Code Pattern


String token = tokenService.generateOpaqueToken(userId);
Cookie remember = new Cookie("rememberToken", token);
remember.setHttpOnly(true);
remember.setSecure(true);
remember.setPath("/");
remember.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(remember);

Persist only token reference server-side; rotate and revoke on logout.

All Four Session Tracking Techniques


Technique Suitable For Limitation
Cookies preferences, lightweight client-side continuity client-controlled, limited size
URL rewriting cookie-disabled fallback session id visible in URL
Hidden form fields controlled form chains not global navigation-safe
HttpSession secure server-side state memory/distribution concerns

The four standard tracking techniques in servlet syllabus context are: Cookies, URL rewriting, Hidden form fields, and HttpSession.

Cookie Disabled: URL Rewriting


String encoded = response.encodeURL("dashboard.jsp");
response.sendRedirect(encoded);

Container appends session id when necessary; use cautiously due to URL exposure.

Practical Debugging Workflow


Debug steps:

  1. inspect response Set-Cookie header
  2. verify browser storage and expiry metadata
  3. inspect request Cookie header on next call
  4. confirm path/domain/sameSite matching
  5. test HTTPS vs HTTP behavior for Secure

Frequent Implementation Issues


  • cookie deleted with wrong scope
  • auth cookie missing HttpOnly/Secure
  • oversized cookie payload causing truncation or rejection
  • trusting unsigned client cookie data
  • assuming third-party cookie acceptance in modern browsers

Case Study: Personalized Dashboard


Requirement:

  • remember language and theme for 30 days
  • keep auth state secure

Design:

  • cookie for language/theme preferences
  • server session/token for authentication state
  • clear both on logout

Exam and Viva Questions


Prepare conceptual + practical answers:

  1. explain cookie lifecycle and attributes
  2. compare cookie with HttpSession
  3. write servlet code for cookie CRUD
  4. explain HttpOnly, Secure, SameSite
  5. discuss remember-me secure architecture

Hands-On Task


Build preference module:

  • set theme cookie from settings page
  • load preference at login page and dashboard
  • add cookie deletion on reset
  • verify behavior in browser dev tools

Extension challenge:

  • add signed cookie validation for tamper detection.

Summary


You should now be able to:

  • model cookie tracking with protocol-level clarity
  • implement secure cookie handling patterns
  • evaluate trade-offs among tracking approaches
  • solve cookie/session questions at MCA theory and lab level