Situational web security questions rarely test whether you can name an attack. They test whether you know where the defence belongs, why it works, and what breaks it in a real codebase. A strong answer names the root cause, such as untrusted data crossing into an interpreter or a missing ownership check. It then applies the defence at the correct layer and mentions the edge case that most people miss. This guide covers the vulnerabilities a mid or senior engineer is expected to handle without looking anything up. Each concept explains the mechanism, shows a short TypeScript example from an invented product, and lists the traps that separate a passable answer from a convincing one. Work through them in the study order at the end. Injection and access control come up most often, and the other topics build on them.
Study order
If time is short, go in this order.
- Broken access control: IDOR, tenant scoping and function-level checks
It is the most common serious flaw in real applications, and interviewers probe it with almost any API design question.
- Injection: parameterized queries and allowlisted identifiers
The code-versus-data principle behind injection underpins XSS and SSRF too, and the identifier allowlist trap is a frequent follow-up.
- XSS: context-aware output encoding and Content Security Policy
XSS defeats CSRF tokens and session protections. You need context-aware encoding and CSP to reason about every other browser-side defence.
- Session management: cookie flags, fixation, expiry and logout
Cookie flags, fixation, logout and JWT revocation come up whenever authentication is discussed, and they connect XSS to CSRF.
- CSRF: why ambient credentials need tokens and SameSite
You need to explain precisely when SameSite is enough and when it is not, including the same-site versus same-origin distinction.
- CORS: what it relaxes, what it does not protect, and safe configuration
It is widely misunderstood. Separating what CORS controls from what it does not signals real seniority.
- Password storage: slow salted hashing with argon2id or bcrypt
A well-bounded topic with clear right answers: algorithm choice, rehashing and enumeration-resistant login flows.
- SSRF: fetching user-supplied URLs without reaching your internal network
It is increasingly asked in cloud-heavy roles, and it tests whether you think about DNS, redirects and network-level controls together.
XSS: context-aware output encoding and Content Security Policy
Cross-site scripting happens when untrusted data reaches the browser in a place where it is interpreted as code. That place can be HTML markup, an attribute, a URL, inline JavaScript or CSS. There are three variants. Stored XSS persists in your database, reflected XSS bounces off a request parameter, and DOM-based XSS never touches the server because client-side code writes attacker data into a sink like innerHTML. Whatever the variant, the attacker's script runs with your origin's privileges. It can read the page, call your API with the victim's session and exfiltrate data.
The primary defence is encoding output for the exact context it lands in. HTML-entity encoding is correct for element text. It is not enough inside a <script> block, in an unquoted attribute, or in an href, where javascript: URLs need scheme validation. Modern templating (React JSX, Angular, server templates with autoescape) encodes text by default, so in practice the risk sits in the escape hatches: dangerouslySetInnerHTML, v-html, innerHTML, and markdown or rich-text renderers. If you must accept HTML, run it through a well-maintained sanitiser with an allowlist. Never write your own regex filter for this.
Content Security Policy is the second layer. A strict policy using per-response nonces or hashes for scripts means an injected <script> without the nonce will not execute. Pair it with object-src 'none' and base-uri 'none'. Treat CSP as mitigation, not a fix: you still encode. HttpOnly cookies stop script from reading the session cookie, but they do not stop an XSS payload from making authenticated requests in the victim's browser.
TypeScript
import express from "express";
import crypto from "node:crypto";
// Platewise: recipe comments page with a live preview parameter
const app = express();
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
app.get("/recipes/:id/comments", (req, res) => {
const nonce = crypto.randomBytes(16).toString("base64");
res.setHeader(
"Content-Security-Policy",
`default-src 'self'; script-src 'nonce-${nonce}'; object-src 'none'; base-uri 'none'`
);
const preview = String(req.query.preview ?? "");
res.send(
`<p class="comment">${escapeHtml(preview)}</p>` +
`<script nonce="${nonce}" src="/static/comments.js"></script>`
);
});
app.listen(3000);Entity-encode for an HTML text context and add a nonce-based CSP so injected scripts without the nonce are blocked.
Traps
- Encoding on input and storing the encoded value. Data then gets double-encoded in one view and is unsafe in another context like JSON or a CSV export. Store raw data and encode at output, for the context.
- Assuming React makes you immune.
dangerouslySetInnerHTML,href={userUrl}with ajavascript:scheme, and server-rendered JSON embedded in a script tag are all live XSS vectors. - Shipping a CSP with
'unsafe-inline'or a broad CDN allowlist in script-src. Either one largely defeats its purpose against injected scripts. - Reusing a static nonce across responses. A nonce must be unpredictable and generated fresh per response.
Injection: parameterized queries and allowlisted identifiers
Injection happens whenever you build a string that another interpreter parses, and part of that string comes from the user. SQL is the classic case. The same flaw appears in shell commands, LDAP filters, NoSQL operator objects, template engines and log formats. The fix is structural: keep code and data in separate channels so the interpreter never confuses them. For SQL that means parameterized queries or prepared statements. The driver sends the query text and the values separately, so a value like ' OR 1=1 -- stays a literal string.
Parameters only bind values. They cannot stand in for table names, column names, sort directions or SQL keywords. When a user-controlled choice affects those parts, such as a sortable column in a list view, map the user's input through a server-side allowlist to a fixed identifier. Never interpolate the raw input, and never try to escape your way out of it.
ORMs reduce risk but do not remove it. Raw-query escape hatches, string-built where fragments and dynamic orderBy calls reintroduce injection. In document databases, passing a parsed JSON body straight into a filter lets an attacker send {"$ne": null} where you expected a string. Validate types at the boundary. Also run the application's database user with least privilege, so a successful injection cannot drop tables or read other schemas.
TypeScript
import { Pool } from "pg";
// Shelfwise: bookstore catalogue search with user-selectable sort
const pool = new Pool();
const SORTABLE: Record<string, string> = {
title: "title",
price: "price_cents",
published: "published_at",
};
function escapeLike(s: string): string {
return s.replace(/[\\%_]/g, (c) => "\\" + c);
}
export async function searchBooks(term: string, sort: string) {
const column = Object.hasOwn(SORTABLE, sort) ? SORTABLE[sort] : "title";
const sql =
`SELECT id, title, price_cents FROM books ` +
`WHERE title ILIKE $1 ORDER BY ${column} LIMIT 50`;
const { rows } = await pool.query(sql, [`%${escapeLike(term)}%`]);
return rows;
}The search term is a bound parameter. The sort column is mapped through an allowlist, because identifiers cannot be parameterized.
Traps
- Checking the allowlist with
sort in SORTABLE. Theinoperator walks the prototype chain, so"constructor"passes the check. UseObject.hasOwnor aMap. - Forgetting that
%and_are wildcards in LIKE patterns. A parameter prevents injection but not an expensive or unintended wildcard search. - Quoting values with hand-written escaping instead of using parameters. Charset and quoting edge cases are exactly where escaping fails.
- Passing request bodies directly into NoSQL query filters. An attacker can send operator objects where you expected scalars.
Session management: cookie flags, fixation, expiry and logout
After login, the session identifier is effectively the user's password for as long as it lives, so protect it accordingly. Set the cookie with HttpOnly so scripts cannot read it, Secure so it never travels over plain HTTP, and SameSite=Lax or Strict. Consider the __Host- prefix: it forces Secure, Path=/ and no Domain attribute, so a sibling subdomain cannot overwrite the cookie. Session IDs must come from a cryptographically secure generator with enough entropy that guessing one is infeasible.
Session fixation is the classic interview trap. If you keep the same session ID before and after authentication, an attacker who planted a known ID in the victim's browser inherits the logged-in session. Always issue a new session ID on login and on any privilege change, such as entering an admin area or completing step-up MFA. Logout must invalidate the session on the server. Clearing the cookie alone leaves a stolen copy valid.
Two timeouts limit damage: an idle timeout and an absolute lifetime. Stateless JWTs complicate this. You cannot revoke a JWT before it expires without keeping server-side state, such as a denylist, a token version on the user record, or short-lived access tokens paired with revocable refresh tokens. Be ready to explain that trade-off rather than presenting JWTs as strictly better than server sessions.
TypeScript
import express from "express";
import session from "express-session";
// Harborlane: tenant portal for property management
declare module "express-session" {
interface SessionData {
userId?: string;
}
}
declare function verifyCredentials(
email: string,
password: string
): Promise<{ id: string } | null>;
const app = express();
app.use(express.json());
app.set("trust proxy", 1);
app.use(
session({
name: "__Host-sid",
secret: process.env.SESSION_SECRET as string,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 30 * 60 * 1000 },
})
);
app.post("/login", async (req, res, next) => {
const user = await verifyCredentials(req.body.email, req.body.password);
if (!user) return res.status(401).json({ error: "Invalid email or password" });
req.session.regenerate((err) => {
if (err) return next(err);
req.session.userId = user.id;
res.json({ ok: true });
});
});
app.post("/logout", (req, res, next) => {
req.session.destroy((err) => {
if (err) return next(err);
res.clearCookie("__Host-sid", { path: "/", secure: true, httpOnly: true, sameSite: "lax" });
res.status(204).end();
});
});Regenerate the session on login to prevent fixation, and destroy it server-side on logout.
Traps
- Keeping the pre-login session ID after authentication. This enables session fixation.
- Logging out by clearing the cookie only. Anyone holding a copy of the ID can keep using it.
- Storing session tokens or JWTs in
localStorage. Any XSS can then read and exfiltrate them, whereas an HttpOnly cookie at least keeps the token itself out of reach. - Issuing long-lived JWTs with no revocation strategy. A password change or account compromise cannot end existing sessions.
Password storage: slow salted hashing with argon2id or bcrypt
Passwords must be stored with a deliberately slow, salted, memory-hard function: argon2id is the current preference, with scrypt or bcrypt as acceptable alternatives. Fast hashes like SHA-256, even salted, are wrong for this. They are designed for throughput, so an attacker with a leaked table and GPUs can try enormous numbers of guesses per second. A unique per-password salt defeats precomputed tables and makes identical passwords produce different hashes. The library generates and embeds the salt for you.
Cost parameters should be as high as your login latency and server capacity allow. Encode them in the hash string so you can raise them later. On successful login, check whether the stored hash uses outdated parameters and transparently rehash with the plaintext you have just verified. The same approach migrates legacy MD5 or SHA-1 hashes, either at login or by wrapping the old hash inside the new algorithm.
The surrounding flow matters as much as the hash. Return the same error and take roughly the same time whether or not the account exists, to avoid user enumeration. Rate-limit and add progressive delays per account and per IP. Know bcrypt's 72-byte input limit. An optional pepper, a secret kept outside the database such as in a KMS, adds protection if only the database leaks.
TypeScript
import argon2 from "argon2";
// Quillstack: writer accounts
const OPTIONS = {
type: argon2.argon2id,
memoryCost: 19456, // KiB
timeCost: 2,
parallelism: 1,
};
export function hashPassword(password: string): Promise<string> {
return argon2.hash(password, OPTIONS);
}
export async function verifyAndUpgrade(
storedHash: string,
password: string
): Promise<{ ok: boolean; newHash?: string }> {
const ok = await argon2.verify(storedHash, password);
if (!ok) return { ok: false };
const newHash = argon2.needsRehash(storedHash, OPTIONS)
? await argon2.hash(password, OPTIONS)
: undefined;
return { ok: true, newHash };
}Hash with argon2id, verify, and rehash on login when the stored parameters are out of date.
Traps
- Using SHA-256 or SHA-512 with a salt and calling it secure. Speed is the problem, not the lack of salt.
- Returning early when the email does not exist. The timing difference leaks which accounts are registered. Verify against a dummy hash instead.
- Feeding long passphrases into bcrypt without knowing it only uses the first 72 bytes.
- Encrypting passwords reversibly. If the application can decrypt them, so can an attacker who takes the key.
Broken access control: IDOR, tenant scoping and function-level checks
Authentication tells you who the caller is. Authorization decides whether that caller may perform this action on this specific object. Most real breaches in this category are insecure direct object references (IDOR). An endpoint like GET /api/invoices/8812 checks that the user is logged in but never checks that invoice 8812 belongs to their organisation. Using UUIDs instead of sequential IDs makes guessing harder, but it is not authorization. IDs leak through URLs, logs, emails and shared links.
Enforce ownership in the data access itself. Scope every query by the caller's tenant or owner, for example WHERE id = $1 AND org_id = $2, rather than fetching the object and remembering to compare afterwards. When the object exists but belongs to someone else, return 404 rather than 403, so you do not confirm its existence. Function-level checks matter too. Admin-only actions need a server-side role or permission check, because hiding a button in the UI protects nothing.
Watch for mass assignment. Binding a request body straight onto a model lets a user send role: "admin" or orgId and change fields they should never control. Allowlist the writable fields per endpoint. Centralise policy logic in one module or a policy engine so every route asks the same question the same way. Then write tests that try cross-tenant access explicitly.
TypeScript
import { Pool } from "pg";
// Clinicly: billing for multi-clinic practices
const pool = new Pool();
export interface Caller {
userId: string;
orgId: string;
role: "member" | "admin";
}
export class ForbiddenError extends Error {}
export async function getInvoice(caller: Caller, invoiceId: string) {
const { rows } = await pool.query(
"SELECT id, amount_cents, status FROM invoices WHERE id = $1 AND org_id = $2",
[invoiceId, caller.orgId]
);
return rows[0] ?? null; // caller maps null to 404
}
export async function voidInvoice(caller: Caller, invoiceId: string): Promise<boolean> {
if (caller.role !== "admin") throw new ForbiddenError("admin role required");
const result = await pool.query(
"UPDATE invoices SET status = 'void' WHERE id = $1 AND org_id = $2 AND status = 'open'",
[invoiceId, caller.orgId]
);
return result.rowCount === 1;
}Every read and write is scoped by the caller's organisation, and privileged actions check the role server-side.
Traps
- Treating unguessable IDs as access control. Authorization must be checked on every request, whatever the ID format.
- Authorizing the list endpoint but not the detail, update, export or bulk endpoints that take an ID directly.
- Taking
orgIdoruserIdfrom the request body or query string instead of from the authenticated session. - Binding request bodies straight onto ORM models. This is mass assignment: users can set
role,isVerifiedor a foreign key.
CORS: what it relaxes, what it does not protect, and safe configuration
The same-origin policy stops a script on one origin from reading responses from another. CORS is the mechanism a server uses to relax that restriction for chosen origins. It is not a server-side defence. It does not stop requests from arriving, it does not stop curl or a backend from calling you, and it does not stop simple cross-site form posts. It only tells the browser whether the calling page may read the response.
Browsers send a preflight OPTIONS request for non-simple requests, such as those with custom headers, a JSON content type, or methods like PUT and DELETE. Simple requests go out immediately, and only the response is withheld. That is why CORS is no substitute for CSRF protection.
The dangerous misconfiguration is reflecting any Origin header back while also sending Access-Control-Allow-Credentials: true. That lets any website read authenticated responses on behalf of your logged-in users. Browsers block the literal * with credentials, so developers sometimes 'fix' the error by echoing the origin, which is worse. Match against an exact allowlist, add Vary: Origin so caches do not serve one origin's headers to another, and never trust the null origin, which sandboxed iframes and local files can send.
TypeScript
import express from "express";
// Harborlane API consumed by two first-party front ends
const app = express();
const ALLOWED_ORIGINS = new Set([
"https://app.harborlane.example",
"https://admin.harborlane.example",
]);
app.use((req, res, next) => {
res.setHeader("Vary", "Origin");
const origin = req.headers.origin;
if (origin && ALLOWED_ORIGINS.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
if (req.method === "OPTIONS") {
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader("Access-Control-Max-Age", "600");
return res.status(204).end();
}
next();
});
app.get("/api/me", (_req, res) => res.json({ name: "demo" }));
app.listen(3000);Exact-match allowlist, credentials only for trusted origins, and Vary: Origin so shared caches stay correct.
Traps
- Reflecting the request's Origin header with credentials enabled. Any site can then read authenticated API responses.
- Validating origins with
endsWith("harborlane.example")or an unanchored regex.evilharborlane.exampleandharborlane.example.attacker.netslip through. - Allowing the
nullorigin. Sandboxed iframes and some redirects produce it, so an attacker can obtain it easily. - Thinking a restrictive CORS policy protects an endpoint from abuse. Non-browser clients ignore CORS entirely.
SSRF: fetching user-supplied URLs without reaching your internal network
Server-side request forgery happens when your server fetches a URL the user controls. Common entry points are webhooks, link previews, image imports, PDF renderers and OAuth or OpenID metadata discovery. The request originates inside your network, so an attacker can point it at things the internet cannot reach. Targets include the cloud metadata endpoint at 169.254.169.254 (which can hand out credentials), internal admin panels, databases with HTTP interfaces, and localhost services.
Blocklisting hostnames does not work, because DNS decides where a name points. Resolve the hostname yourself and reject private, loopback, link-local and reserved ranges for both IPv4 and IPv6. Then connect to the exact IP you validated. Re-resolving at connect time opens a DNS rebinding window, where the first lookup returns a public address and the second returns an internal one. Disable automatic redirects, or re-validate every hop, because a public URL can 302 to an internal address. Restrict schemes to https (and perhaps http) so file: or gopher: never reach a fetch library that supports them.
Network controls are the stronger layer. Run outbound fetches through an egress proxy or an isolated worker with no route to internal subnets. On AWS, require IMDSv2, which needs a session token obtained with a PUT, to blunt metadata theft. Return generic errors and apply timeouts and size limits, so the feature cannot be used to port-scan or to exhaust resources.
TypeScript
import { lookup } from "node:dns/promises";
import net from "node:net";
// Pingrelay: customers register webhook URLs for order events
const blocked = new net.BlockList();
blocked.addSubnet("0.0.0.0", 8, "ipv4");
blocked.addSubnet("10.0.0.0", 8, "ipv4");
blocked.addSubnet("100.64.0.0", 10, "ipv4");
blocked.addSubnet("127.0.0.0", 8, "ipv4");
blocked.addSubnet("169.254.0.0", 16, "ipv4");
blocked.addSubnet("172.16.0.0", 12, "ipv4");
blocked.addSubnet("192.168.0.0", 16, "ipv4");
blocked.addAddress("::", "ipv6");
blocked.addAddress("::1", "ipv6");
blocked.addSubnet("::ffff:0:0", 96, "ipv6"); // IPv4-mapped: reject, or unwrap and re-check
blocked.addSubnet("fc00::", 7, "ipv6");
blocked.addSubnet("fe80::", 10, "ipv6");
export async function resolveSafeWebhook(raw: string): Promise<{ url: URL; address: string }> {
const url = new URL(raw);
if (url.protocol !== "https:") throw new Error("Only https webhooks are allowed");
const results = await lookup(url.hostname, { all: true });
if (results.length === 0) throw new Error("Host did not resolve");
for (const { address, family } of results) {
if (blocked.check(address, family === 6 ? "ipv6" : "ipv4")) {
throw new Error("Webhook host resolves to a disallowed address");
}
}
// Connect to results[0].address with SNI/Host set to url.hostname, redirects disabled
return { url, address: results[0].address };
}Resolve first, reject internal ranges for every returned address, then pin the connection to the validated IP with redirects off.
Traps
- Validating the hostname and then letting the HTTP client resolve it again. DNS rebinding swaps in an internal IP between the check and the request.
- Following redirects automatically. A harmless external URL can redirect straight to the metadata endpoint.
- Checking only IPv4 ranges. IPv6 loopback, unique-local and IPv4-mapped addresses like
::ffff:127.0.0.1bypass the check. - Parsing the URL with one library and fetching with another. Parser differentials over userinfo, backslashes or encoded characters let an attacker reach a different host than the one you validated.
Common questions
Short answers to the usual doubts.
How should I structure an answer to a situational security question?
Start with the root cause in one sentence, for example 'the endpoint trusts the ID without checking ownership'. Then give the primary fix at the correct layer, followed by one defence-in-depth measure. Finish with an edge case or trade-off, such as subdomain cookies, redirects or revocation. Interviewers reward the edge case because it shows you have shipped the fix rather than memorised it.
Are JWTs more secure than server-side sessions?
No, they make different trade-offs. JWTs avoid a session lookup but cannot be revoked before expiry without adding server state, and they are often stored in localStorage, where XSS can read them. Server sessions in HttpOnly cookies are easy to invalidate but need CSRF protection. A common middle ground is short-lived access tokens with revocable refresh tokens.
Should an unauthorized object request return 403 or 404?
For objects owned by another tenant or user, 404 is usually better because it does not confirm the resource exists. Use 403 when the caller can legitimately know the resource exists but lacks permission for the action, such as a member trying an admin-only operation on their own organisation's invoice.
Do security headers alone protect an application?
No. Headers like CSP, HSTS, X-Content-Type-Options and frame-ancestors reduce the impact of mistakes or close specific vectors such as clickjacking and protocol downgrades. They do not fix injection, missing authorization or weak session handling. Present them as a mitigation layer, not a primary control.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Web securityTake the test