🛡️ Application Security CheatSheet

Session Management & Cookies

Sessions let a server remember who you are between requests. The browser stores a cookie with a random session ID; the server uses it to look up your session data.

Practical note: these issues usually slip through because everything looks “fine” in happy-path testing — until one weird request hits production.

Beginner mental hook: Cookie = “key”; Session store = “lockbox.” If the key is stolen or reused incorrectly, the attacker becomes you.

Mental model

  1. Login: server creates session data and sets a cookie containing a random session ID.
  2. Request: browser automatically sends the cookie to the server.
  3. Server: looks up session ID in the session store and decides identity/permissions.
  4. Logout: server destroys session and clears cookie.

Common failure modes (what goes wrong)

A) Session fixation (no rotation)

B) Insecure cookie settings

C) Weak invalidation / long TTLs

D) CSRF confusion

Defensive patterns (Node.js)

Secure session setup (Express)

import session from "express-session";

app.set("trust proxy", 1); // if behind a reverse proxy

app.use(session({
  name: "sid",
  secret: process.env.SESSION_SECRET,  // high entropy, rotated
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    maxAge: 60 * 60 * 1000, // 1 hour
  }
}));

Rotate on login (prevents fixation)

app.post("/login", async (req, res) => {
  const user = await authenticate(req.body);
  if (!user) return res.status(401).send("bad credentials");

  req.session.regenerate(() => {           // âś… new session ID
    req.session.userId = user.id;
    req.session.authTime = Date.now();
    res.send("ok");
  });
});

Destroy on logout

app.post("/logout", (req, res) => {
  req.session.destroy(() => {
    res.clearCookie("sid");
    res.send("logged out");
  });
});
Guardrails: rotate, set cookie flags, set TTLs, and pair cookie-based auth with CSRF strategy.

Safe validation (defensive verification)

Interview Questions & Answers (Easy → Hard)

Easy

  1. What is a session?
    A: Plain: server memory of login. Deep: session ID cookie maps to server-side data.
  2. Why HttpOnly?
    A: Plain: prevents JS reading cookies. Deep: reduces session theft via XSS (not a full fix for XSS).
  3. Why Secure?
    A: Plain: cookie only over HTTPS. Deep: prevents network sniffing on HTTP links/misconfig.
  4. What is SameSite?
    A: Plain: limits cross-site cookie sending. Deep: reduces CSRF risk; choose Lax/Strict based on UX.
  5. What is logout supposed to do?
    A: Plain: end session. Deep: destroy server session + clear cookie.
  6. Session vs JWT?
    A: Plain: server vs token. Deep: sessions simplify revocation; JWT needs lifecycle controls.
  7. Why rotate session IDs?
    A: Plain: stop fixation. Deep: prevents pre-set IDs becoming authenticated.

Medium

  1. Scenario: session ID not regenerated on login. Risk?
    A: Plain: fixation. Deep: victim logs into attacker-known session ID; fix with regenerate.
  2. Scenario: long session TTL. Risk?
    A: Plain: stolen sessions last longer. Deep: tighten TTL; add idle/absolute timeouts and revocation events.
  3. Scenario: cookie-based auth, no CSRF tokens. Risk?
    A: Plain: CSRF. Deep: cookies auto-send; protect state-changing routes with CSRF strategy.
  4. Follow-up: Lax vs Strict?
    A: Plain: strict blocks more. Deep: Lax is common baseline; pair with CSRF tokens for sensitive actions.
  5. Scenario: “Remember me” implemented as a long cookie. Fix?
    A: Plain: use refresh-like server state. Deep: persistent token bound to device with revocation and rotation.
  6. Follow-up: where to store sessions?
    A: Plain: central store. Deep: Redis/DB session store for scale; TTL-managed; revokeable.
  7. Scenario: session stolen. What should happen?
    A: Plain: detect/revoke. Deep: anomaly detection, forced logout, step-up on risky actions.

Hard

  1. How do you design session revocation at scale?
    A: Plain: central tracking. Deep: server-side store + per-device sessions + revoke on events + telemetry.
  2. How do you prevent session replay across devices?
    A: Plain: bind to device signals. Deep: device/session IDs, rotate tokens, detect impossible travel, and step-up.
  3. How do you secure “change email/password” endpoints?
    A: Plain: require extra checks. Deep: step-up + recent auth + CSRF + session rotation after change.
  4. What telemetry matters?
    A: Plain: unusual logins. Deep: session creation spikes, failed CSRF, device changes, abnormal IP patterns.
  5. Scenario: reverse proxy + Secure cookies issues. Fix?
    A: Plain: trust proxy config. Deep: set trust proxy and ensure HTTPS termination is correct so cookies are Secure.
  6. When choose BFF pattern?
    A: Plain: to avoid tokens in browser. Deep: web app uses server session; backend calls APIs with tokens safely server-side.

Exploitation progression (attacker mindset)

Checklist

Remediation playbook

  1. Enable strict cookie flags and enforce HTTPS-only cookies.
  2. Implement session rotation at login and privilege transitions.
  3. Add idle + absolute timeouts; ensure logout destroys server session state.
  4. Add CSRF protection to state-changing endpoints if cookie-based auth is used.
  5. Add “active sessions” management and revoke sessions on password reset/security events.
  6. Add tests for rotation, invalidation, and CSRF enforcement.