在Symfony中如何使用LexicJWT在EventSubscriber中获取用户

时间:2018-12-14 13:37:32

标签: php symfony lexikjwtauthbundle

我是Symfony的新手。我使用LexicJWT令牌。

final class ProductCreateSubscriber implements EventSubscriberInterface
{
    private $entityManager;
    private $hostRepository;

    public function __construct(EntityManagerInterface $entityManager, HostRepository $hostRepository)
    {
        $this->entityManager = $entityManager;
        $this->hostRepository = $hostRepository;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['createHost', EventPriorities::PRE_WRITE],
        ];
    }

    public function createHost(GetResponseForControllerResultEvent $event)
    {
        $product = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        - - - - - -- - - I NEED USER HERE - - - - -  - -    

        if (!$product instanceof Product || Request::METHOD_POST !== $method) {
            return;
        } 

        $parsedUrl = parse_url($product->getUrl());
        if (isset($parsedUrl['host'])) {
            $host = $this->hostRepository->findOneByName($parsedUrl['host']);
            if (!$host) {
                $host = $this->hostRepository->createByName($parsedUrl['host']);
            }
            $product->setHost($host);
        }
    }
}

如何在createHost方法中获取用户?如何在EventSubsriber中获得用户或令牌?找不到有关此的任何信息?我在哪里可以读到它?

1 个答案:

答案 0 :(得分:2)

JWT令牌通过标头传递,因此您需要在事件中访问标头。

您可以尝试像这样访问标头:

$request = $event->getRequest();
$headers = $request->headers->all();

您可以从标头中获取包含JWT令牌的Authentication标头,并将其解码以获取用户。

更新: 正如@Jared Farrish提到的,请确保令牌有效!