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

  1. Safe methods bypass validation: GET, HEAD, OPTIONS requests automatically pass

  2. Origin validation (if configured): Checks Origin or Referer header against allowed origins

  3. Token validation: Validates CSRF token from X-CSRF-TOKEN header or _token POST parameter

  4. Time-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

  1. Time-bucketed tokens: Tokens rotate automatically every hour (default), reducing exposure window

  2. Grace period: Previous bucket tokens are accepted to prevent race conditions during rotation

  3. Origin validation: Additional layer of protection against cross-origin attacks

  4. Safe methods: GET requests don't require CSRF tokens (as per HTTP specification)

  5. Session-based: CSRF secret is stored in session, not exposed to client

See Also

Last updated