Symfony2 服务构造函数中的 getUser

问题描述:

我的 Symfony2 服务中有一个非常奇怪的问题.我想在我的服务的构造函数中获取当前用户,但 SecurityContext->getToken 返回 false!

I have a very strange problem in one of my Symfony2's service. I want to get the current user in the constructor of my service but the SecurityContext->getToken return false!

那是我的服务构造函数:

That is my service constructor :

public function __construct(Registry $doctrine, SecurityContext $context){
    $this->doctrine = $doctrine;
    $this->context = $context;
    if(!$this->context->getToken()){
        echo "Il y a une merde au niveau du token !";
    }
    $this->my_auth = $this->getMyAuth();
}

这里是我的 service.yml 中的服务声明

And here the service declaration in my service.yml

security.autorisation:
    class: Nsi\SecurityBundle\Service\Autorisation
    arguments: [@doctrine,@security.context]

但是当我进入我的管理页面时,会出现消息Il y a une merde au niveau du Token".最令人惊讶的是,我底部的 symfony 工具栏显示了我的登录信息!

But when I go on my admin page, the message "Il y a une merde au niveau du Token" appear. the most surprising is that my bottom symfony toolbar show me my login !

我的项目是一个 Symfony 2.3.11 项目

My project is a Symfony 2.3.11 project

想得到你的帮助

不要从服务构造函数中调用它,因为服务初始化在身份验证之前调用.这就是您没有设置令牌的原因.

Don't call it from service constructor, because service initialization called earlier than authentication. That's why you have no token set.