Marwa Framework provides built-in CSRF (Cross-Site Request Forgery) protection to prevent malicious actors from executing unauthorized actions on behalf of authenticated users.
SecurityMiddleware validates the token on protected routesCSRF protection is enabled by default with sensible settings:
// config/security.php
return [
'csrf' => [
'enabled' => true,
'field' => '_token', // Form field name
'header' => 'X-CSRF-TOKEN', // Header name for AJAX
'token' => '__marwa_csrf_token', // Session key
'methods' => ['POST', 'PUT', 'PATCH', 'DELETE'],
'except' => [], // Routes excluded from CSRF
],
];
<!-- Blade/Liquid template -->
<form method="POST" action="/profile">
{!! csrf_field() !!}
<input type="text" name="name" value="">
<button type="submit">Update</button>
</form>
This generates:
<input type="hidden" name="_token" value="abc123def456...">
// In templates
<input type="hidden" name="_token" value="">
For AJAX requests, send the token via the X-CSRF-TOKEN header:
// Using Fetch API
fetch('/api/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({ name: 'John' })
});
Add the CSRF token to your layout’s <head>:
<head>
<meta name="csrf-token" content="">
</head>
Exclude routes that don’t require CSRF protection (e.g., external webhooks):
// config/security.php
return [
'csrf' => [
'enabled' => true,
'except' => [
'webhook/stripe',
'api/external/*',
],
],
];
Validate tokens programmatically when needed:
use Marwa\Framework\Supports\Helpers\Security;
if (validate_csrf_token($tokenFromRequest)) {
// Token is valid
} else {
// Invalid token
}
Rotate the CSRF token after critical operations:
use Marwa\Framework\Facades\Security;
$newToken = Security::rotateCsrfToken();
// config/security.php
return [
'csrf' => [
'enabled' => false,
],
];
Warning: Only disable CSRF protection for routes that don’t modify data or when using alternative protection mechanisms.
random_bytes(32)hash_equals() to prevent timing attacks