Symfony2: Why does getToken return null when injecting SecurityContext into TwigExtension?

I made exactly the answer from this post , but the token property is null, and the user is correctly registered and the route is behind the firewall. In addition, I am embedding SecurityContext in other services and it is working fine.

services.xml:

<service id="tc.extensions.relation_helper" class="TC\CoreBundle\Extensions\RelationHelperExtension"> <argument type="service" id="security.context" /> <tag name="twig.extension" /> </service> 

My extension:

 class RelationHelperExtension extends Twig_Extension { /** * @var User */ private $user; public function __construct(SecurityContext $securityContext){ $this->user = $securityContext->getToken()->getUser(); } 
+4
source share
2 answers

As @Elnur_Abdurrakhimov said, we must first cache the securityContext and call getToken()->getUser() if necessary.

 class RelationHelperExtension extends Twig_Extension { private $context; public function __construct(SecurityContext $securityContext){ $this->context= $securityContext; } private function getUser(){ return $this->context->getToken()->getUser(); } 
+5
source

To understand this behavior:

Twig_Extension set before sequence SecurityContext => SecurityContext is empty

But if you store it in an attribute when you use your own twigy extension service (in most cases) in the request area, and the SecurityContext is initialized with good values ​​:)

+3
source

Source: https://habr.com/ru/post/1501908/


All Articles