src/Security/AppAuthentificator.php line 40

Open in your IDE?
  1. <?php
  2. // src/Security/ApiKeyAuthenticator.php
  3. namespace App\Security;
  4. use App\Exception\BadRequestException;
  5. use App\Repository\ApplicationRepository;
  6. use Firebase\JWT\JWT;
  7. use Firebase\JWT\Key;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  13. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  14. use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
  15. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  16. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  17. use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
  18. class AppAuthentificator extends AbstractAuthenticator
  19. {
  20.     protected $applicationRepository;
  21.     public function __construct(ApplicationRepository $applicationRepository)
  22.     {
  23.         $this->applicationRepository $applicationRepository;
  24.     }
  25.     public function supports(Request $request): ?bool
  26.     {
  27.         return $request->headers->has('X-CLIENT-ID');
  28.     }
  29.     public function authenticate(Request $request): Passport
  30.     {
  31.         $clientId $request->headers->get('X-CLIENT-ID');
  32.         $clientSecret $request->headers->get('X-CLIENT-SECRET');
  33.         $application $this->applicationRepository->findOneBy(['client_id' => $clientId]);
  34.         if (!$application || $application->getClientSecret() !== $clientSecret) {
  35.             throw new CustomUserMessageAuthenticationException('Invalid client ID or client secret');
  36.         }
  37.         try {
  38.             JWT::decode($clientSecret, new Key($_ENV["AUTH_SECRET_KEY"], 'HS256'));
  39.         } catch (\Exception $e){
  40.             throw new BadRequestException('Invalid key: '.$e->getMessage());
  41.         }
  42.         return new SelfValidatingPassport(new UserBadge($clientId));
  43.     }
  44.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  45.     {
  46.         return null;
  47.     }
  48.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  49.     {
  50.         $data = [
  51.             'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
  52.         ];
  53.         return new JsonResponse($dataResponse::HTTP_UNAUTHORIZED);
  54.     }
  55. }