Revision: Tue, 18 Feb 2020 08:24:29 GMT

HTTP - CSRF protection

The default Web bundle including CSRF protection middleware. To install it in alternative bundles:

$ composer require spiral/csrf

To activate the extension:


The extension will activate Spiral\Csrf\Middleware\CsrfMiddleware in order to issue unique token for every user.

Enable Firewall

The extension provides two middleware which activates the protection on your routes and/or globally. To protect all the requests except GET, HEAD, OPTIONS use Spiral\Csrf\Middleware\CsrfFirewall:

use Spiral\Csrf\Middleware\CsrfFirewall;

// ...

public function boot(RouterInterface $router)
    $route = new Route('/', new Target\Action(HomeController::class, 'index'));


To protect againt all the HTTP verbs use Spiral\Csrf\Middleware\StrictCsrfFirewall.


Once the protection is activated you must sign every request with the token available via PSR-7 attribute csrfToken.

To receive this token in the controller or view:

public function index(ServerRequestInterface $request)
    $csrfToken = $request->getAttribute('csrfToken');

Every POST/PUT/DELETE request from user must include this token as POST parameter csrf-token or header X-CSRF-Token. User will receive 412 Bad CSRF Token if token is missing or not set.

public function index(ServerRequestInterface $request)
    $form = '
        <form method="post">
          <input type="hidden" name="csrf-token" value="{csrfToken}"/>
          <input type="text" name="value"/>
          <input type="submit"/>

    $form = str_replace(

    return $form;

Activate Globally

To activate CSRF protection globally register Spiral\Csrf\Middleware\CsrfFirewall or Spiral\Csrf\Middleware\StrictCsrfFirewall via HttpBootloader:

use Spiral\Csrf\Middleware\CsrfFirewall;

// ...

public function boot(HttpBootloader $http)
Edit this page