本文介绍了Symfony2:为什么在 TwigExtension 中注入 SecurityContext 时 getToken 返回 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全按照 这篇文章 的回答做了,但令牌属性是null 且用户已正确登录且路由位于防火墙后面.此外,我正在其他服务中注入 SecurityContext 并且它工作正常.

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 :

services.xml :

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

我的扩展:

class RelationHelperExtension extends Twig_Extension
{
    /**
     * @var User
     */
    private $user;

    public function __construct(SecurityContext $securityContext){
        $this->user = $securityContext->getToken()->getUser();
    }

推荐答案

正如@Elnur_Abdurrakhimov 所说,我们必须首先缓存 securityContext,并在需要时调用 getToken()->getUser().

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();
    }

这篇关于Symfony2:为什么在 TwigExtension 中注入 SecurityContext 时 getToken 返回 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:29