<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class ApiKeyAuthenticator extends AbstractAuthenticator
{
public function start(): Response
{
$data = [
// you might translate this message
'code' => Response::HTTP_UNAUTHORIZED,
'message' => Response::$statusTexts[Response::HTTP_UNAUTHORIZED],
'result' => [
'error' => 'Authentication Required'
]
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function supports(Request $request): ?bool
{
return $request->headers->has('X-API-KEY');
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$data = [
// you may want to customize or obfuscate the message first
'code' => Response::HTTP_UNAUTHORIZED,
'message' => Response::$statusTexts[Response::HTTP_UNAUTHORIZED],
'result' => [
'error' => $exception->getMessage()
]
// or to translate this message
// $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
// on success, let the request continue
return null;
}
public function supportsRememberMe(): void
{
// TODO: Implement supportsRememberMe() method.
}
public function authenticate(Request $request): Passport
{
$apiToken = $request->headers->get('X-API-KEY');
if (null === $apiToken) {
throw new CustomUserMessageAuthenticationException('No X-API-KEY provided');
}
return new SelfValidatingPassport(new UserBadge($apiToken));
}
}