src/Security/JWTAuthenticator.php line 25
<?php/*** Created by PhpStorm.* User: JMR* Date: 25/10/2024* Time: 09:12*/// src/Security/JWTAuthenticator.phpnamespace App\Security;use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpFoundation\Response; // Import the correct Response classuse 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\Core\User\UserInterface;use Symfony\Component\Security\Core\User\UserProviderInterface;use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;use Symfony\Component\Security\Http\Authenticator\Passport\Passport;use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;class JWTAuthenticator extends AbstractAuthenticator{private $jwtEncoder;public function __construct(JWTEncoderInterface $jwtEncoder){$this->jwtEncoder = $jwtEncoder;}public function supports(Request $request): ?bool{// Check if the request contains the Authorization headerreturn $request->headers->has('x-authorization');}public function authenticate(Request $request): Passport{$authHeader = $request->headers->get('x-authorization');$token = null;if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {$token = substr($authHeader, 7);}/*if (!$token) {throw new CustomUserMessageAuthenticationException('Token not provided');}*///var_dump($token);$decodedData = $this->jwtEncoder->decode($token);//var_dump($decodedData);/*if (!$decodedData) {throw new CustomUserMessageAuthenticationException('Invalid token');}*/// Here you could fetch the user using the decoded data, e.g., decodedData['username']return new SelfValidatingPassport(new UserBadge($decodedData['username']));}public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response{// No action needed on success, just return null to continue to the controllerreturn null;}public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response{return new JsonResponse(['error' => $exception->getMessageKey()], 401);}}