【问题标题】:How in Symfony get user in EventSubscriber using LexicJWTSymfony 如何使用 LexicJWT 在 EventSubscriber 中获取用户
【发布时间】:2019-05-15 18:56:35
【问题描述】:

我是 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 中获取用户或令牌?找不到这方面的任何信息?我在哪里可以阅读它?

【问题讨论】:

    标签: php symfony lexikjwtauthbundle


    【解决方案1】:

    JWT token 是通过 header 传递的,所以需要在 event 中访问 header。

    您可以尝试这样访问标题:

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

    您可以从标头中获取包含 JWT 令牌的 Authentication 标头,然后对其进行解码以获取用户。

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多