src/Program/Security/Authenticator/ApiAuthenticator.php line 19

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Program\Security\Authenticator;
  4. use App\Program\Gateway\ProgramGateway;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  10. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  11. use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
  12. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  13. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  14. use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
  15. final class ApiAuthenticator extends AbstractAuthenticator
  16. {
  17.     public function __construct(private ProgramGateway $userLoader)
  18.     {
  19.     }
  20.     public function supports(Request $request): ?bool
  21.     {
  22.         return $request->headers->has('X-AUTH-TOKEN');
  23.     }
  24.     public function authenticate(Request $request): Passport
  25.     {
  26.         $apiKey $request->headers->get('X-AUTH-TOKEN');
  27.         if (null === $apiKey) {
  28.             throw new CustomUserMessageAuthenticationException('No API key provided');
  29.         }
  30.         return new SelfValidatingPassport(new UserBadge($apiKey, [$this->userLoader'loadUserByIdentifier']));
  31.     }
  32.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  33.     {
  34.         return null;
  35.     }
  36.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  37.     {
  38.         $data = [
  39.             'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
  40.         ];
  41.         return new JsonResponse($dataResponse::HTTP_UNAUTHORIZED);
  42.     }
  43. }