Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a1b1a44

Browse files
committed
feature #25197 [FrameworkBundle][TwigBridge] make csrf_token() usable without forms (xabbuh)
This PR was merged into the 4.1-dev branch. Discussion ---------- [FrameworkBundle][TwigBridge] make csrf_token() usable without forms | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | | License | MIT | Doc PR | 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. Commits ------- 709efa3 make csrf_token() usable without forms
2 parents d4bfbb8 + 709efa3 commit a1b1a44

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

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 <[email protected]>
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 <[email protected]>
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)