schnittstabil/csrf-twig-helpers

CSRF (Cross-Site Request Forgery) protection helpers for the Twig templating engine.

1.1.1 2016-04-08 16:03 UTC

This package is auto-updated.

Last update: 2024-10-26 02:31:05 UTC


README

SensioLabsInsight

CSRF (Cross-Site Request Forgery) protection helpers for the Twig templating engine 🌵

Install

$ composer require schnittstabil/csrf-twig-helpers

Usage

<?php
/**
 * Some callable, which is used to get csrf tokens. E.g:
 */
function getToken() {
    if (!isset($_SESSION['csrf_token'])) {
        // generate a new token...
    }

    return $_SESSION['csrf_token'];
}

$twig = new Twig_Environment($loader);

$twig->addExtension(
    new Schnittstabil\Csrf\Twig\Helpers\Extension(getToken, 'X-XSRF-TOKEN')
);
?>

Template functions

{{ csrf_token() }}
{# => result of getToken() #}

{{ csrf_token_name() }}
{# => X-XSRF-TOKEN #}

{{ csrf_input_widget() }}
{# => <input name="X-XSRF-TOKEN" type="hidden" value="...some token..." /> #}

{{ csrf_meta_widget() }}
{# => <meta name="X-XSRF-TOKEN" content="...some token..." /> #}

Slim v3 Example

For complete examples see the examples directory.

Install Additional Requirements

$ composer require slim/slim slim/twig-view schnittstabil/psr7-csrf-middleware

Twig Templates

<!-- index.html.twig -->
<form role="form" method="post" action="{{ path_for('contact') }}">
    <input type="email" name="email" />
    <textarea name="message"></textarea>
    {{ csrf_input_widget() }}
    <button type="submit">Send!</button>
</form>

Scripts

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

use Schnittstabil\Psr7\Csrf\MiddlewareBuilder as CsrfMiddlewareBuilder;

/**
 * Create App
 */
$app = new Slim\App();

/**
 * Register Csrf Middleware
 */
$app->getContainer()['csrf'] = function ($c) {
    $key = 'This key is not so secret - change it!';

    return CsrfMiddlewareBuilder::create($key)
        ->buildSynchronizerTokenPatternMiddleware();
};
$app->add('csrf');

/**
 * Register Twig Extensions
 */
$app->getContainer()['view'] = function ($c) {
    $view = new Slim\Views\Twig('templates', [
        'cache' => 'cache',
    ]);
    $view->addExtension(new Slim\Views\TwigExtension(
        $c['router'],
        $c['request']->getUri()
    ));
    $view->addExtension(new Schnittstabil\Csrf\Twig\Helpers\Extension(
        [$c['csrf']->getTokenService(), 'generate']
    ));

    return $view;
};

/**
 * Add routes
 */
$app->get('/', function ($request, $response) {
    return $this->view->render($response, 'index.html.twig');
});

$app->post('/contact', function ($request, $response) {
    return $this->view->render($response, 'contact.html.twig');
})->setName('contact');

/**
 * Run app
 */
$app->run();
?>

Related

License

MIT © Michael Mayer