简体   繁体   English

Symfony2的服务构造函数中的getUser

[英]getUser in Symfony2's service constructor

I have a very strange problem in one of my Symfony2's service. 我在Symfony2的一项服务中遇到一个非常奇怪的问题。 I want to get the current user in the constructor of my service but the SecurityContext->getToken return false! 我想在服务的构造函数中获取当前用户,但SecurityContext-> getToken返回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();
}

And here the service declaration in my service.yml 这是我的service.yml中的服务声明

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

But when I go on my admin page, the message "Il ya une merde au niveau du Token" appear. 但是,当我进入管理页面时,会出现消息“ Il ya une merde au niveau du Token”。 the most surprising is that my bottom symfony toolbar show me my login ! 最令人惊讶的是,我的底部symfony工具栏显示了我的登录信息!

My project is a Symfony 2.3.11 project 我的项目是一个Symfony 2.3.11项目

Thinks for your help 寻求您的帮助

Don't call it from service constructor, because service initialization called earlier than authentication. 不要从服务构造函数中调用它,因为服务初始化的调用要早于身份验证。 That's why you have no token set. 这就是为什么您没有设置令牌的原因。

Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM