8000 make csrf_token() usable without forms · symfony/symfony@709efa3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 709efa3

Browse files
committed
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.
1 parent 22192b1 commit 709efa3

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Bridge\Twig\Extension;
13+
14+
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
15+
use Twig\Extension\AbstractExtension;
16+
use Twig\TwigFunction;
17+
18+
/**
19+
* @author Christian Flothmann <christian.flothmann@sensiolabs.de>
20+
*/
21+
class CsrfExtension extends AbstractExtension
22+
{
23+
private $csrfTokenManager;
24+
25+
public function __construct(CsrfTokenManagerInterface $csrfTokenManager)
26+
{
27+
$this->csrfTokenManager = $csrfTokenManager;
28+
}
29+
30+
/**
31+
* {@inheritdoc}
32+
*/
33+
public function getFunctions(): array
34+
{
35+
return array(
36+
new TwigFunction('csrf_token', array($this, 'getCsrfToken')),
37+
);
38+
}
39+
40+
public function getCsrfToken(string $tokenId): string
41+
{
42+
return $this->csrfTokenManager->getToken($tokenId)->getValue();
43+
}
44+
}

src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,10 @@
2121
<argument type="service" id="request_stack" on-invalid="ignore" />
2222
</service>
2323
<service id="Symfony\Component\Security\Csrf\CsrfTokenManagerInterface" alias="security.csrf.token_manager" />
24+
25+
<service id="twig.extension.security_csrf" class="Symfony\Bridge\Twig\Extension\CsrfExtension">
26+
<tag name="twig.extension" />
27+
<argument type="service" id="security.csrf.token_manager" />
28+
</service>
2429
</services>
2530
</container>

0 commit comments

Comments
 (0)
0