我正在尝试使用带有FOSRestBundle的LexikJWTAuthBundle来保护我的API路由。当我在请求的头部手动提供JWT时,它工作得很好,但对于我的应用程序,我想通过'kernel.request‘SF事件自动将它添加到每个API请求的头部。
问题是我事件订阅者似乎没有被正确调度,我认为LexikJWTAuthBundle以前检测到我的请求中没有任何JWT,并返回401响应。
事件订阅者:
<?php
namespace MyApp\APIBundle\EventListener;
use MyApp\APIBundle\Controller\TokenAPIController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class RequestAPIListener implements EventSubscriberInterface
{
/**
* @var string Token API
*/
private $apiToken;
public function __construct(string $apiToken = null)
{
$this->apiToken = $apiToken;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
// dump('hi'); <---- This is execute when uncomment
// die;
return [
KernelEvents::REQUEST => [
'onRequest'
]
];
}
public function onRequest(GetResponseEvent $event)
{
dump($event, $this->apiToken); <---- This is not execute
die;
$request->headers->set('Authorization', "Bearer $token");
}
}
事件订阅者定义:
services:
myapp.api_bundle.event_listener.request_api:
class: MyApp\APIBundle\EventListener\RequestAPIListener
arguments: ['@=service("service_container").get("session").get("api_token")']
tags:
- { name: kernel.event_subscriber }
我该如何解决这个问题呢?或者,如果您知道另一种自动添加令牌的方法?
https://stackoverflow.com/questions/41269500
复制相似问题