CSRF vs XSS: Key Differences
What you'll learn: You'll understand how CSRF and XSS differ in their attack mechanics, capabilities, and how to defend against each.
The Core Distinction
While both CSRF and XSS are web security vulnerabilities, they work in fundamentally different ways. CSRF exploits the trust a website has in the user's browser, while XSS exploits the trust a user has in a website. Think of CSRF as someone forging your signature on a check, versus XSS as someone inserting fake text into a trusted newspaper that you read.
Key Differences
Execution Context:
- CSRF executes with the victim's authenticated session but from an attacker-controlled origin (different website)
- XSS executes malicious code directly within the vulnerable site's trusted context in the victim's browser
Attacker Capabilities:
- CSRF can only perform actions (state changes) the user is authorized to do—it cannot read responses or access data due to Same-Origin Policy
- XSS can read sensitive data, steal tokens, modify page content, and perform any action the user can—with full JavaScript access
Attack Delivery:
- CSRF requires tricking the user into making a request (clicking a link, visiting a malicious page)
- XSS requires injecting malicious scripts into the vulnerable application itself
Defense Mechanisms:
- CSRF is prevented by CSRF tokens, SameSite cookies, and verifying request origins
- XSS is prevented by output encoding, Content Security Policy, input validation, and avoiding innerHTML with untrusted data
Quick Analogy
CSRF is like someone remotely pressing buttons on your phone while you're logged into your banking app—they can act, but can't see the screen. XSS is like malware installed on your phone itself—it can see everything and do anything.
Key Takeaway: CSRF abuses your authenticated session from outside your trusted site, while XSS runs malicious code inside your trusted site—requiring completely different defense strategies.