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.
Why authentication bugs happen (deep reason)
- Trust boundary confusion: treating client state (âlogged inâ) as authoritative rather than server-side session state.
- Weak credential lifecycle: poor password policies, unsafe storage, missing rotation/revocation, or leaked secrets.
- Broken recovery flows: password reset and âmagic linksâ often bypass the strongest controls.
- Automation pressure: credential stuffing and bots are the default threat; missing rate-limits and abuse controls causes takeovers.
- State is hard: sessions, tokens, device trust, and MFA introduce complexity and edge cases.
Mental model: identity â session â continued trust
- Identity proof: verify a secret or factor (password/MFA).
- Session issuance: create a server-tracked session or a signed token (cookie/JWT).
- Session protection: cookie flags, CSRF strategy, binding to device context where appropriate.
- Session lifecycle: expiration, logout, rotation, revocation, re-authentication for sensitive actions.
- Recovery: password reset / account recovery must be at least as strong as login.
Core authentication failure modes
1) Credential handling
- Passwords stored/checked unsafely (weak hashing, missing salt, custom crypto).
- Passwords or tokens leaked via logs, URLs, referrers, analytics, or error traces.
2) Session issues
- Session fixation, long-lived sessions without rotation, missing logout invalidation.
- Insecure cookies (missing
HttpOnly/Secure/SameSite), weak session IDs.
3) Workflow flaws
- Login bypass via alternate endpoints, partial checks, or inconsistent enforcement.
- Password reset/magic link weaknesses (token reuse, weak expiry, account enumeration).
4) Abuse controls
- No rate limiting, no lockout strategy, no bot detection, no monitoring for stuffing patterns.
- MFA optional but not enforced for risky actions; step-up auth missing.
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.
- Sessions: protect session IDs like passwords; rotate after login and privilege changes; enforce cookie flags.
- JWTs: verify signature, issuer/audience, expiry; minimize sensitive claims; plan revocation (short TTL + refresh token strategy).
Deep dives (go deeper on key authentication topics)
- JWT (Access Tokens & Refresh Tokens)
- OAuth 2.0 / OpenID Connect & SSO
- SAML (Enterprise SSO)
- Session Management & Cookies
- MFA / Step-up Authentication
- Password Reset & Account Recovery
- API Keys, Personal Tokens & Service Credentials
Preventing regressions
- Centralize auth: one authentication module/middleware; avoid ad-hoc checks across routes.
- Invariant tests: âlogout invalidates sessionâ, âreset token single-useâ, âMFA required for sensitive actionsâ.
- Telemetry: monitor failed logins, suspicious IP/device changes, token reuse, and reset activity spikes.
- Key management: rotation playbooks for signing keys/secrets; never hardcode secrets in repos.
- Secure defaults: framework-level cookie settings and standardized token validation.
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
- Multiple login endpoints (web, mobile, legacy), SSO callbacks, or âmagic linkâ flows with different rules.
Phase 2: Assess automation resistance
- Rate limits, lockout strategy, bot detection, and telemetry coverage.
Phase 3: Target recovery
- Reset tokens, OTP flows, email change and MFA enrollment flows (often weaker than core login).
Phase 4: Persist
- Long-lived sessions, refresh tokens, device trust, and âremember meâ behavior.
Tricky edge cases & bypass patterns (what attackers look for)
- Account enumeration: different errors/timings for âuser existsâ vs âwrong passwordâ. Prefer uniform responses and consistent timing where feasible.
- Reset token replay: tokens not invalidated after use or not tied to the latest password change.
- Session fixation: session id not rotated after login; attacker-provided session can become authenticated.
- Remember-me tokens: long-lived tokens stored insecurely or not revocable per device.
- MFA gaps: MFA enforced at login but not at sensitive actions; or âtrusted deviceâ logic is too permissive.
- OAuth/OIDC pitfalls: mixing up âauthenticationâ vs âauthorizationâ, incorrect audience/issuer checks, weak state/nonce handling.
- Token leakage: tokens in URLs (logs, referrers), client-side storage exposure, or verbose error traces.
- Clock & expiry issues: skew handling, overly long TTLs, refresh token rotation missing.
Safe validation workflow (defensive verification)
- Inventory auth surfaces: login, SSO, API tokens, password reset, MFA enrollment, device trust, logout.
- Check credential storage: confirm modern hashing and no secret leakage in logs/analytics.
- Check sessions: cookie flags, rotation on login, expiry, logout invalidation, and CSRF strategy.
- Check reset: short TTL, single-use, invalidated on password change, uniform responses to avoid enumeration.
- Check abuse controls: rate limits, throttling, monitoring, and alerting on suspicious patterns.
- Check MFA: consistent enforcement, step-up for high-risk actions, safe enrollment and recovery.
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. Confidence levels (how sure are you?)
| Confidence | What you observed | What 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)
- Passwords stored with modern hashing (bcrypt/argon2) + per-user salt; no custom crypto.
- Uniform login failure responses; avoid account enumeration and sensitive error leakage.
- Rate limiting / throttling on login, reset, OTP, and MFA endpoints; monitoring for stuffing patterns.
- Session id rotated on login and privilege changes; logout invalidates server-side session.
- Cookies set with
HttpOnly,Secure, and appropriateSameSite. - Token lifetimes are short; refresh token rotation exists if using JWT/OIDC flows.
- Password reset/magic links: single-use, short TTL, stored hashed, invalidated on password change.
- MFA enforced consistently; step-up authentication for sensitive actions.
- Audit logs for login, reset, MFA changes, and unusual device/IP changes.
Remediation playbook
- Contain: enable throttling and monitoring immediately for login/reset; rotate secrets if leakage suspected.
- Fix credentials: migrate to bcrypt/argon2; remove plaintext/weak hashing; scrub secrets from logs.
- Fix sessions: enforce cookie flags; rotate session ids at login; implement logout invalidation and short TTLs.
- Fix recovery: redesign reset tokens to be single-use + short-lived + hashed-at-rest; anti-enumeration responses.
- Fix MFA: ensure MFA is enforced consistently; add step-up for high-risk operations; harden enrollment and recovery.
- Prevent regressions: centralize auth logic; add tests for reset reuse, session rotation, logout invalidation; add alerts.
Interview Questions & Answers (Easy â Hard)
Easy
- 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. - 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. - What cookie flags matter and why?
A: Plain: they stop theft and accidental sending. Deep:HttpOnlyreduces JS access,Securerequires HTTPS,SameSitereduces CSRF-like cross-site sends. - 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. - 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. - 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
- 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. - 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. - 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. - 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. - 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. - 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. - 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
- 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. - 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. - 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. - 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. - 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. - 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. - 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.