Event 'kernel.request' doesn't dispatch correctly

508 views Asked by At

I'm trying tu use LexikJWTAuthBundle with FOSRestBundle to securize my API routes. It works well when I manually give the JWT in the header of my requests, but for my app I would like to add it automatically in each API requests' header via the 'kernel.request' SF event.

The problem is that my event subscriber seems to not be dispatch correctly, I suppose that LexikJWTAuthBundle detect before that I don't have any JWT in my request and return me 401 responses.

The event subscriber :

<?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");
    }
}

The event subscriber definition :

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 }

How can I solve this ? Or maybe if you know another way to add automatically the token ?

1

There are 1 answers

0
Maxime Picard On BEST ANSWER

The problem was just the priority of my custom listener.

The Firewall listener was triggered before mine, so I set a priority higher for mine :

public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => [
                ['onRequest', 10]
            ]
        ];
    }