src/Listener/Security/ApiTokenSubscriber.php line 33
<?php
declare(strict_types=1);
namespace App\Listener\Security;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class ApiTokenSubscriber implements EventSubscriberInterface
{
private ?string $xAuthToken = null;
private ?string $env = 'dev';
public function __construct(ParameterBagInterface $theParameterBag, KernelInterface $theKernel)
{
$this->xAuthToken = $theParameterBag->get('x_auth_token');
$this->env = $theKernel->getEnvironment();
}
public static function getSubscribedEvents(): array
{
return [
// ORDRE POUR NE PAS PASSER PAR DESSUS LE listener : lexik_jwt_authentication.handler.authentication_failure
KernelEvents::FINISH_REQUEST => ['onKernelFinishRequest'],
];
}
public function onKernelFinishRequest(FinishRequestEvent $theEvent): void
{
// Don't do anything if it's not the master request.
if (!$theEvent->isMainRequest()) {
return;
}
$theRequest = $theEvent->getRequest();
$controller = $theRequest->attributes->get('_controller');
if (
$this->env === 'prod'
|| (
// Swagger de l'API
$controller !== 'api_platform.swagger_ui.action'
// Profiler symfony
&& !str_starts_with($controller, 'web_profiler.controller.profiler::')
)
) {
if (!$theRequest->headers->has('X-AUTH-TOKEN')) {
throw new AccessDeniedException('Token de l\'API inexistant.');
} elseif ($theRequest->headers->get('X-AUTH-TOKEN') !== $this->xAuthToken) {
throw new AccessDeniedException('Token de l\'API invalide.');
}
}
}
}