1
votes

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
    }
}
2
Are You logged in ??skowron-line
@skowron-line yes I'm loggedsadok-f
@joaoalves thanks for your response but I'm not using a Listener to sent it with hight priority.sadok-f
I suppose that your service is created early before security.context is populated.Konstantin Pelepelin

2 Answers

1
votes

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;
    }
0
votes

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

     ....