XSS vs CSRF: How Attack Vectors Differ and How to Defend
Cross-site scripting steals session state while cross-site request forgery forces actions using that state, requiring distinct defenses.

Cross-site scripting injects malicious scripts into trusted sites, stealing data or hijacking sessions. Cross-site request forgery tricks browsers into executing unwanted actions on authenticated sites. XSS compromises confidentiality; CSRF compromises integrity. Defenses differ because one targets code execution and the other targets intent verification.
The Core Distinction Between Injection and Forgery
Cross-site scripting (XSS) and cross-site request forgery (CSRF) both exploit the trust a website places in the user's browser, but they do so through fundamentally different mechanisms. XSS involves injecting malicious client-side scripts into web pages viewed by other users. The browser executes these scripts as if they originated from the trusted site, allowing the attacker to read sensitive data or perform actions on behalf of the user.
CSRF, by contrast, does not inject code. It relies on the browser’s automatic inclusion of credentials, such as session cookies, with every request to a given domain. The attacker forces the victim’s browser to send a crafted request to the target site, hoping the server processes it as a legitimate action.

How Cross-Site Scripting Compromises Confidentiality
XSS attacks succeed when a web application includes untrusted data in its output without proper encoding or escaping. Imagine a comment section where a user submits a string containing JavaScript. If the server stores this string and displays it to other users without neutralizing the script tags, the browser executes the code. This gives the attacker access to the victim’s session cookie, local storage, and DOM elements. The attacker can then exfiltrate this data to a remote server or modify the page appearance to phish for credentials. The primary risk here is the theft of identity and data. The attacker becomes the user in the eyes of the application.
How Cross-Site Request Forgery Compromises Integrity
CSRF attacks exploit the stateful nature of web sessions. When you log into a banking site, the server issues a session cookie. Your browser sends this cookie with every subsequent request to that bank, including requests triggered by images, forms, or JavaScript on other sites. An attacker creates a malicious page with a hidden form that submits a money transfer request to your bank.
When you visit the attacker’s page while logged into your bank, your browser automatically attaches the session cookie. The bank sees a valid session and a valid request structure, so it processes the transfer. The attacker cannot see the response, but the action is performed. The primary risk is unauthorized state changes.
Point-by-Point Comparison of Attack Mechanics
| Aspect | Cross-Site Scripting (XSS) | Cross-Site Request Forgery (CSRF) |
|---|---|---|
| Primary Goal | Steal data or hijack session | Perform unauthorized actions |
| Code Execution | Requires execution in victim browser | No code execution required |
| Data Visibility | Attacker can read response data | Attacker cannot read response data |
| Credential Use | Steals or manipulates credentials | Relies on automatic credential inclusion |
| Defense Focus | Input validation and output encoding | Intent verification and token binding |
| Exploit Complexity | Often requires specific input vectors | Often requires user interaction |
| Impact Type | Confidentiality and Integrity | Integrity only |
Choosing the Right Defense Strategy
You must select defenses based on the specific threat model. Defenses that stop one attack vector often fail against the other. Understanding the mechanism helps you apply the correct countermeasure without wasting resources on ineffective controls.
Choose the first when:
- You need to protect sensitive data from being read by third-party scripts.
- The application displays user-generated content or reflects input in the URL.
- You want to prevent the theft of session cookies or local storage data.
- The risk involves the attacker modifying the page structure to deceive users.
Choose the the second when:
- You need to ensure that state-changing requests originate from your own application.
- The application performs actions based on authenticated sessions without requiring re-authentication.
- You want to prevent automated scripts from triggering actions on behalf of users.
- The primary concern is the integrity of transactions rather than data confidentiality.
See also: Content Security Policy unsafe-inline: What It Does and How to Remove It · How to Write an Access Control Policy That Stops Broken Access Control
Where the Attack Vectors Overlap
The danger increases when an attacker combines both techniques. If an application is vulnerable to XSS, the attacker can inject a script that performs a CSRF attack on behalf of the victim. This script can bypass CSRF protections because it runs within the context of the trusted site and can read the anti-CSRF token from the page. This combination allows the attacker to both steal data and perform actions, effectively bypassing most standard defenses. This overlap highlights why defense in depth is necessary. You cannot rely on a single layer of security.
Practical Implementation Considerations
For XSS, focus on input validation and output encoding. Validate input against a whitelist of allowed characters and encode output based on the context (HTML, JavaScript, URL). For CSRF, include unique tokens in all state-changing forms and verify them server-side. Use SameSite cookie attributes to restrict when cookies are sent with cross-site requests. These measures address the distinct mechanisms of each attack. Remember that proof-of-concept exploits often demonstrate isolated flaws, but real-world attacks chain multiple vulnerabilities.
When evaluating risks, consider vulnerability severity ratings to prioritize fixes. High-severity XSS flaws often require immediate attention due to data theft potential. Meanwhile, change management for security patches ensures that newly discovered flaws in frameworks are addressed promptly. Ignoring output encoding standards leaves applications exposed to persistent XSS. Similarly, neglecting token validation exposes users to silent state changes. Both flaws are common in legacy systems and complex web applications.
Key takeaways
- XSS executes code in the victim's browser context, while CSRF relies on the browser's automatic credential inclusion.
- Anti-CSRF tokens prevent unauthorized state changes but do nothing to stop injected scripts from reading page content.
- Input validation and output encoding stop XSS at the source, whereas SameSite cookie attributes mitigate CSRF at the transport layer.
XSS steals your identity while CSRF forces your actions, requiring separate technical defenses for each. Implement strict output encoding for XSS and anti-CSRF tokens for state-changing requests to cover both vectors.
Frequently asked questions
Can I prevent CSRF with CORS headers?
No, CORS controls which origins can read responses, not which origins can send requests. CSRF exploits automatic credential inclusion, which CORS does not block.
Does SameSite=Lax stop all CSRF attacks?
It stops many cross-site POST requests, but it does not protect against GET-based CSRF or attacks from the same site. It is a mitigation, not a complete solution.
Is stored XSS worse than reflected XSS?
Stored XSS persists on the server and affects every user who views the content, making it harder to detect and remediate. Reflected XSS requires the victim to click a malicious link.
Do API endpoints need CSRF protection?
Traditional CSRF relies on cookies. If your API uses token-based authentication in the Authorization header, CSRF is less likely, but logic flaws may still exist.
How this guide was produced: written by the RedTeam Tribune editorial team with AI assistance, checked against the public references listed below, and reviewed when the facts change. See our editorial policy or report an error.



