Before your interview: XSS, CSRF, CORS and SameSite
Four browser security mechanisms that interviewers love to mix up on purpose. What XSS, CSRF, CORS and SameSite actually do, how they relate, where each defense stops working, and the follow-up questions that separate a memorized answer from an understood one.
XSS, CSRF, CORS and SameSite come up in almost every web security interview, and rarely one at a time. The interviewer asks about one, then asks how it relates to another, because that is where shallow answers break: “CORS protects against CSRF”, “React prevents XSS”, “SameSite made CSRF tokens obsolete”. Each of those sentences is half true, and the missing half is exactly what the follow-up question is about.
The four fit together once you separate two questions the browser answers for every request: can this page make the browser send something? and can this page read what comes back? XSS is an attacker getting to run code inside the target’s origin, where both answers are yes. CSRF is an attacker abusing the fact that sending is allowed even when reading is not. CORS controls reading. SameSite controls whether cookies go along with the sending.
This is part 2 of the series. Part 1 covered the same-origin policy and cookie attributes on the way to a page; this part builds on both.
TL;DR#
- XSS means the attacker’s script runs in your origin. Every other browser defense assumes that doesn’t happen. The fix is encoding output for the exact context it lands in; CSP is the second line, not the first.
- CSRF needs three things: credentials the browser attaches automatically (usually cookies), a state-changing request, and parameters the attacker can predict. Remove any one and the attack fails.
- SameSite is about sites, not origins.
app.bank.exampleandblog.bank.exampleare the same site, so SameSite does nothing against an attacker on a sibling subdomain. - CORS relaxes the same-origin policy for reading responses. It never blocks a request from being sent, so it is not CSRF protection, and a misconfigured CORS policy is a vulnerability in its own right.
- If there is XSS, CSRF defenses are irrelevant. Script running in the origin can read the anti-CSRF token and send same-origin requests.
The mechanism#
Two words: origin and site#
An origin is scheme + host + port: https://app.bank.example:443. The same-origin policy uses it.
A site is scheme + registrable domain, the part of the name a person can actually register: https://bank.example. “Registrable” is decided by the Public Suffix List, which is why alice.github.io and bob.github.io are different sites (github.io is on the list) while app.bank.example and blog.bank.example are the same site. SameSite cookies and the Sec-Fetch-Site header use this coarser boundary.
Most of the confusion in this topic comes from mixing these two up.
XSS: the attacker’s code in your origin#
Cross-site scripting (XSS) happens when data an attacker controls ends up in a page in a place where the browser treats it as code. The script then runs with the page’s origin: it can read the DOM, call the site’s APIs with the user’s session, read tokens from localStorage, and change what the user sees. HttpOnly stops it from reading the session cookie, but it doesn’t need to: it is already inside the session.
There are three classic types, and the interviewer will expect you to name them and say why the distinction matters:
- Reflected: the payload comes from the current request (a search parameter echoed into the page). The victim has to be lured into opening a crafted link.
- Stored: the payload is saved (a comment, a profile name, a support ticket) and served to everyone who views it. No lure needed, and an admin viewing it in a back-office tool is the classic escalation.
- DOM-based: the server never sees the payload. Client-side JavaScript takes something from a source the attacker controls (
location.hash,postMessagedata,window.name) and writes it to a sink that interprets it as code or HTML (innerHTML,document.write,eval,setTimeoutwith a string, jQuery’s$()with HTML). Server-side scanners and output encoding on the server miss it entirely.
The fix is context-aware output encoding. “Escape the input” is the answer that costs points, because the right encoding depends on where the data lands, not where it came from:
| Where the data lands | What it needs | What still goes wrong |
|---|---|---|
HTML text (<p>HERE</p>) | HTML entity encoding (< → <) | — |
Quoted attribute (<input value="HERE">) | Attribute encoding, quotes included | Unquoted attributes break on a space |
URL attribute (<a href="HERE">) | Scheme allowlist (https:, mailto:) and encoding | Encoding alone allows javascript:alert(1) |
JavaScript string (var x = 'HERE') | JS string escaping; better, pass data via a data- attribute or JSON | </script> closes the block regardless of JS escaping |
CSS, event handlers (onclick="HERE") | Avoid; there is no safe general encoding | Practically everything |
Template engines that auto-escape by context (React’s JSX, Angular, Go’s html/template) get most of this right by default. The bugs live in the escape hatches: dangerouslySetInnerHTML, v-html, Angular’s bypassSecurityTrust*, raw innerHTML in a component, user-controlled href values, and server-side rendering that concatenates strings. When users legitimately need rich HTML (a comment editor), encoding is the wrong tool: you sanitize with a maintained library such as DOMPurify, and accept that sanitizers have had bypasses (mutation XSS, where the browser’s parser rewrites “safe” markup into something dangerous).
CSP: the second line#
Content Security Policy (CSP) is a response header that tells the browser which scripts may run. If an injection slips through, a good CSP keeps the injected script from executing.
“Good” is doing a lot of work in that sentence. An allowlist CSP (script-src 'self' cdn.example.com) is easy to bypass when any allowed host serves a JSONP endpoint or an old version of a framework that evaluates templates; Google’s research in 2016 found the large majority of real-world allowlist policies bypassable this way. And 'unsafe-inline' in script-src switches off the protection against injected inline scripts, which is the main thing you wanted.
The approach that holds up is a strict CSP: every legitimate script carries a per-response random nonce (or a hash), and 'strict-dynamic' lets those trusted scripts load further scripts.
Content-Security-Policy: script-src 'nonce-R4nd0m' 'strict-dynamic'; object-src 'none'; base-uri 'none'
An injected <script> has no nonce, so it doesn’t run. For DOM-based XSS, Trusted Types (require-trusted-types-for 'script') goes further: the browser refuses plain strings at dangerous sinks such as innerHTML, so every write must pass through a policy you wrote. Browser support started in Chromium; check MDN for the current state elsewhere.
The cost is real: nonces need server-side rendering of every page, third-party scripts and inline event handlers have to be refactored, and a static site without a server can only use hashes. That is why CSP rollouts start with Content-Security-Policy-Report-Only, collect violation reports for a few weeks, and only then enforce.
CSRF: sending is enough#
Cross-site request forgery (CSRF) is the attack the same-origin policy leaves open. A page on evil.example can make the victim’s browser send a request to bank.example: a form that auto-submits, an <img> tag, a fetch() call. The attacker can’t read the response, but for a money transfer, an email change or a password reset, they don’t need to. The request is enough, and the browser attaches the victim’s cookies to it.
It takes three conditions, and each defense removes one:
- Ambient credentials: the browser attaches authentication automatically. Cookies are the usual case; HTTP Basic auth and client certificates behave the same. An API authenticated by a bearer token the JavaScript puts in the
Authorizationheader is not CSRF-prone, because the attacker’s page has no way to make the browser add that header. (Where that token is stored is a separate question; it comes up in part 3.) - A state-changing action, reachable by a request the attacker can make cross-site.
- Predictable parameters: nothing in the request is secret to the attacker.
The defenses, and their limits:
- Anti-CSRF token (synchronizer token): a random value tied to the session, embedded in forms, and checked on every state-changing request. The attacker can’t read it, so they can’t include it. It is the classic defense, and it fails completely if there is XSS, because the script can read it.
- Double-submit cookie: the same value in a cookie and in a request parameter. The naive version is weak: an attacker who controls any sibling subdomain can set a cookie for the parent domain (cookie tossing) and choose both values. Bind the value to the session with an HMAC, or use a
__Host-prefixed cookie. - SameSite cookies: the browser doesn’t attach the cookie to cross-site requests. Details below.
- Checking
OriginorSec-Fetch-Site: browsers send these headers on cross-origin requests, and page scripts can’t forge them. Rejecting state-changing requests whoseSec-Fetch-Siteiscross-site(and falling back toOriginfor older clients) is cheap and needs no state. Go 1.25 shipped exactly this ashttp.CrossOriginProtectionin the standard library. - Requiring a custom header or
Content-Type: application/json: forces a CORS preflight, which a cross-site page can’t pass. It works, but only as long as the server really rejects other content types; a form can send atext/plainbody that happens to be valid JSON.
Two cases people forget. Login CSRF: the attacker logs the victim into the attacker’s account, and the victim then saves card details or search history into it. Login forms need CSRF protection too. State-changing GET: if GET /account/delete does something, every defense built for POST is beside the point; SameSite=Lax explicitly sends cookies on top-level GET navigations.
SameSite: the cookie stays home#
The SameSite cookie attribute tells the browser when to attach the cookie to requests that start on another site:
Strict: never cross-site, not even when the user clicks a link to your site from an email. The user arrives logged out, which is why it’s often reserved for a second, high-privilege cookie.Lax: not on cross-site subrequests (fetch, forms that POST, images, frames), but yes on top-level GET navigations, so links keep working.None: always, and it requiresSecure. Needed for cookies that legitimately work across sites (embedded widgets, some SSO flows).
Chrome has treated cookies with no SameSite attribute as Lax since 2020, with a two-minute exception that still allows top-level cross-site POSTs right after the cookie is set, kept for older single sign-on flows. Not every browser applies the default, so set the attribute explicitly.
Where SameSite does not help:
- Attacks from the same site. XSS or a subdomain takeover on
blog.bank.exampleis same-site withapp.bank.example. Every cookie goes along,Strictincluded. - State-changing GET under
Lax, as above. - Same-site gadgets: an open redirect or a client-side redirect on your own site turns a cross-site request into a same-site one.
- Non-browser clients and non-cookie credentials. It is a cookie attribute, nothing more.
That is why the honest answer to “is SameSite enough?” is “it’s a strong default, keep a token or an Origin/Sec-Fetch-Site check for state-changing requests”.
CORS: permission to read#
The same-origin policy stops evil.example from reading responses from api.bank.example. Cross-Origin Resource Sharing (CORS) is how the API server says “these other origins may read my responses”, by answering with Access-Control-Allow-Origin.
The part interviewers probe: CORS is enforced by the browser, on reading. For a simple request (GET, HEAD or POST with only standard headers and a Content-Type of application/x-www-form-urlencoded, multipart/form-data or text/plain) the browser sends the request first, then decides whether the page may see the response. The server has already processed it. Only non-simple requests (a PUT, a JSON body, a custom header) trigger a preflight: an OPTIONS request asking permission before the real one is sent.
So CORS never protects the server. It can only make things worse, and the common ways it does:
- Reflecting the
Originheader withAccess-Control-Allow-Credentials: true. Any site can now read authenticated responses on the victim’s behalf: account data, API keys, the anti-CSRF token. - Allowing
null. Sandboxed iframes andfile:pages sendOrigin: null, and an attacker can produce it on purpose. - Broken origin matching:
endsWith("bank.example")acceptsevilbank.example; a regex with an unescaped dot acceptsbankXexample.com;startsWith("https://bank.example")acceptshttps://bank.example.evil.com. - Trusting every subdomain: then one XSS on any forgotten subdomain can read the main API.
Notice that Access-Control-Allow-Origin: * is safer than reflection: browsers refuse to combine the wildcard with credentials, so it can only expose public data. Responses that vary by origin also need Vary: Origin, or a shared cache can serve one origin’s CORS headers to another.
How they fit together#
| What it controls | Stops | Does not stop | |
|---|---|---|---|
| Same-origin policy | Reading cross-origin responses | Cross-origin data theft | Sending requests (CSRF) |
| CORS | Relaxing the SOP, per origin | Nothing; it grants access | Anything; misconfigured, it opens reading |
| SameSite | Cookies on cross-site requests | Most cross-site CSRF | Same-site attackers, GET actions under Lax |
Anti-CSRF token / Sec-Fetch-Site | Whether a state change is intended | CSRF, including same-site (token) | XSS |
| CSP / Trusted Types | Which scripts may run | Many XSS payloads | The injection bug itself, and CSS/HTML injection |
| Output encoding | Data staying data | XSS at the source | Nothing, if done for the right context |
The questions, and what they really want to hear#
“What types of XSS are there, and how do you prevent it?”#
What it tests: whether “prevent” means a mechanism or a slogan.
30-second answer: “Reflected, stored and DOM-based. The root cause is the same: attacker data interpreted as code. The fix is encoding output for the context it lands in, which auto-escaping templates do by default, so the real work is controlling the escape hatches like innerHTML and raw HTML rendering. Sanitize when users need rich HTML, and add a nonce-based CSP as a second line in case something slips through.”
Deeper: walk the encoding table and pick the href case: HTML encoding is correct there and still doesn’t stop javascript:. For DOM XSS, explain sources and sinks, and why a server-side scanner misses it. On CSP, say why allowlists fail and what 'strict-dynamic' changes. Name the cost: CSP needs refactoring and a report-only phase.
Follow-ups to expect:
- Junior: “What can an attacker do with XSS if the cookie is
HttpOnly?” (Act as the user from inside the page; read anything the page can read.) - Mid: “How would you find DOM XSS?” (Trace sources to sinks; Burp’s DOM Invader; review
innerHTML,postMessagehandlers.) - Senior: “How would you roll out CSP on a large legacy app?” “What’s mutation XSS, and why does it matter for sanitizers?”
“We use React. Are we safe from XSS?”#
What it tests: whether you know where frameworks stop.
30-second answer: “Safer by default, not safe. JSX escapes text and attribute values, but dangerouslySetInnerHTML, user-controlled URLs in href, direct DOM access through refs, third-party components, and server-side rendering that builds HTML strings are all still injection points. And DOM XSS in non-React code on the same page is untouched.”
Follow-ups: “How would you review a React codebase for XSS quickly?” (Grep the escape hatches; check where URLs come from; check the CSP.)
“Explain CSRF. Does SameSite make CSRF tokens unnecessary?”#
What it tests: the three preconditions, and the site/origin distinction.
30-second answer: “CSRF is making a victim’s browser send a state-changing request with their cookies from another site. It needs automatically attached credentials, a state-changing action and predictable parameters. SameSite=Lax blocks most of it by not sending cookies on cross-site subrequests, but it’s site-scoped, so a compromised sibling subdomain bypasses it, and it allows top-level GETs. I’d keep a token or a Sec-Fetch-Site check on state-changing requests.”
Deeper: login CSRF; cookie tossing against naive double-submit; the two-minute Lax exception; why a JSON API with bearer tokens in headers is not CSRF-prone, and why a JSON API with cookies may be (a text/plain form body).
Follow-ups:
- Mid: “What’s the difference between
LaxandStrict, and why not useStricteverywhere?” - Senior: “Design CSRF protection for an app with fifty subdomains, some run by marketing agencies.”
“What does CORS protect against? Show me a dangerous CORS configuration.”#
What it tests: the most common misconception in the topic.
30-second answer: “CORS doesn’t protect anything. It’s an opt-in for the server to let other origins read its responses, relaxing the same-origin policy. Simple requests are sent anyway; the browser just withholds the response. The dangerous configuration is reflecting any Origin with Allow-Credentials: true: then any site can read the user’s authenticated data.”
Deeper: null origin, regex and suffix-matching mistakes, trusting all subdomains, missing Vary: Origin, and why * is the less dangerous mistake. A pentester will also mention that CORS doesn’t apply at all to non-browser clients: curl ignores it, so it is never access control.
“Is CSRF still possible if the site has XSS?”#
What it tests: whether you see the hierarchy between the two.
30-second answer: “It doesn’t matter anymore. XSS is strictly worse: the script runs in the origin, so it can read the anti-CSRF token and send same-origin requests with the cookies. Every CSRF defense assumes the attacker is outside the origin. That’s why XSS is always the higher priority to fix.”
Answers that cost points#
- “CORS protects against CSRF.” CORS governs reading. A cross-site form POST needs no CORS permission to be sent.
- "
Access-Control-Allow-Origin: *is the most dangerous setting." Browsers won’t send credentials with it. Reflecting the origin with credentials is far worse. - “Sanitize the input to prevent XSS.” Encode the output for its context; sanitize only when you must accept HTML, and do it with a maintained library.
- "
HttpOnlyprevents XSS." It stops the script reading the cookie, not using the session. - “SameSite=Strict stops all CSRF.” Not from the same site, and not against state-changing GET requests under
Lax. - “A CSP with
'unsafe-inline'is fine.” It allows injected inline scripts, which is most of what CSP is for. - “Set
X-XSS-Protection: 1; mode=block.” The filter is gone from browsers; the recommendation is0or omission. - “A random token in a cookie that’s echoed in a header is enough.” Not if a sibling subdomain can set cookies; bind it to the session.
The same topic in different interviews#
- Pentester: what you would test and how: payloads per context, DOM Invader for DOM sources and sinks, CSP bypass analysis (JSONP endpoints, old Angular on an allowed CDN, missing
base-uri), CSRF PoC generation and theSameSiteand token edge cases, CORS probing with craftedOriginheaders (null, suffix tricks, subdomains). - AppSec: how to make it hard to write the bug: auto-escaping templates and a lint rule or SAST rule for the escape hatches, a strict CSP with nonces and Trusted Types, a framework-level CSRF middleware, a central CORS configuration with an explicit allowlist instead of per-endpoint code.
- Security engineer: the platform view: CSP report collection and monitoring, cookie policy across many subdomains (and keeping untrusted content on a separate registrable domain, the way user content is served from separate domains by large platforms), CDN header management, and subdomain inventory, since every forgotten subdomain is same-site.
Practice#
- The free PortSwigger Web Security Academy chapters on XSS, CSRF (including the SameSite bypass labs) and CORS. The SameSite labs are the best way to make the site/origin difference stick.
- CSP Evaluator: paste a real policy and see which bypasses it allows.
- Your browser’s developer tools: the Application tab shows each cookie’s
SameSitevalue; the Network tab showsSec-Fetch-SiteandOriginon every request, and preflights as separateOPTIONSentries. - Write a twenty-line page that
fetch()es an API with credentials from another local origin, and change the server’s CORS headers one at a time. Watching which requests reach the server and which responses the page can read is worth more than any diagram.
This site’s colophon describes its own Content Security Policy and what a static host lets it set.
Test yourself#
A profile page renders the user’s website as <a href="{{ .Website }}"> in a template that HTML-encodes every value. Is there an XSS risk?
Answer
Yes. HTML encoding stops the value from breaking out of the attribute, but javascript:alert(document.cookie) contains no characters that need encoding, and the browser runs it when the link is clicked. A URL in an attribute needs a scheme allowlist (https: and maybe mailto:) on top of encoding. Go’s html/template, for example, does this by context: it replaces unsafe URL schemes with #ZgotmplZ. A strict CSP without 'unsafe-inline' also blocks javascript: URLs, as the second line.
The session cookie of app.bank.example is SameSite=Strict and HttpOnly. An attacker finds stored XSS on blog.bank.example, run by a different team. Can they make a logged-in user perform a transfer on app.bank.example?
Answer
SameSite won’t stop them: the two hosts are the same site, so a request from the blog to the app carries the Strict cookie. What still protects the app is anything that depends on the origin, not the site: an anti-CSRF token (the blog’s script can’t read the app’s pages, since that’s cross-origin, unless the app’s CORS policy trusts all *.bank.example subdomains with credentials), or a check that rejects requests whose Sec-Fetch-Site is not same-origin or whose Origin isn’t the app’s own. If the app has a naive double-submit cookie scheme, the blog can overwrite that cookie for .bank.example and win. The structural fix is to move content run by other teams to a separate registrable domain.
An API answers every request with Access-Control-Allow-Origin: <the request's Origin> and Access-Control-Allow-Credentials: true. A developer suggests switching to Access-Control-Allow-Origin: * to be “less permissive”. What’s the actual risk today, and is the suggestion an improvement?
Answer
Today any website the user visits can fetch() the API with credentials: "include" and read the authenticated response: personal data, API keys, anti-CSRF tokens. The wildcard is, oddly, an improvement for that risk: browsers refuse to expose credentialed responses when the origin is *, so only unauthenticated, public data would be readable. But it will break any legitimate front end that needs credentials. The right fix is an explicit allowlist of exact origins, compared as full strings (not with endsWith or a loose regex), with Vary: Origin on the response.
Further reading#
- OWASP Cross Site Scripting Prevention Cheat Sheet and Cross-Site Request Forgery Prevention Cheat Sheet.
- MDN: Cross-Origin Resource Sharing (CORS) and MDN: Set-Cookie, SameSite.
- web.dev: Mitigate cross-site scripting with a strict CSP.
- Weichselbaum, Spagnuolo, Lekies, Janc: CSP Is Dead, Long Live CSP! (2016), the study behind strict CSP.
- Filippo Valsorda: Cross-Site Request Forgery, the reasoning behind Go’s
CrossOriginProtectionand Fetch-Metadata-based CSRF protection.