CSRF Protection Setup for Websites
CSRF — attack where attacker forces authorized user to unintentionally execute action on target site. Classic example: user logged into bank, opens malicious page — it sends POST request to transfer money on their behalf.
Attack Mechanism
Browser automatically attaches cookies to any request to domain, regardless of request origin. If site uses session authentication via cookies, attacker can create form or XHR executing action on behalf of victim.
CSRF Token Protection
Classic and most reliable approach: unique token per session is generated, embedded in forms and verified on each POST/PUT/DELETE request.
Laravel (built-in protection):
// Middleware VerifyCsrfToken connected globally in app/Http/Kernel.php
// In Blade templates:
<form method="POST" action="/profile">
@csrf
{{-- Generates: <input type="hidden" name="_token" value="..."> --}}
</form>
For AJAX requests token passed via meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
// Axios — setup once globally
axios.defaults.headers.common['X-CSRF-TOKEN'] =
document.querySelector('meta[name="csrf-token"]').content;
// Fetch
const response = await fetch('/api/data', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
SameSite Cookie
Modern and elegant protection method — SameSite flag in cookies:
// Laravel config/session.php
'same_site' => 'lax', // or 'strict'
| Value | Behavior |
|---|---|
Strict |
Cookie not sent in any cross-site requests |
Lax |
Cookie not sent on cross-site POST, but sent on link navigation |
None |
Cookie sent everywhere (requires Secure) |
Lax — good balance for most sites. Strict breaks external link navigation (user clicks link from email and ends up unauthorized).
Double Submit Cookie
For sessionless APIs (SPA + JWT): token stored in cookie and duplicated in header. Server compares them.
// Client reads cookie (accessible via JS, not HttpOnly)
const csrfToken = document.cookie
.split('; ')
.find(row => row.startsWith('XSRF-TOKEN='))
?.split('=')[1];
axios.defaults.headers.common['X-XSRF-TOKEN'] = csrfToken;
Laravel Sanctum uses exactly this pattern for SPA authentication.
CSRF Protection Exceptions
Some routes intentionally exclude from CSRF verification (payment system webhooks, Stripe events etc):
// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
'stripe/*',
'webhooks/github',
];
For excluded routes authentication verification done via HMAC signature or Bearer token.
Origin/Referer Verification
Additional layer: verify Origin or Referer header on mutating requests. If Origin doesn't match server domain — request rejected.
// Example middleware
public function handle($request, Closure $next)
{
$origin = $request->header('Origin');
$allowed = ['https://example.com', 'https://app.example.com'];
if ($request->isMethod('POST') && !in_array($origin, $allowed)) {
abort(403, 'Forbidden origin');
}
return $next($request);
}
CSRF Protection Testing
- Create HTML page on different domain with form posting to protected URL
- Authorize on target site
- Navigate to malicious page and try to submit form
- Server must return 419 (Laravel) or 403
Implementation Timeline
- Basic CSRF protection in Laravel/Django/Rails: 1 day
- SPA integration (Sanctum/XSRF cookie): 1–2 days
- Audit and fix vulnerable forms in legacy project: 2–5 days







