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

问题描述 投票:26回答:7

在Symfony 2.8 / 3.0中,使用我们新的安全组件,如何在不注入整个容器的情况下获取服务中当前记录的User(即FOSUser)对象?

它甚至可能以非黑客的方式存在吗?

PS:让我们不要将“将其作为参数传递给服务函数”,因为这很简单。还有,很脏。

symfony symfony-2.8
7个回答
45
投票

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


26
投票

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

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

16
投票

版本3.4中的新功能:安全实用程序类是在Symfony 3.4中引入的。

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


8
投票

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

见doc:https://symfony.com/doc/current/security.html#retrieving-the-user-object


4
投票

来自Symfony 3.3,仅来自Controller,根据这篇博文: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)
{...}

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,那么你很高兴。


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

© www.soinside.com 2019 - 2024. All rights reserved.