Last updated: May 1, 2026
Why this module exists. Every web app makes session decisions in the first month of development that they regret 18 months later. The wrong choice between cookies and tokens, the wrong refresh strategy, the wrong idle timeout — each is technical debt that becomes a breach footnote. This module is the playbook for getting it right the first time.
The four session storage options
| Mechanism | Where it lives | Strengths | Weaknesses |
|---|---|---|---|
| Server-side session + cookie ID | Cookie holds opaque session ID; server has the data | Easy revocation; easy to extend; battle-tested | Server-side state; sticky sessions or shared session store needed |
| Stateless JWT in cookie | Cookie holds the JWT | Stateless; works across services | Hard to revoke before expiry; JWT validation bugs |
| JWT in localStorage | JS-readable | Easy for SPAs | XSS reads it; no httpOnly protection |
| Refresh + access token pair | Refresh in httpOnly cookie; access in memory | Best of both; short access lifetime; refresh revocable server-side | More complexity |
The recommendation for 2026
For new apps: refresh + access token pair. Refresh token in HttpOnly + Secure + SameSite=Lax cookie, lifetime ~30 days, server-side revocation list. Access token in memory (not cookie, not localStorage), lifetime ~15 minutes. Auto-refresh in the background.
For server-rendered apps with traditional auth: server-side session + secure cookie. Don’t reinvent.
For pure microservices with internal-only auth: stateless JWT signed by an internal CA, with a short lifetime (5-10 minutes), can work — but treat client-facing sessions differently.
Cookie attributes that matter
- HttpOnly — JS can’t read. Mitigates session theft via XSS. Mandatory for any session cookie.
- Secure — only sent over HTTPS. Mandatory in 2026; HTTP-only sites shouldn’t exist.
- SameSite=Lax — sent on top-level navigations only; prevents CSRF on most cases. Default for new browsers.
- SameSite=Strict — never sent cross-site; breaks deep-linking but maximally secure.
- SameSite=None; Secure — sent everywhere; only when you specifically need cross-site cookies (e.g., embedded iframe).
- Domain — usually omit (defaults to host-only). Setting Domain=.example.com makes the cookie available to all subdomains; rarely what you want.
- Path=/ — usually fine; finer paths add complexity without much security.
- __Host- prefix — modern browsers treat
__Host-idcookies as Secure + Path=/ + no Domain. Consider for high-security cookies.
Idle timeout vs absolute timeout
Two different timers:
- Idle timeout — session expires N minutes after last activity. 15-30 minutes for standard apps; 5 minutes for high-stakes (banking).
- Absolute timeout — session expires N hours after creation regardless of activity. 8 hours for standard apps; force re-auth daily for high-stakes.
Both should be enforced. Absolute timeout protects against long-lived stolen tokens.
Session fixation
Attacker sets a known session ID on victim’s browser (via XSS, same-site script injection, or sometimes URL parameter). Victim logs in. Attacker now uses the same session ID, lands inside victim’s account.
Fix: regenerate session ID on every authentication state change. Login, logout, privilege change. PHP: session_regenerate_id(true). Express: rebuild session.
Logout — the operation people forget
Logout must:
- Invalidate the session server-side (delete from session store / blacklist the JWT).
- Clear the cookie client-side (
Set-Cookie: session=; Max-Age=0). - Optionally redirect to a “you’re logged out” page that doesn’t require auth.
Common bug: setting an expired cookie but not invalidating server-side. The token is still valid; an attacker who captured it earlier can still use it.
Refresh token rotation
Modern best practice: each time a refresh token is used, a new one is issued and the old one is invalidated. If both old and new are presented (the user’s session was forked into two devices, or it was stolen), revoke the entire chain.
This is what Auth0, Cloudflare Access, Microsoft Entra all do by default in 2026.
Real-world cases
- Many bug-bounty disclosures for cookies missing
HttpOnlyon session cookies. Each enables XSS-to-account-takeover chains. - 2018 Drupalgeddon family — sessions persisted across logout in some implementations.
- OAuth implementations with refresh tokens that lasted years and weren’t rotated. Stolen tokens used months after the breach.
Try this yourself
# Audit your session cookies
curl -sI -c - https://target.com/login -d "user=test&pass=test" \
| grep -i "Set-Cookie"
# Look for HttpOnly, Secure, SameSite
# Test session fixation
# 1. Get a session ID without authenticating
SID=$(curl -s -c cookies.txt https://target.com/ | grep -i "session=")
# 2. Use that exact session to log in
curl -b cookies.txt -d "user=test&pass=test" https://target.com/login
# 3. Compare cookie before and after; if same → fixation possible
# Check token rotation (for OAuth flows)
# Use refresh token twice; second use should fail or trigger revocation
Defender’s checklist
- HttpOnly, Secure, SameSite=Lax on every session cookie.
- Regenerate session ID on auth state change.
- Idle and absolute timeouts both enforced server-side.
- Server-side revocation capability for every session, even if using JWTs (maintain a small denylist).
- Refresh token rotation with reuse detection.
- Logout invalidates server-side and clears client cookie.
- Audit log every session creation, refresh, and revocation. Investigation of compromised accounts depends on this.
Module Quiz · 6 questions
Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.
Practical depth on what to tune, what to harden, and how this maps to Indian regulatory expectations.
Session in 2026 — beyond cookies
Modern session management blends multiple primitives:
Hardening + detection + India context
Device-bound session credentials — the next-gen pattern
Cookie theft remains the dominant route to account takeover. Stolen cookies replayed from attacker infrastructure work because the server cannot distinguish replay. Device-bound session credentials (DBSC) — Chrome 125+ — bind a session to a device-specific key in the TPM / Secure Enclave; every request signs a challenge with that key; replay from a different device fails. WebAuthn-PRF achieves similar binding via FIDO2 authenticator. Trade-offs:
Session forensics — what investigators look for
During an account-takeover investigation, session-related evidence is critical. Logs to preserve:
Performance discipline that strengthens security
A practical performance discipline that applies regardless of the specific vulnerability class is to instrument every endpoint with three SLOs: latency at the 50th, 95th, and 99th percentiles. The 50th percentile reflects typical user experience, the 95th catches tail behaviour visible to a meaningful fraction of users, and the 99th captures the long-tail outliers that often hide bugs (timeouts on a stale dependency, locking contention under load, garbage-collection pauses on a hot endpoint). Every release should compare these percentiles against the previous baseline; regressions of more than ten percent on the 95th percentile are typically worth investigating before shipping. Modern observability stacks make this routine — Datadog APM, New Relic, Honeycomb, Grafana Tempo with OpenTelemetry instrumentation, and on the open-source side Jaeger plus Prometheus plus Grafana — but the discipline matters more than the tool. Indian product teams that have adopted this percentile-driven culture report fewer surprise outages and a smaller incident-response load over time, which compounds into a stronger security posture: the same instrumentation that catches a slow endpoint also catches an exploitation attempt that forces unusual code paths.
Observability that catches attacks alongside outages
Observability for security overlaps with observability for reliability but adds a few specific signals worth instrumenting. First, application-layer authentication and authorisation events should produce structured logs with the user identifier, the action attempted, the source IP, the User-Agent fingerprint, and the outcome. Second, every state-changing API call should log its idempotency key, the request body shape, and the resulting object identifier. Third, every external dependency call should log the destination, the response code, and the latency. Together these three categories produce a clean event stream that a SIEM can correlate to detect both functional regressions and active attacks. The cost is moderate — log storage in Elasticsearch or Splunk runs perhaps thirty to sixty rupees per gigabyte per year at typical Indian-tier prices — and the payoff is dramatic: incidents that previously took days to investigate are typically resolved in hours when the relevant evidence has been pre-indexed. Indian regulators increasingly expect this level of operational logging, particularly RBI under the Cyber Security Framework Annex 1 and SEBI under the CSCRF master circular.
DPDP and sectoral obligations a practitioner cannot ignore
Under India’s Digital Personal Data Protection Act 2023, the operational obligations on any web application that handles personal data extend beyond simple consent collection. Section 8 requires that data fiduciaries implement reasonable security safeguards — interpreted in practice as reflecting a documented information security programme, regular vulnerability assessment, and demonstrable controls aligned to a recognised standard such as ISO 27001 or NIST CSF. Section 9 imposes data principal rights including access, correction, and erasure, which means the application must be architected so that these requests can be fulfilled within the prescribed timeframes (currently expected to be on the order of thirty days). Section 8(6) imposes breach notification: when a personal-data breach occurs, the data fiduciary must notify the Data Protection Board and affected data principals within prescribed timeframes (the draft Rules suggest seventy-two hours for material breaches). For the practitioner this translates into specific engineering tasks: data inventory and lineage tracking, retention controls and automated deletion at end-of-purpose, audit-grade logging of every access to personal data, breach-detection telemetry, and a formal incident-response playbook with regulatory-notification templates. The 2024-2025 inspections by RBI and SEBI of regulated entities have already cited DPDP-overlay obligations, so the alignment is not theoretical; it shapes what auditors expect to see in the next inspection cycle.
A small threat-modelling routine before every release
A short threat-modelling exercise specific to this vulnerability class is worth running before each release. The classic STRIDE framework — Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege — provides a useful checklist when applied to the specific data flow at hand. Begin by drawing the data flow for the feature being changed: external actors at the edge, the trust boundaries they cross, the back-end services involved, the data stores read or written, and the third-party integrations called. For each trust boundary crossing, ask which STRIDE categories apply and what controls mitigate them. The output is a small set of testable assertions: this endpoint must not allow tenant A to read tenant B’s records, this mutation must require step-up authentication, this third-party call must validate the response signature, and so on. Convert each assertion into an automated test or a manual verification step in the release checklist. The discipline pays off in two ways: first, it catches design-level bugs before they reach code review; second, it produces an auditable record of security thinking that regulators value. Indian product teams that have institutionalised this practice report fewer security incidents and shorter mean-time-to-remediate when issues are found, which compounds into better customer trust and lower regulatory friction over time.
Further reading
Additional FAQs
Cookie or JWT — which should I default to?
For new web apps in 2026: server-side session ID in HttpOnly cookie. Stateless JWT only when you genuinely need stateless (cross-domain, multi-service, mobile). Most “we use JWT” apps would be simpler and safer with classic sessions.
How do I implement "log out all devices"?
Server-side session table — delete all entries for the user. JWT — increment a per-user version claim and reject tokens with old version; combined with short access-token lifetimes, propagation is fast.
Custom team training + practitioner advisory
Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.