src/Security/ApiAuthenticator.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Config;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  11. use Symfony\Contracts\HttpClient\HttpClientInterface;
  12. class ApiAuthenticator implements EventSubscriberInterface
  13. {
  14.     private $em;
  15.     private $client;
  16.     public function __construct(EntityManagerInterface $emHttpClientInterface $client)
  17.     {
  18.         $this->em $em;
  19.         $this->client $client;
  20.     }
  21.     public function authenticate(Request $request)
  22.     {
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [KernelEvents::REQUEST => ['onKernelRequest'128]];
  27.     }
  28.     /**
  29.      * @throws TransportExceptionInterface
  30.      */
  31.     public function onKernelRequest(RequestEvent $event): void
  32.     {
  33.         $request $event->getRequest();
  34.         if(str_starts_with($request->getRequestUri(),'/api')) {
  35.             if (!($request->headers->has('Authorization') && === strpos($request->headers->get('Authorization'), 'Bearer '))) {
  36.                 $event->setResponse(new Response('Unauthorized.'401));
  37.             }
  38.             $authorization $request->headers->get('Authorization');
  39.             $apiToken substr($authorization7);
  40.             $options['auth_bearer'] = $apiToken;
  41.             /** @var Config $config */
  42.             $config $this->em->getRepository(Config::class)->findOne();
  43.             $response $this->client->request(
  44.                 'GET',
  45.                 $config->getEventUrl(),
  46.                 $options
  47.             );
  48.             if(!($response->getStatusCode() ===200)){
  49.                 $event->setResponse(new Response('Unauthorized.'401));
  50.             }
  51.         }
  52.     }
  53. }