Skip to content

Commit 2abd80e

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 2abd80e

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/Symfony/Bridge/Twig/Extension/SecurityExtension.php

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use Symfony\Component\Security\Acl\Voter\FieldVote;
1515
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
1616
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
17+
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
1718
use Twig\Extension\AbstractExtension;
1819
use Twig\TwigFunction;
1920

@@ -25,10 +26,12 @@
2526
class SecurityExtension extends AbstractExtension
2627
{
2728
private $securityChecker;
29+
private $csrfTokenManager;
2830

29-
public function __construct(AuthorizationCheckerInterface $securityChecker = null)
31+
public function __construct(AuthorizationCheckerInterface $securityChecker = null, CsrfTokenManagerInterface $csrfTokenManager = null)
3032
{
3133
$this->securityChecker = $securityChecker;
34+
$this->csrfTokenManager = $csrfTokenManager;
3235
}
3336

3437
public function isGranted($role, $object = null, $field = null)
@@ -48,14 +51,25 @@ public function isGranted($role, $object = null, $field = null)
4851
}
4952
}
5053

54+
public function getCsrfToken(string $tokenId): string
55+
{
56+
return $this->csrfTokenManager->getToken($tokenId)->getValue();
57+
}
58+
5159
/**
5260
* {@inheritdoc}
5361
*/
5462
public function getFunctions()
5563
{
56-
return array(
64+
$functions = array(
5765
new TwigFunction('is_granted', array($this, 'isGranted')),
5866
);
67+
68+
if (null !== $this->csrfTokenManager) {
69+
$functions[] = new TwigFunction('csrf_token', array($this, 'getCsrfToken'));
70+
}
71+
72+
return $functions;
5973
}
6074

6175
/**

src/Symfony/Bundle/SecurityBundle/Resources/config/templating_twig.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
<service id="twig.extension.security" class="Symfony\Bridge\Twig\Extension\SecurityExtension">
1616
<tag name="twig.extension" />
1717
<argument type="service" id="security.authorization_checker" on-invalid="ignore" />
18+
<argument type="service" id="security.csrf.token_manager" on-invalid="null" />
1819
</service>
1920
</services>
2021
</container>

0 commit comments

Comments
 (0)