CsrfMiddleware
in package
implements
MiddlewareInterface
Middleware that validates CSRF tokens.
Requires valid CSRF token for POST, PUT, DELETE, and PATCH requests. Token must be provided via:
- Form field: _csrf_token
- Header: X-CSRF-TOKEN
GET and OPTIONS requests are exempt. API requests with Bearer tokens are exempt (API tokens serve as CSRF protection).
Tags
Table of Contents
Interfaces
- MiddlewareInterface
- Interface for route middleware.
Constants
- FORM_FIELD = '_csrf_token'
- Form field name for CSRF token.
- HEADER_NAME = 'X-CSRF-TOKEN'
- Header name for CSRF token.
- PROTECTED_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH']
- HTTP methods that require CSRF validation.
- SESSION_TOKEN = 'LWT_SESSION_TOKEN'
- Session key for CSRF token.
Methods
- formField() : string
- Generate a hidden form field with the CSRF token.
- getToken() : string
- Get the current CSRF token for embedding in forms.
- handle() : bool
- Handle the incoming request.
- diagnoseFailure() : string
- Diagnose why CSRF validation failed.
- extractToken() : string|null
- Extract CSRF token from request.
- formatBytes() : string
- Format bytes into a human-readable string.
- handleInvalidToken() : void
- Handle invalid or missing CSRF token.
- hasApiToken() : bool
- Check if request has a plausible API Bearer token.
- isApiRequest() : bool
- Check if this is an API request.
- parseIniSize() : int
- Parse a PHP ini size value (e.g. "8M") to bytes.
- sendForbiddenPage() : never
- Send 403 Forbidden HTML page.
- sendForbiddenResponse() : never
- Send 403 Forbidden JSON response.
- validateToken() : bool
- Validate the CSRF token.
Constants
FORM_FIELD
Form field name for CSRF token.
private
mixed
FORM_FIELD
= '_csrf_token'
HEADER_NAME
Header name for CSRF token.
private
mixed
HEADER_NAME
= 'X-CSRF-TOKEN'
PROTECTED_METHODS
HTTP methods that require CSRF validation.
private
array<string|int, string>
PROTECTED_METHODS
= ['POST', 'PUT', 'DELETE', 'PATCH']
SESSION_TOKEN
Session key for CSRF token.
private
mixed
SESSION_TOKEN
= 'LWT_SESSION_TOKEN'
Methods
formField()
Generate a hidden form field with the CSRF token.
public
static formField() : string
Return values
string —HTML hidden input element
getToken()
Get the current CSRF token for embedding in forms.
public
static getToken() : string
Creates a new token if one doesn't exist in the session.
Return values
string —The CSRF token
handle()
Handle the incoming request.
public
handle() : bool
Validates CSRF token for state-changing requests.
Return values
bool —True if validation passes, false if halted
diagnoseFailure()
Diagnose why CSRF validation failed.
private
diagnoseFailure() : string
Return values
string —Human-readable reason for the failure
extractToken()
Extract CSRF token from request.
private
extractToken() : string|null
Checks form field first, then header.
Return values
string|null —The token or null if not found
formatBytes()
Format bytes into a human-readable string.
private
static formatBytes(int $bytes) : string
Parameters
- $bytes : int
-
Number of bytes
Return values
string —Formatted string (e.g. "1.5 MB")
handleInvalidToken()
Handle invalid or missing CSRF token.
private
handleInvalidToken([string $reason = '' ]) : void
Parameters
- $reason : string = ''
-
Diagnostic reason for the failure
hasApiToken()
Check if request has a plausible API Bearer token.
private
hasApiToken() : bool
API tokens serve as CSRF protection since they're not automatically sent by browsers like cookies are. The actual token validity is verified by AuthMiddleware, which runs before CsrfMiddleware. Here we only confirm the token is non-trivial (minimum 20 chars).
Return values
bool —True if Bearer token present and non-trivial
isApiRequest()
Check if this is an API request.
private
isApiRequest() : bool
Return values
bool —True if API request
parseIniSize()
Parse a PHP ini size value (e.g. "8M") to bytes.
private
static parseIniSize(string $size) : int
Parameters
- $size : string
-
The ini size string
Return values
int —Size in bytes
sendForbiddenPage()
Send 403 Forbidden HTML page.
private
sendForbiddenPage([string $reason = '' ]) : never
Parameters
- $reason : string = ''
-
Diagnostic reason for the failure
Return values
neversendForbiddenResponse()
Send 403 Forbidden JSON response.
private
sendForbiddenResponse() : never
Return values
nevervalidateToken()
Validate the CSRF token.
private
validateToken() : bool
Return values
bool —True if token is valid