FastSitePHP\Security\Web\CsrfSession

Session-Based CSRF Tokens

Source Code

GitHub

Exemple de Code

Security - CSRF using Session

// One call to a static function creates a token on GET Requests
// and validates it with Requests POST, PUT, DELETE, etc.
// If there is an error with the token then an exception is
// thrown which will cause 500 response with the error page.
\FastSitePHP\Security\Web\CsrfSession::setup($app);

// The token is assigned a locals value in the Application Object
$token = $app->locals['csrf_token'];

// This allows it to be used with templating code.
// Tokens are validated from [setup()] but not automatically added
// to forms so they must be added through templating or by code.
//
// <meta name="X-CSRF-Token" content="{{ $csrf_token }}">
// <input name="X-CSRF-Token" value="{{ $csrf_token }}">

// A good place to call this function is on route filters
// of pages that use authentication. Example:

// Create a filter function to assign to multiple routes
$csrf_session = function() use ($app) {
    \FastSitePHP\Security\Web\CsrfSession::setup($app);
};

// Use the function when defining a route
$app->get('/form', function() use ($app) {
    return $app->render('form.php');
})
->filter($csrf_session);

Methods

setup(Application $app, $key = 'X-CSRF-Token')

Static Function

Setup and validate session-based CSRF Tokens. A good place to call this function is on route filters of pages that use authentication.

This will assign the token to app property $app->locals['csrf_token'] which then must be included with the form or response. When using [$app->render()] the value will be available as variable [$csrf_token].

For usage see demo code.