sadok-f
sadok-f

Reputation: 1457

Symfony Service Configurator: getToken with security.context is NULL

I'm using Symfony Service Configurator in my project to configure a service after its instantiation (Docs), in Configure method I need the current user logged so I inject the container and I tried to get the token form Security.context service but I got always NULL. I tried also to inject only Security.context in my Configurator construct but I got same result.

Any ideas pls

Thanks.

class MyConfigurator
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }


    public function configure()
    {
        $user = $this->container->get('security.context')->getToken();
        var_dump($user); // = NULL
    }
}

Upvotes: 1

Views: 1348

Answers (2)

Tsounabe
Tsounabe

Reputation: 2184

A better way should be:

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

class MyConfigurator
{
     private $tokenStorage;

     public function __construct(EntityManager $em, TokenStorage $tokenStorage)
     {
         $this->em = $em;
         $this->tokenStorage= $tokenStorage;
     }

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

     ....

Upvotes: 0

sadok-f
sadok-f

Reputation: 1457

I resolve the problem by getting the UserId from the session and fetch the current User from Database.

The UserId is set previously by a AuthenticationListener in my project. So I modify my Configurator construct to be like this:

    /**
     * @param EntityManager $em
     * @param Session $session
     */
    public function __construct(EntityManager $em, Session $session)
    {
        $this->em = $em;
        $this->session = $session;
    }

Upvotes: 1

Related Questions