Skip to content

Stateless PSR-7 CSRF (Cross-Site Request Forgery) protection middleware 🔏

License

Notifications You must be signed in to change notification settings

schnittstabil/psr7-csrf-middleware

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Psr7\Csrf\Middleware Build Status Coverage Status Scrutinizer Code Quality Code Climate

SensioLabsInsight

Stateless PSR-7 CSRF (Cross-Site Request Forgery) protection middleware 🔏

Install

$ composer require schnittstabil/psr7-csrf-middleware

Usage

<?php
require __DIR__.'/vendor/autoload.php';

use 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 require dflydev/fig-cookies
 */
$csrfMiddleware = CsrfMiddlewareBuilder::create($key)
    ->buildCookieToHeaderMiddleware();
?>

Slim v3 Example

<?php
/*
 * Requires additional dependency:
 *     composer require slim/slim
 */
require __DIR__.'/vendor/autoload.php';

use Psr\Http\Message\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();
?>

Related

License

MIT © Michael Mayer

About

Stateless PSR-7 CSRF (Cross-Site Request Forgery) protection middleware 🔏

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages