如何在服务中获取当前登录的用户

时间:2016-04-26 16:08:25

标签: symfony symfony-2.8

在Symfony 2.8 / 3.0中,如果使用我们新的安全组件,如何在服务中获取当前记录的User即FOSUser )对象,而不需要注入整个容器?<​​/ p>

甚至可以用非hacky方式吗?

PS:我们不认为&#34; 将其作为参数传递给服务功能&#34;因为显而易见。另外,很脏。

8 个答案:

答案 0 :(得分:43)

security.token_storage服务注入您的服务,然后使用:

$this->token_storage->getToken()->getUser();

如此处所述:http://symfony.com/doc/current/book/security.html#retrieving-the-user-object和此处:http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services

答案 1 :(得分:22)

使用构造函数依赖注入,您可以这样做:

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class A
{
    private $user;

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

    public function foo()
    {
        dump($this->user);
    }
}

答案 2 :(得分:15)

版本3.4中的新增功能:Symfony 3.4中引入了Security实用程序类。

use Symfony\Component\Security\Core\Security;

public function indexAction(Security $security)
{
    $user = $security->getUser();
}

https://symfony.com/doc/3.4/security.html#always-check-if-the-user-is-logged-in

答案 3 :(得分:4)

来自Symfony 3.3,<仅来自控制器的 ,根据此博文:https://symfony.com/blog/new-in-symfony-3-2-user-value-resolver-for-controllers

这很简单:

use Symfony\Component\Security\Core\User\UserInterface

public function indexAction(UserInterface $user)
{...}

答案 4 :(得分:4)

在symfo 4中:

use Symfony\Component\Security\Core\Security;

class ExampleService
{
    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function someMethod()
    {
        $user = $this->security->getUser();
    }
}

参阅文档:https://symfony.com/doc/current/security.html#retrieving-the-user-object

答案 5 :(得分:2)

Symfony在Symfony \ Bundle \ FrameworkBundle \ ControllerControllerTrait中执行此操作

protected function getUser()
{
    if (!$this->container->has('security.token_storage')) {
        throw new \LogicException('The SecurityBundle is not registered in your application.');
    }

    if (null === $token = $this->container->get('security.token_storage')->getToken()) {
        return;
    }

    if (!is_object($user = $token->getUser())) {
        // e.g. anonymous authentication
        return;
    }

    return $user;
}

因此,如果您只是注入并替换security.token_storage,那么您就可以了。

答案 6 :(得分:1)

如果你扩展Controller

$this->get('security.context')->getToken()->getUser();

或者,如果您有权访问容器元素..

$container = $this->configurationPool->getContainer();
$user = $container->get('security.context')->getToken()->getUser();

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

答案 7 :(得分:0)

这在 Symfony 5.2 中运行良好

$this->get('security.token_storage')->getToken()->getUser()