symfonysecurity-context

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

Solution

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