PSR-7 Storage-less HTTP CSRF protection
PSR7Csrf is a PSR-7 middleware that enables CSRF protection for PSR-7 based applications.
psr7-sessions/storageless
5.0.0+
DEPRECATED in favor of Please note that this package is DEPRECATED.
Since psr7-sessions/storageless
5.0.0,
the generated cookies are CSRF-resistant by default for unsafe HTTP methods (POST
/PUT
/DELETE
/PATCH
/etc.),
so the usage of this package is no longer needed.
You can still install ocramius/psr7-csrf
, but since there is no practical need for it,
it is not necessary to do so.
What is this about?
Instead of storing tokens in the session, PSR7Csrf simply uses JWT tokens, which can be verified, signed and have a specific lifetime on their own.
This storage-less approach prevents having to load tokens from a session or from a database, and simplifies the entire UI workflow: tokens are valid as long as their signature and expiration date holds.
Installation
composer require ocramius/psr7-csrf
Usage
The simplest usage is based on defaults. It assumes that you have a configured PSR-7 compatible application that supports piping middlewares, and it also requires you to run PSR7Session.
In a zendframework/zend-expressive
application, the setup would look like the following:
$app = \Zend\Expressive\AppFactory::create();
$app->pipe(\PSR7Session\Http\SessionMiddleware::fromSymmetricKeyDefaults(
'mBC5v1sOKVvbdEitdSBenu59nfNfhwkedkJVNabosTw=', // replace this with a key of your own (see PSR7Session docs)
1200 // 20 minutes session duration
));
$app->pipe(\PSR7Csrf\Factory::createDefaultCSRFCheckerMiddleware());
This setup will require that any requests that are not GET
, HEAD
or
OPTIONS
contain a csrf_token
in the request body parameters (JSON
or URL-encoded).
You can generate the CSRF token for any form like following:
$tokenGenerator = \PSR7Csrf\Factory::createDefaultTokenGenerator();
$app->get('/get', function ($request, $response) use ($tokenGenerator) {
$response
->getBody()
->write(
'<form method="post" action="/post">'
. '<input type="submit"/>'
. '<input type="hidden" name="csrf_token" value="'
. $tokenGenerator($request)
. '"/>'
. '</form>'
);
return $response;
});
$app->post('/post', function ($request, $response) {
$response
->getBody()
->write('It works!');
return $response;
});
Examples
composer install # install at the root of this package first!
cd examples
composer install
php -S localhost:9999 index.php
Then try accessing http://localhost:9999
: you should see a simple
submission form.
If you try modifying the submitted CSRF token (which is in a hidden
form field), then the POST
request will fail.
Known limitations
Please refer to the known limitations of PSR7Session.
Also, this component does NOT prevent double-form-submissions: it merely prevents CSRF attacks from third parties. As long as the CSRF token is valid, it can be reused over multiple requests.
Contributing
Please refer to the contributing notes.
License
This project is made public under the MIT LICENSE.