Cross-Site Request Forgery (CSRF)
An attack that tricks authenticated users into executing unwanted actions on a web application where they're logged in.
Cross-Site Request Forgery (CSRF) is a web security vulnerability that forces authenticated users to perform unintended actions on applications where they're currently logged in. In Web3 contexts, CSRF attacks can target APIs that trigger blockchain transactions, modify user settings, or interact with connected wallets. While smart contracts themselves aren't directly vulnerable to CSRF, the backend services and APIs that interact with them often are.
How CSRF Works
CSRF exploits the browser's automatic inclusion of credentials (cookies, session tokens) with requests:
- User logs into legitimate DeFi application (establishes session)
- User visits malicious site (in another tab)
- Malicious site triggers request to DeFi application
- Browser automatically includes user's credentials
- DeFi application processes the request as if user initiated it
1<!-- Malicious site embeds this image -->2<img src="https://defi-app.com/api/transfer?to=attacker&amount=1000" />34<!-- Or this form that auto-submits -->5<form action="https://defi-app.com/api/transfer" method="POST" id="csrf">6 <input type="hidden" name="to" value="attacker" />7 <input type="hidden" name="amount" value="1000" />8</form>9<script>document.getElementById('csrf').submit();</script>
CSRF in Web3 Applications
While blockchain transactions require explicit wallet signing (providing natural CSRF protection), many DeFi operations don't:
Vulnerable operations:
- API calls that prepare transactions for signing
- User profile and settings modifications
- Withdrawal address changes
- Email/notification preference updates
- API key generation or rotation
Attack scenario:
1// Legitimate API endpoint2POST /api/settings/withdrawal-address3Body: { "address": "0xNEW_ADDRESS" }45// Attacker's page triggers this request6// If no CSRF protection, attacker can change withdrawal address7// Next withdrawal goes to attacker
Why Some Web3 Apps Are Vulnerable
Over-reliance on wallet signatures: Teams assume all sensitive operations require signing, missing traditional API security.
Hybrid architectures: Backend services with traditional session management alongside blockchain interactions.
API-first design: RESTful APIs designed without considering browser-based attacks.
Third-party integrations: Webhooks and callbacks that trust origin headers.
CSRF Prevention Techniques
Synchronizer Token Pattern
Include a random token in forms that attackers can't guess:
1<form action="/api/settings" method="POST">2 <input type="hidden" name="csrf_token" value="random-token-12345" />3 <!-- Form fields -->4</form>
Server validates the token matches the user's session:
1app.post('/api/settings', (req, res) => {2 if (req.body.csrf_token !== req.session.csrfToken) {3 return res.status(403).json({ error: 'Invalid CSRF token' });4 }5 // Process request6});
SameSite Cookies
Modern cookie attribute that prevents cross-site sending:
1// Express.js session configuration2app.use(session({3 cookie: {4 sameSite: 'strict', // or 'lax'5 secure: true,6 httpOnly: true7 }8}));
| SameSite Value | Behavior |
|---|---|
| Strict | Cookie never sent cross-site |
| Lax | Sent on top-level GET navigations only |
| None | Always sent (requires Secure) |
Double Submit Cookie
Store token in both cookie and request:
1// Set CSRF token in cookie2res.cookie('csrf', token, { sameSite: 'strict' });34// Client includes token in header5fetch('/api/action', {6 method: 'POST',7 headers: {8 'X-CSRF-Token': getCookie('csrf')9 }10});1112// Server compares cookie value with header value
Origin/Referer Validation
Check request origin matches expected domain:
1function validateOrigin(req: Request): boolean {2 const origin = req.headers.origin || req.headers.referer;3 const allowedOrigins = ['https://app.example.com'];4 return allowedOrigins.some(allowed => origin?.startsWith(allowed));5}
Framework Implementations
Express.js with csurf
1import csrf from 'csurf';23const csrfProtection = csrf({ cookie: true });45app.get('/form', csrfProtection, (req, res) => {6 res.render('form', { csrfToken: req.csrfToken() });7});89app.post('/process', csrfProtection, (req, res) => {10 // Token validated automatically11});
Next.js
1// pages/api/protected.ts2import { withIronSession } from 'next-iron-session';34export default withIronSession(async (req, res) => {5 const token = req.headers['x-csrf-token'];6 if (token !== req.session.csrfToken) {7 return res.status(403).json({ error: 'CSRF validation failed' });8 }9 // Process request10});
CSRF Testing in Audits
When auditing for CSRF:
- Identify state-changing operations: All POST, PUT, DELETE, PATCH endpoints
- Check token presence: Verify CSRF tokens in forms and AJAX requests
- Test token validation: Try requests without tokens or with invalid tokens
- Review cookie settings: Check SameSite and Secure flags
- Test cross-origin requests: Attempt requests from different origins
CSRF vs Wallet Signing
| Operation | CSRF Risk | Protection |
|---|---|---|
| Blockchain transaction | Low | Wallet signature required |
| API state change | High | CSRF tokens required |
| Read-only API | None | No protection needed |
| Hybrid (prepare + sign) | Medium | Protect preparation step |
Audit Checklist
- All state-changing APIs require CSRF tokens
- Tokens validated server-side on every request
- SameSite cookie attribute set appropriately
- Origin/Referer headers validated for sensitive operations
- API endpoints don't accept GET for state changes
- CORS configured to reject unauthorized origins
- Sensitive operations require re-authentication or wallet signature
CSRF protection is essential for any Web3 application with traditional backend services. While blockchain transactions have built-in protection through wallet signatures, the surrounding infrastructure—settings, profiles, API keys, and preparation endpoints—remains vulnerable without proper CSRF defenses.
Articles Using This Term
Learn more about Cross-Site Request Forgery (CSRF) in these articles:
Related Terms
Cross-Site Scripting (XSS)
A web vulnerability where attackers inject malicious scripts into web applications, enabling theft of user data or unauthorized actions.
Access Control
Security mechanisms that restrict which addresses can call specific functions in a smart contract, preventing unauthorized actions.
Frontend Security
Security practices protecting web application client-side code from attacks like XSS, CSRF, and malicious script injection.
Need expert guidance on Cross-Site Request Forgery (CSRF)?
Our team at Zealynx has deep expertise in blockchain security and DeFi protocols. Whether you need an audit or consultation, we're here to help.
Get a Quote

