đŸ›Ąïž Application Security CheatSheet

Authentication Deep Dive

Authentication answers: “Who are you?” It proves identity using something you know (password/PIN), something you have (phone, token), or something you are (biometrics).

Practical note: auth breaks most often at the seams — redirects, token storage, callback handling — not in the login form itself.

Most authentication bugs are not “crypto failures” — they’re workflow failures: weak password handling, broken session behavior, unsafe password reset, or missing protections against automated attacks.

Key idea: Authentication is a system: identity proofing + session issuance + ongoing session validation + recovery. If any piece is weak, the whole login is weak.

Why authentication bugs happen (deep reason)

Authentication is where “small” flaws become account takeover: weak reset, session fixation, missing MFA enforcement, or insecure token handling.

Mental model: identity → session → continued trust

  1. Identity proof: verify a secret or factor (password/MFA).
  2. Session issuance: create a server-tracked session or a signed token (cookie/JWT).
  3. Session protection: cookie flags, CSRF strategy, binding to device context where appropriate.
  4. Session lifecycle: expiration, logout, rotation, revocation, re-authentication for sensitive actions.
  5. Recovery: password reset / account recovery must be at least as strong as login.
experienced rule: Treat recovery as a privileged authentication path. If reset is weaker than login, attackers will use reset.

Core authentication failure modes

1) Credential handling

2) Session issues

3) Workflow flaws

4) Abuse controls

Session vs tokens: what to choose and what can go wrong

Server sessions (cookie session id → server store) make revocation and rotation easier. JWTs (self-contained tokens) can scale well but make revocation, key rotation, and claim correctness harder if implemented casually.

Deep dives (go deeper on key authentication topics)

How to use: Read Authentication first, then pick the deep dive that matches the system you’re interviewing for (web sessions, SSO, enterprise SAML, etc.).
Interview-safe phrasing: “JWT is not an authentication mechanism; it’s a token format. Your security depends on validation and lifecycle.”

Preventing regressions

Interview-ready answers (60-second + 2-minute)

60-second answer

Authentication is proving identity and issuing a session. I secure it by hashing passwords with a modern algorithm, preventing automation with rate limits and detection, and making session handling robust: rotate session IDs on login, use HttpOnly/Secure/SameSite cookies, short expiries, and revocation on logout. I treat password reset and magic links as high risk with single-use, short-lived tokens and anti-enumeration responses.

2-minute answer

I view authentication as a lifecycle: identity proof → session issuance → continued trust → recovery. On the credential side, use strong password hashing (bcrypt/argon2), protect secrets, and avoid leaking tokens in logs or URLs. On the session side, rotate IDs at login and privilege changes, enforce secure cookie flags, and implement expiration and revocation. For modern threats, I assume credential stuffing: rate limits, progressive throttling, device/IP risk signals, and monitoring. Finally, I harden recovery flows (reset tokens, magic links) to be single-use, short TTL, bound to the account and context, and I require step-up authentication for sensitive operations.

How authentication exploitation progresses (attacker mindset)

Conceptual only. Attackers usually look for the easiest path to “become a user”: weak reset, session bugs, missing MFA enforcement, or automation-friendly login endpoints.

Phase 1: Find alternate paths

Phase 2: Assess automation resistance

Phase 3: Target recovery

Phase 4: Persist

Interview takeaway: The highest-value fixes reduce attacker ROI: strong recovery, short token lifetimes, rotation, and robust abuse controls.

Tricky edge cases & bypass patterns (what attackers look for)

Safe validation workflow (defensive verification)

  1. Inventory auth surfaces: login, SSO, API tokens, password reset, MFA enrollment, device trust, logout.
  2. Check credential storage: confirm modern hashing and no secret leakage in logs/analytics.
  3. Check sessions: cookie flags, rotation on login, expiry, logout invalidation, and CSRF strategy.
  4. Check reset: short TTL, single-use, invalidated on password change, uniform responses to avoid enumeration.
  5. Check abuse controls: rate limits, throttling, monitoring, and alerting on suspicious patterns.
  6. Check MFA: consistent enforcement, step-up for high-risk actions, safe enrollment and recovery.
Avoid providing “how to bypass” steps. In interviews, focus on how you validate controls and prove correctness with logs and test cases.

Defensive patterns & fixes (Node.js)

Vulnerable pattern (minimal): weak session/cookie defaults + no rotation

import express from "express";
import session from "express-session";

const app = express();
app.use(express.urlencoded({ extended: false }));

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: true, // ❌ creates sessions before login
  cookie: { }              // ❌ missing Secure/HttpOnly/SameSite
}));

app.post("/login", async (req, res) => {
  const { username, password } = req.body;
  const user = await db.users.findByUsername(username);

  // ❌ simplified password check (concept); real code must use secure hash verification
  if (!user || user.password === password) {
    // ❌ wrong logic and weak checks are common sources of auth bugs
  }

  // ❌ no session rotation; fixation risk
  req.session.userId = user.id;
  res.redirect("/account");
});

Fixed pattern: strong password hashing + safe session issuance + rotation

import express from "express";
import session from "express-session";
import bcrypt from "bcrypt";

const app = express();
app.use(express.urlencoded({ extended: false }));

app.use(session({
  name: "sid",
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false, // ✅ only create session when needed
  cookie: {
    httpOnly: true,
    secure: true,      // ✅ require HTTPS in production
    sameSite: "lax",   // ✅ reduces CSRF risk for typical apps
    maxAge: 1000 * 60 * 60, // 1 hour (tune)
  }
}));

app.post("/login", async (req, res) => {
  const username = String(req.body.username || "");
  const password = String(req.body.password || "");

  const user = await db.users.findByUsername(username);
  // ✅ uniform failure response to reduce enumeration
  if (!user) return res.status(401).send("Invalid credentials");

  const ok = await bcrypt.compare(password, user.passwordHash);
  if (!ok) return res.status(401).send("Invalid credentials");

  // ✅ rotate session id on login to prevent fixation
  req.session.regenerate((err) => {
    if (err) return res.status(500).send("Login failed");
    req.session.userId = user.id;
    req.session.authTime = Date.now(); // helpful for step-up policies
    res.redirect("/account");
  });
});

app.post("/logout", (req, res) => {
  // ✅ destroy session server-side
  req.session.destroy(() => {
    res.clearCookie("sid");
    res.redirect("/");
  });
});

Defensive reset pattern (concept): single-use, short TTL tokens

// Concept only: store a hashed reset token + expiry; invalidate on use and on password change.
// - Never store raw tokens.
// - Token should be single-use and short-lived.
// - Responses should avoid account enumeration.
Reality check: Exact settings depend on your app (SSO, APIs, mobile). But the invariants are stable: strong credential storage, safe session issuance, rotation, expiry/revocation, and hardened recovery.

Confidence levels (how sure are you?)

ConfidenceWhat you observedWhat you can claim
Low Auth exists but flows and controls are unclear (SSO? reset? MFA?) “Potential weaknesses; need to map all auth surfaces and confirm session/reset controls.”
Medium Some controls present, but gaps exist (no rotation, long TTL, inconsistent MFA, weak throttling) “Likely auth hardening needed; recommend specific control improvements and regression tests.”
High Repeatable evidence of broken invariants (reset reuse, session not invalidated, secret leakage) “Confirmed authentication weakness with clear root cause and actionable remediation.”

Checklist (quick review)

Remediation playbook

  1. Contain: enable throttling and monitoring immediately for login/reset; rotate secrets if leakage suspected.
  2. Fix credentials: migrate to bcrypt/argon2; remove plaintext/weak hashing; scrub secrets from logs.
  3. Fix sessions: enforce cookie flags; rotate session ids at login; implement logout invalidation and short TTLs.
  4. Fix recovery: redesign reset tokens to be single-use + short-lived + hashed-at-rest; anti-enumeration responses.
  5. Fix MFA: ensure MFA is enforced consistently; add step-up for high-risk operations; harden enrollment and recovery.
  6. Prevent regressions: centralize auth logic; add tests for reset reuse, session rotation, logout invalidation; add alerts.

Interview Questions & Answers (Easy → Hard)

How to answer: Start with the lifecycle (prove identity → issue session → protect session → recover safely), then discuss automation threats and defense-in-depth.

Easy

  1. What’s the difference between authentication and authorization?
    A: Plain: authn is who you are; authz is what you can do. Deep: authn issues identity/session; authz evaluates policy on every request/object.
  2. Why is password reset often the weakest link?
    A: Plain: it’s a backdoor to login. Deep: it can bypass MFA and strong checks unless tokens are short-lived, single-use, and tied to account state.
  3. What cookie flags matter and why?
    A: Plain: they stop theft and accidental sending. Deep: HttpOnly reduces JS access, Secure requires HTTPS, SameSite reduces CSRF-like cross-site sends.
  4. What is account enumeration?
    A: Plain: learning whether a user exists. Deep: different error messages/timing leaks identity; fix with uniform responses and consistent behavior.
  5. What is session fixation?
    A: Plain: attacker forces a session id then user logs in. Deep: if session id isn’t rotated at login, an attacker-known id becomes authenticated; rotate/regenerate sessions on login.
  6. Why do we assume bots and stuffing today?
    A: Plain: leaked passwords are everywhere. Deep: automation is cheap; you need throttling, detection, and monitoring as default controls.

Medium

  1. Scenario: “Remember me” keeps users logged in for 30 days. What risks do you consider?
    A: Plain: stolen sessions last longer. Deep: use device-bound revocable tokens, rotate on use, shorten TTL where possible, and provide per-device logout/revocation.
  2. Scenario: Login has rate limiting, but password reset doesn’t. Why is that dangerous?
    A: Plain: attackers use the easiest door. Deep: reset becomes a high-signal abuse surface; throttle reset/OTP endpoints and monitor spikes.
  3. Follow-up: What makes a reset token “good”?
    A: Plain: short and one-time. Deep: random, single-use, short TTL, stored hashed, invalidated on password change, bound to user and optionally device/context.
  4. Scenario: You use JWTs for sessions. How do you handle logout?
    A: Plain: tokens should expire soon. Deep: short access-token TTL + refresh token rotation; server-side revocation lists for refresh tokens; key rotation strategy.
  5. Scenario: MFA exists but users can change email without MFA. What’s the issue?
    A: Plain: Someone can lock the real user out. Deep: sensitive changes need step-up authentication; enforce MFA for email/password/MFA changes.
  6. Follow-up: How do you reduce user friction while staying secure?
    A: Plain: only ask for more checks when needed. Deep: risk-based step-up: new device/IP, high-value actions, anomalous behavior; keep baseline login usable.
  7. Scenario: Different microservices validate tokens differently. Why is that risky?
    A: Plain: the weakest service becomes the entry. Deep: centralize validation libraries and enforce consistent issuer/audience/expiry checks; add contract tests.

Hard

  1. Scenario: You suspect credential stuffing in production. What’s your immediate response?
    A: Plain: slow it down and watch. Deep: enable throttles, add bot signals, monitor IP/device patterns, protect reset endpoints, and alert on spikes; coordinate with fraud/SOC.
  2. Scenario: How do you secure OAuth/OIDC login end-to-end?
    A: Plain: validate the provider response. Deep: verify issuer/audience, enforce state/nonce, handle redirects safely, and map external identity to internal user with strong linking rules.
  3. Follow-up: What’s the most common “experienced miss” in authentication?
    A: Plain: forgetting recovery. Deep: reset and enrollment flows aren’t treated as privileged; missing idempotency/limits and inconsistent MFA enforcement.
  4. Scenario: How do you implement step-up authentication?
    A: Plain: re-check identity for risky actions. Deep: require recent authTime and/or MFA for sensitive endpoints; keep policy centralized and auditable.
  5. Follow-up: How do you handle session revocation at scale?
    A: Plain: keep sessions short and track them. Deep: for server sessions, invalidate in store; for tokens, use short TTL + refresh rotation + revocation store; build key rotation playbooks.
  6. Scenario: A user reports “I got logged out randomly.” What security design might cause this?
    A: Plain: safety checks can invalidate sessions. Deep: device binding, IP changes, aggressive TTLs, or rotation logic; tune with risk signals and good UX messaging.
  7. Follow-up: How do you keep authentication consistent across web and mobile?
    A: Plain: share the same rules. Deep: centralized auth service/libraries, consistent token/session lifecycle, and consistent recovery/MFA policies with platform-appropriate storage.
Safety note: for understanding +