How to get the current logged User in a service

冷暖自知 提交于 2019-11-28 01:47:15

Inject security.token_storage service into your service, and then use:

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

as described here: http://symfony.com/doc/current/book/security.html#retrieving-the-user-object and here: http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services

Using constructor dependency injection, you can do it this way:

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

New in version 3.4: The Security utility class was introduced in 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

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

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

From Symfony 3.3, from a Controller only, according this blog post: https://symfony.com/blog/new-in-symfony-3-2-user-value-resolver-for-controllers

It's easy as:

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

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

Symfony does this in 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;
}

So if you simply inject and replace security.token_storage, you're good to go.

if you class extend of Controller

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

Or, if you has access to container element..

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!