How to get userid from eventlistener which are called from AJAX

后端 未结 3 1013
时光取名叫无心
时光取名叫无心 2021-01-12 05:23

I am using symfony2 and FOSUserBundle.

Normally,I can get user data from Controller

$user = $this->get(\'security.context\')->getToken()->g         


        
3条回答
  •  暖寄归人
    2021-01-12 06:18

    As of Symfony 2.6 this issue should be fixed. A pull request has just been accepted into the master. Your problem is described in here. https://github.com/symfony/symfony/pull/11690

    As of Symfony 2.6, you can inject the security.token_storage into your listener. This service will contain the token as used by the SecurityContext in <=2.5. In 3.0 this service will replace the SecurityContext::getToken() altogether. You can see a basic change list here: http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service

    Example usage in 2.6:

    Your configuration:

    services:
        my.listener:
            class: EntityListener
            arguments:
                - "@security.token_storage"
            tags:
                - { name: doctrine.event_listener, event: prePersist }
    


    Your Listener

    use Doctrine\ORM\Event\LifecycleEventArgs;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    
    class EntityListener
    {
        private $token_storage;
    
        public function __construct(TokenStorageInterface $token_storage)
        {
            $this->token_storage = $token_storage;
        }
    
        public function prePersist(LifeCycleEventArgs $args)
        {
            $entity = $args->getEntity();
            $entity->setCreatedBy($this->token_storage->getToken()->getUsername());
        }
    }
    

提交回复
热议问题