CsrfMiddleware
The CsrfMiddleware class provides automatic CSRF (Cross-Site Request Forgery) protection for unsafe HTTP methods (POST, PUT, PATCH, DELETE). It validates CSRF tokens and optionally checks Origin/Referer headers.
Capabilities
Automatic CSRF validation on unsafe HTTP methods
Time-bucketed token validation with grace period
Origin/Referer header validation
Configurable session key and time buckets
Safe methods (GET, HEAD, OPTIONS) automatically pass validation
Constructor
public function __construct(
array $allowedOrigins = [],
string $csrfSessionKey = 'csrf_secret',
int $bucketSeconds = 3600,
bool $allowPreviousBucket = true
)Parameters
$allowedOrigins: Array of allowed origins (e.g.,['https://example.com']). If empty, origin validation is skipped.$csrfSessionKey: Session key where CSRF secret is stored (default:'csrf_secret')$bucketSeconds: Time bucket size in seconds for token rotation (default:3600= 1 hour)$allowPreviousBucket: Allow tokens from previous time bucket for grace period (default:true)
Public API
Returns true if the request passes CSRF validation, false otherwise.
How It Works
Safe methods bypass validation: GET, HEAD, OPTIONS requests automatically pass
Origin validation (if configured): Checks
OriginorRefererheader against allowed originsToken validation: Validates CSRF token from
X-CSRF-TOKENheader or_tokenPOST parameterTime-bucketed tokens: Tokens are valid for current and previous time bucket (grace period)
Basic Example
Router Integration Example
Custom Configuration Example
Frontend Integration
Generating Tokens
Sending Tokens
HTML Form:
JavaScript (Fetch API):
Security Notes
Time-bucketed tokens: Tokens rotate automatically every hour (default), reducing exposure window
Grace period: Previous bucket tokens are accepted to prevent race conditions during rotation
Origin validation: Additional layer of protection against cross-origin attacks
Safe methods: GET requests don't require CSRF tokens (as per HTTP specification)
Session-based: CSRF secret is stored in session, not exposed to client
See Also
Request - For generating CSRF tokens
AuthMiddleware - For authentication
Session - For session management
Last updated