CSRF Protection

Slim 3 uses the optional standalone slimphp/Slim-CsrfPHP component to protect your application from CSRF (cross-site request forgery).This component generates a unique token per request that validates subsequentPOST requests from client-side HTML forms.

Installation

Execute this bash command from your project’s root directory:

  1. composer require slim/csrf

Usage

The slimphp/Slim-Csrf component contains an application middleware. Add itto your application like this:

  1. // Add middleware to the application
  2. $app = new \Slim\App;
  3. $app->add(new \Slim\Csrf\Guard);
  4. // Create your application routes...
  5. // Run application
  6. $app->run();

Fetch the CSRF token name and value

The latest CSRF token’s name and value are available as attributes on thePSR7 request object. The CSRF token name and value are unique for each request.You can fetch the current CSRF token name and value like this.

  1. $app->get('/foo', function ($req, $res, $args) {
  2. // CSRF token name and value
  3. $nameKey = $this->csrf->getTokenNameKey();
  4. $valueKey = $this->csrf->getTokenValueKey();
  5. $name = $req->getAttribute($nameKey);
  6. $value = $req->getAttribute($valueKey);
  7. // Render HTML form which POSTs to /bar with two hidden input fields for the
  8. // name and value:
  9. // <input type="hidden" name="<?= $nameKey ?>" value="<?= $name ?>">
  10. // <input type="hidden" name="<?= $valueKey ?>" value="<?= $value ?>">
  11. });
  12. $app->post('/bar', function ($req, $res, $args) {
  13. // CSRF protection successful if you reached
  14. // this far.
  15. });

You should pass the CSRF token name and value to the template so theymay be submitted with HTML form POST requests. They are often stored as a hiddenfield with HTML forms.

For more use cases and documentation please check slimphp/Slim-Csrf’s page.