Symfony2 : Why getToken return null when injecting SecurityContext in a TwigExtension?

孤街浪徒 提交于 2020-02-24 00:50:35

问题


I did exactly the answer from this post but the token property is null and the user is correctly logged in and the route is behind a firewall. Also, I am injecting the SecurityContext in other services and it works 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();
    }

回答1:


As @Elnur_Abdurrakhimov said we must cache the securityContext first and the call the getToken()->getUser() when needed.

class RelationHelperExtension extends Twig_Extension
{
    private $context;

    public function __construct(SecurityContext $securityContext){
        $this->context= $securityContext;
    }

    private function getUser(){
            return $this->context->getToken()->getUser();
    }



回答2:


To understand this behavior :

Twig_Extension are instancied BEFORE SecurityContext init sequence => at this moment SecurityContext is empty

But if you store it in a attribute, when you USE your own twig extension serviceyou are (in most of case) in a Request scope & SecurityContext is initalized with good values :)



来源:https://stackoverflow.com/questions/18770467/symfony2-why-gettoken-return-null-when-injecting-securitycontext-in-a-twigexte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!