From 709efa30fc4b4e67e14ffb60ac004187703c90c6 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 28 Nov 2017 18:56:57 +0100 Subject: [PATCH] make csrf_token() usable without forms The Twig function `csrf_token()` is currently only registered when the Form component is installed. However, this function is also useful, for example, when creating simple login forms for which you do not need the full Form component. --- .../Bridge/Twig/Extension/CsrfExtension.php | 44 +++++++++++++++++++ .../Resources/config/security_csrf.xml | 5 +++ 2 files changed, 49 insertions(+) create mode 100644 src/Symfony/Bridge/Twig/Extension/CsrfExtension.php diff --git a/src/Symfony/Bridge/Twig/Extension/CsrfExtension.php b/src/Symfony/Bridge/Twig/Extension/CsrfExtension.php new file mode 100644 index 0000000000..97f3484a29 --- /dev/null +++ b/src/Symfony/Bridge/Twig/Extension/CsrfExtension.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\Twig\Extension; + +use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; +use Twig\Extension\AbstractExtension; +use Twig\TwigFunction; + +/** + * @author Christian Flothmann + */ +class CsrfExtension extends AbstractExtension +{ + private $csrfTokenManager; + + public function __construct(CsrfTokenManagerInterface $csrfTokenManager) + { + $this->csrfTokenManager = $csrfTokenManager; + } + + /** + * {@inheritdoc} + */ + public function getFunctions(): array + { + return array( + new TwigFunction('csrf_token', array($this, 'getCsrfToken')), + ); + } + + public function getCsrfToken(string $tokenId): string + { + return $this->csrfTokenManager->getToken($tokenId)->getValue(); + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml index 8a3ffac2da..e7bcec1c5f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml @@ -21,5 +21,10 @@ + + + + +