projectDir = $kernel->getProjectDir(); } /** * Called on every request to decide if this authenticator should be used for the request. * Returning `false` will cause this authenticator to be skipped. */ public function supports(Request $request): ?bool { return $request->headers->has('X-API-KEY'); } public function authenticate(Request $request): Passport { $apiToken = $request->headers->get('X-API-KEY'); $envFile = $this->projectDir . DIRECTORY_SEPARATOR . 'env.json'; if (!is_file($envFile)) { throw new CustomUserMessageAuthenticationException('Configuration file not found.'); } $config = json_decode(file_get_contents($envFile), true); $expectedToken = $config['vars']['OGCLIENT_API_KEY'] ?? null; if (null === $expectedToken || $apiToken !== $expectedToken) { throw new CustomUserMessageAuthenticationException('Invalid API Token.'); } // Usamos tu propia entidad User para crear un usuario virtual "al vuelo" return new SelfValidatingPassport(new UserBadge('ogclient_api_user', function() { $apiUser = new User(); $apiUser->setUsername('ogclient_api_user'); $apiUser->setRoles(['ROLE_OGCLIENT_API']); $apiUser->setPassword(''); // Evitamos nulos en propiedades requeridas si las hay return $apiUser; })); } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { // on success, let the request continue return null; } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { $data = [ 'message' => strtr($exception->getMessageKey(), $exception->getMessageData()) ]; return new JsonResponse($data, Response::HTTP_UNAUTHORIZED); } }