PHP code example of schnittstabil / psr7-csrf-middleware
1. Go to this page and download the library: Download schnittstabil/psr7-csrf-middleware library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
schnittstabil / psr7-csrf-middleware example snippets
Schnittstabil\Psr7\Csrf\MiddlewareBuilder as CsrfMiddlewareBuilder;
/*
* Shared secret key used for generating and validating CSRF tokens:
*/
$key = 'This key is not so secret - change it!';
/*
* Build a stateless Synchronizer Token Pattern CSRF proptection middleware.
*/
$csrfMiddleware = CsrfMiddlewareBuilder::create($key)
->buildSynchronizerTokenPatternMiddleware();
/*
* Build a (AngularJS compatible) stateless Cookie-To-Header CSRF proptection middleware.
*
* Requires additional dependency:
* composer
/*
* Requires additional dependency:
* composer essage\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Slim\App;
use Schnittstabil\Psr7\Csrf\MiddlewareBuilder as CsrfMiddlewareBuilder;
$app = new App();
/*
* CSRF protection setup
*/
$app->getContainer()['csrf_token_name'] = 'X-XSRF-TOKEN';
$app->getContainer()['csrf'] = function ($c) {
$key = 'This key is not so secret - change it!';
return CsrfMiddlewareBuilder::create($key)
->buildSynchronizerTokenPatternMiddleware($c['csrf_token_name']);
};
$app->add('csrf');
/*
* GET routes are not protected (by default)
*/
$app->get('/', function (RequestInterface $request, ResponseInterface $response) {
$name = $this->csrf_token_name;
$token = $this->csrf->getTokenService()->generate();
// render HTML...
$response = $response->write("<input type=\"hidden\" name=\"$name\" value=\"$token\" />");
return $response->write('successfully GET!');
});
/*
* POST routes are protected (by default; same applies to PUT, DELETE and PATCH)
*/
$app->post('/', function (RequestInterface $request, ResponseInterface $response) {
return $response->write('successfully POST');
});
/*
* Run application
*/
$app->run();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.