1

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
    }
}
sadok-f
  • 1,387
  • 15
  • 28

2 Answers2

1

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;
    }
sadok-f
  • 1,387
  • 15
  • 28
0

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

     ....
Tsounabe
  • 2,109
  • 1
  • 16
  • 25