Join our Newsletter — 33% off our NHI Course
Home› Guides› XSS vs CSRF: Which Trust Each Abuses and…
Guide Application Security

XSS vs CSRF: Which Trust Each Abuses and How to Defend

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 14 November 2026 14 min read
On this page

Cross-site scripting and cross-site request forgery are often filed together as "browser bugs", yet they abuse opposite trust relationships, and a control that stops one usually does nothing against the other. XSS exploits the user's trust in a site: the browser runs attacker script as if the site wrote it. CSRF exploits the site's trust in the user's browser: the server accepts a request because it arrived with the user's cookies. That difference decides what an attacker can read, whether session and OAuth tokens can be stolen, and which defences apply. This guide compares the two by trust exploited, impact, architecture, controls, testing and failure modes, with a worked scenario for each and the answer to a common question: does a CSRF token stop XSS? It is for application security engineers, developers and assessors. Defence mechanics are in the Cross-Site Scripting (XSS) Prevention Guide and the CSRF Prevention Guide; this page is about the differences and how they interact.

Key takeaways

  • Opposite trust, opposite direction. XSS runs attacker code inside your origin; CSRF sends a forged request into your origin from somewhere else.
  • XSS is the stronger primitive. Script in your origin can read pages, read anti-forgery tokens and send same-origin requests, so OWASP warns that XSS can defeat all CSRF mitigation techniques.
  • CSRF is blind and bounded. The attacker cannot read responses and can only trigger actions the victim's session already permits, which is still serious when the victim is an administrator.
  • Controls do not transfer. Output encoding, safe sinks, sanitisation, CSP and Trusted Types address XSS; framework tokens, Fetch Metadata, Origin checks and SameSite cookies address CSRF.
  • Token theft is an XSS outcome. Tokens in browser storage are readable by injected script; HttpOnly cookies and a backend-for-frontend design limit theft but not misuse of the live session.

The short answer

MITRE CWE-79, Improper Neutralization of Input During Web Page Generation, covers XSS in three forms: reflected, stored and DOM-based. CWE-352 covers CSRF: the application cannot sufficiently verify that a request was intentionally provided by the user who sent it. In the 2025 CWE Top 25, CWE-79 ranks first and CWE-352 third. The OWASP Top 10 2025 places XSS under A05:2025 Injection, which notes more than 30,000 XSS CVEs, while CSRF sits under A01:2025 Broken Access Control. CAPEC catalogues them as CAPEC-63 Cross-Site Scripting and CAPEC-62 Cross Site Request Forgery.

A quick test: where does the malicious logic execute? If it runs inside your page with your origin's privileges, it is XSS. If it runs on another site and only causes the browser to send a request to yours, it is CSRF.

Does a CSRF token stop XSS? No. A token proves a request came from a page your origin served. Injected script runs in exactly such a page, so it can read the token from the DOM or a cookie and include it, or simply drive the form. CSRF tokens remain necessary for cookie-authenticated apps, but they are not an XSS control.

Side-by-side comparison

DimensionXSSCSRF
Trust abusedThe browser's trust that script served from your origin is yoursThe server's trust that a request carrying the session cookie was intended by the user
Where attacker logic runsInside your origin, in the victim's browserOn an attacker-controlled site; your origin only receives the request
Root causeUntrusted data reaches an HTML, JavaScript, URL or CSS context without the right encoding or sanitisationState-changing endpoint accepts ambient credentials without verifying intent or origin
Can the attacker read responsesYes, anything the page can readNo, the same-origin policy blocks reading
Token and secret exposureTokens in localStorage, sessionStorage, JavaScript memory or non-HttpOnly cookies, plus CSRF tokens in the pageNone; credentials are used, never revealed
Typical impactSession or token theft, account takeover, data exfiltration, keylogging forms, actions as the user, worm-like spread for stored XSSOne or a few unwanted state changes: email or password change, transfers, settings, admin actions
Victim interactionVisit an infected page (stored) or a crafted link (reflected, DOM)Visit attacker content while signed in
Authentication scheme dependenceAffects every scheme, because script uses whatever the page usesMainly cookie or HTTP authentication that browsers attach automatically; bearer tokens set by script are not attached cross-site
Primary controlsFramework auto-escaping, context-specific encoding, safe sinks, sanitisation, CSP, Trusted TypesFramework anti-forgery tokens, Fetch Metadata, Origin verification, SameSite cookies, no state change on GET

XSS in depth: threat model, architecture and impact

Threat model: an attacker who can place data where your application later renders it: a profile field (stored), a query parameter reflected into the response (reflected), or a URL fragment or postMessage value that client-side code writes into the DOM (DOM-based). See Stored vs Reflected vs DOM XSS for how the three differ in detection and fix.

Architecture in words: data flows from a source (request, database, third-party API, URL) to a sink (template interpolation, innerHTML, an event-handler attribute, eval, a javascript: URL). The bug exists where no encoder or sanitiser suited to that exact context sits between them. OWASP notes that modern frameworks escape rendered values by default, so most current XSS appears where developers use escape hatches such as React's dangerouslySetInnerHTML, Angular's bypassSecurityTrustAs* functions or Lit's unsafeHTML, or write directly to DOM sinks.

Impact: script in your origin has every capability your own front end has. RFC 10017, OAuth 2.0 for Browser-Based Applications (published as BCP 212 in August 2026), describes how injected code can read tokens from browser storage, how persistent theft can defeat refresh token rotation because the attacker always holds the newest token, and how an attacker can run a silent flow to obtain fresh tokens that short lifetimes, rotation and DPoP cannot stop. Even where tokens are out of reach, the attacker can proxy requests through the user's browser; the RFC states that nothing fully prevents this except stopping the malicious code from running.

CSRF in depth: threat model, architecture and impact

Threat model: an attacker who can get a signed-in victim to load content they control: a link, an image tag, an auto-submitting form, a malicious advert. The attacker knows the target endpoint's parameters but cannot read anything back.

Architecture in words: the browser attaches cookies for your site to requests your site receives, subject to SameSite rules, regardless of which site initiated them. The server sees a well-formed request with a valid session and processes it. The bug exists where a state-changing endpoint does not check a signal that only your own pages can produce: a synchronizer token, a session-bound signed double-submit token, a Sec-Fetch-Site value, an Origin header or a custom header that forces a CORS preflight.

Impact: bounded by the victim's privileges and by the attacker's blindness. Multi-step flows that need values from earlier responses are hard to forge. Login CSRF inverts the usual pattern: OWASP describes logging the victim into the attacker's account so that data the victim enters later, such as card details, lands with the attacker. Client-side CSRF is a hybrid: attacker-controlled input such as the URL fragment makes your own JavaScript send a forged request, so tokens and SameSite do not help because the request genuinely originates from your page.

Controls per attack and where they overlap

ControlEffect on XSSEffect on CSRF
Framework auto-escaping and context-specific output encodingPrimary preventionNone
Safe sinks (textContent, setAttribute with fixed names) and HTML sanitisation for user-authored HTMLPrimary prevention, especially DOM-basedNone
Content Security Policy (nonce or hash based, no unsafe-inline)Defence in depth; OWASP says it should not be the primary defenceNone
Trusted TypesBlocks string assignment to DOM sinks where enforcedNone
HttpOnly session cookieStops script reading the cookie value; MDN notes the cookie is still sent with script-initiated requests, so session riding remainsNone
Synchronizer or signed double-submit tokenNone: script can read and replay itPrimary prevention for cookie-authenticated forms
Fetch Metadata (Sec-Fetch-Site) and Origin verificationNone: XSS requests are same-originStrong prevention; Sec-Fetch-Site is a forbidden header that script cannot set
SameSite=Lax or Strict cookiesNone against same-origin script; a same-site subdomain with XSS is also inside the boundaryDefence in depth; OWASP says it rarely suffices alone
Re-authentication for sensitive actionsPartial: script cannot supply the password or passkey without user involvementStrong for the protected action
Backend-for-frontend with tokens kept server sidePrevents token theft and silent token acquisition; does not stop proxying through the browserRequires CSRF protection on the BFF's cookie session

The pattern is clear: anti-forgery controls assume the attacker is outside your origin, and XSS puts them inside it. That is why XSS prevention is a precondition for CSRF defences to mean anything, and why the order of investment is not optional. See also CORS vs CSRF Protection for why CORS is not a CSRF control.

Session design shifts risk between the two attacks, so make the choice consciously.

  • Cookie sessions: exposed to CSRF by default and need anti-forgery controls. Set HttpOnly, Secure, an explicit SameSite, and the __Host- prefix, which MDN describes as requiring Secure, no Domain attribute and Path=/, so sibling hosts cannot set or override the cookie. See the Cookie Security Guide.
  • Default SameSite behaviour varies: OWASP notes Chromium-based browsers treat cookies without the attribute as Lax while Firefox and Safari do not, and MDN describes a two-minute window in which a default-Lax cookie is still sent on cross-site POSTs. Never rely on the default.
  • Bearer tokens in browser storage: immune to classic CSRF because script must attach them, but readable by any XSS. RFC 10017 strongly recommends the backend-for-frontend pattern for sensitive applications and those handling personal data.
  • Sender-constrained tokens: DPoP and device-bound session credentials reduce the value of exfiltrated tokens off the device, but script running in the victim's browser can still use them in place.

Worked scenarios

XSS: a support widget escape hatch

A single-page app renders customer messages in an internal support console using an escape hatch to preserve formatting. A customer submits a message containing markup that the console renders as script. When an agent opens the ticket, the script reads the agent's access token from localStorage, sends it to an external host and, using the agent's existing session, adds a new administrator. The CSRF token on the admin form did not help: the script read it from the page. Response: revoke the agent's sessions and tokens (see the Session Token Theft Response Playbook), audit admin changes, replace the escape hatch with a maintained sanitiser, move tokens behind a BFF and deploy a nonce-based CSP that would have blocked the exfiltration request.

CSRF: a GET endpoint behind SameSite=Lax

An account service relies on SameSite=Lax and has no tokens. An old endpoint changes the notification email via GET for compatibility with an email link. An attacker sends signed-in users a link to that endpoint with their own address; Lax permits cookies on top-level GET navigations, so the change succeeds, and password reset emails now go to the attacker. Response: make the endpoint POST only, add framework anti-forgery tokens and a Sec-Fetch-Site check, require re-authentication to change contact details, and notify the old address on every change.

Testing each

  1. XSS: combine SAST rules for escape hatches and dangerous sinks, DAST for reflected and stored cases, and DOM-aware testing for client-side flows. Review every framework escape hatch by hand. See SAST vs DAST.
  2. CSRF: enumerate every state-changing endpoint, including APIs, login and logout, and confirm each verifies a token, Fetch Metadata or Origin signal server side. Check that no state change is reachable by GET.
  3. Interaction: for every confirmed XSS, record which CSRF-protected actions it can reach and which tokens it can read; this sets severity.
  4. Roll out new controls safely: deploy CSP in Content-Security-Policy-Report-Only first, and Fetch Metadata rejection in log-only mode, then enforce once reports are clean; roll back by returning to report-only.

Decision guidance: which to prioritise

  • Single-page app with tokens in the browser: XSS first. Move to a BFF or in-memory tokens with short lifetimes, enforce Trusted Types and a strict CSP.
  • Server-rendered app with cookie sessions: both, but CSRF coverage is the quick win: confirm the framework's protection is on for every route, then hunt escape hatches.
  • Admin and support consoles: XSS in these is the highest impact because victims hold the most privilege; stored XSS from customer-supplied content is the classic path.
  • Public APIs with bearer tokens only: CSRF risk is low; check CORS so custom-header protections hold.
  • Small vs large organisations: a small team gets most value from framework defaults left on and a short list of banned escape hatches enforced in code review. A large organisation should centralise CSP and Fetch Metadata policy at the edge or in shared middleware and track coverage per application.

Where identity fits

Both attacks end in identity misuse. CSRF borrows a session for one action; XSS can steal the session or OAuth tokens and keep them. Treat confirmed XSS on an authenticated page as a credential exposure event: revoke sessions and refresh tokens for affected users, and review OAuth grants issued during the window. Where integrations or service accounts use the same web console, their API keys displayed in the page are exposed too.

Detection and measurement

  • CSP violation reports: collect report-to data centrally; new inline script or unexpected hosts on authenticated pages are an XSS signal.
  • Anti-forgery rejections: log token, Origin and Sec-Fetch-Site failures by endpoint; spikes on one endpoint suggest probing.
  • Session anomalies: the same session or token used from a new IP or user agent shortly after a page view points to theft.

Metrics:

  • Escape hatch count: number of dangerouslySetInnerHTML, bypassSecurityTrust* and similar uses, trending down.
  • CSP enforcement coverage: percentage of authenticated pages with an enforced nonce or hash policy.
  • CSRF coverage: percentage of state-changing endpoints with verified server-side protection (target 100%).
  • Tokens in browser storage: number of applications storing access or refresh tokens in localStorage.
  • Time to remediate XSS: days from finding to fix, split by stored, reflected and DOM.

Common failure patterns

  • Treating CSRF tokens as XSS protection: injected script reads and submits them.
  • Relying on HttpOnly alone: the cookie cannot be read but is still sent with every script-initiated request.
  • Trusting default SameSite: behaviour differs by browser and Lax still allows top-level GETs.
  • CSP with unsafe-inline or broad host allowlists: a policy that looks present but blocks little.
  • Exempting routes from CSRF protection too broadly: webhook routes need an exemption because they use signatures instead (see Webhook HMAC Signing vs mTLS vs IP Allowlisting), but blanket API exemptions on cookie-authenticated routes reopen CSRF.

Framework mapping

ConcernNIST SP 800-53 Rev. 5NIST CSF 2.0ATT&CK v20
Preventing XSS through validation and output handlingSI-10 Information Input Validation, SI-15 Information Output FilteringPR.PS-06T1189 Drive-by Compromise
Session integrity against forged requestsSC-23 Session AuthenticityPR.AA-05T1185 Browser Session Hijacking
Protecting session cookies and tokens from theftSC-23 Session AuthenticityPR.DS-10T1539 Steal Web Session Cookie, T1550.004 Web Session Cookie
Testing for both classesSA-11 Developer Testing and EvaluationPR.PS-06
Monitoring violations and rejectionsSI-4 System MonitoringDE.CM-09

In ISO/IEC 27001:2022 Annex A the closest controls are 8.28 Secure coding, 8.29 Security testing in development and acceptance, and 8.26 Application security requirements.

Practitioner checklist

  • Keep framework auto-escaping on and inventory every escape hatch and raw DOM sink.
  • Sanitise user-authored HTML with a maintained library and never modify its output afterwards.
  • Deploy a nonce or hash based CSP, report-only first, then enforced; add Trusted Types where supported.
  • Confirm framework anti-forgery protection on every state-changing route, including login and APIs using cookies.
  • Add a Sec-Fetch-Site check with Origin verification as the fallback.
  • Set session cookies explicitly: HttpOnly, Secure, SameSite and the __Host- prefix.
  • Keep OAuth tokens out of browser storage for sensitive apps; prefer a backend-for-frontend.
  • Require re-authentication for email, password, MFA and payment changes.
  • Treat confirmed authenticated XSS as a credential exposure and revoke sessions.

Standards and references

Related NHI Mgmt Group resources: Cross-Site Scripting (XSS) Prevention Guide · CSRF Prevention Guide · Content Security Policy Guide · Trusted Types and DOM XSS Prevention Guide · SSRF vs CSRF

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 14 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org