src/Security/ApiKeyAuthenticator.php line 16

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use Symfony\Component\HttpFoundation\JsonResponse;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  8. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  9. use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
  10. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  11. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  12. use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
  13. class ApiKeyAuthenticator extends AbstractAuthenticator
  14. {
  15.     /**
  16.      * Called on every request to decide if this authenticator should be
  17.      * used for the request. Returning `false` will cause this authenticator
  18.      * to be skipped.
  19.      */
  20.     public function supports(Request $request): ?bool
  21.     {
  22.         return $request->headers->has('x-api-key');
  23.     }
  24.     public function authenticate(Request $request): Passport
  25.     {
  26.         $apiToken $request->headers->get('x-api-key');
  27.         if (null === $apiToken) {
  28.             // The token header was empty, authentication fails with HTTP Status
  29.             // Code 401 "Unauthorized"
  30.             throw new CustomUserMessageAuthenticationException('No API token provided');
  31.         }
  32.         return new SelfValidatingPassport(new UserBadge($apiToken));
  33.     }
  34.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  35.     {
  36.         // on success, let the request continue
  37.         return null;
  38.     }
  39.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  40.     {
  41.         $data = [
  42.             // you may want to customize or obfuscate the message first
  43.             'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
  44.             // or to translate this message
  45.             // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
  46.         ];
  47.         return new JsonResponse($dataResponse::HTTP_UNAUTHORIZED);
  48.     }
  49. }