src/Listener/Security/ApiTokenSubscriber.php line 33

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Listener\Security;
  4. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\HttpKernel\KernelInterface;
  9. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  10. final class ApiTokenSubscriber implements EventSubscriberInterface
  11. {
  12.     private ?string $xAuthToken null;
  13.     private ?string $env 'dev';
  14.     public function __construct(ParameterBagInterface $theParameterBagKernelInterface $theKernel)
  15.     {
  16.         $this->xAuthToken $theParameterBag->get('x_auth_token');
  17.         $this->env $theKernel->getEnvironment();
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             // ORDRE POUR NE PAS PASSER PAR DESSUS LE listener : lexik_jwt_authentication.handler.authentication_failure
  23.             KernelEvents::FINISH_REQUEST => ['onKernelFinishRequest'],
  24.         ];
  25.     }
  26.     public function onKernelFinishRequest(FinishRequestEvent $theEvent): void
  27.     {
  28.         // Don't do anything if it's not the master request.
  29.         if (!$theEvent->isMainRequest()) {
  30.             return;
  31.         }
  32.         $theRequest $theEvent->getRequest();
  33.         $controller $theRequest->attributes->get('_controller');
  34.         if (
  35.             $this->env === 'prod'
  36.             || (
  37.                 // Swagger de l'API
  38.                 $controller !== 'api_platform.swagger_ui.action'
  39.                 // Profiler symfony
  40.                 && !str_starts_with($controller'web_profiler.controller.profiler::')
  41.             )
  42.         ) {
  43.             if (!$theRequest->headers->has('X-AUTH-TOKEN')) {
  44.                 throw new AccessDeniedException('Token de l\'API inexistant.');
  45.             } elseif ($theRequest->headers->get('X-AUTH-TOKEN') !== $this->xAuthToken) {
  46.                 throw new AccessDeniedException('Token de l\'API invalide.');
  47.             }
  48.         }
  49.     }
  50. }