Encontrei um Solução da estendendo a classe AbstractAuthenticator como abaixo estou utilizando o PHP8.1, além de ter colocado a chave do token no arquivo .env.
class Authenticator extends AbstractAuthenticator
{
public function __construct(
private readonly UserRepository $userRepository
) {
}
public function supports(Request $request): ?bool
{
return $request->getPathInfo() !== '/login';
}
public function authenticate(Request $request): Passport
{
$token = str_replace(
'Bearer ',
'',
$request->headers->get('Authorization')
);
if (empty($token)) {
throw new CustomUserMessageAccountStatusException(
'Invalid token'
);
}
$credentials = JWT::decode($token, new Key($_ENV['JWT_SECRET'], 'HS256'));
$username = $credentials->username;
return new SelfValidatingPassport(new UserBadge($username, function (string $userIdentifier) {
return $this->userRepository
->findOneBy(['username' => $userIdentifier]);
}));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return new JsonResponse(['message' => 'Invalid credentials'], Response::HTTP_UNAUTHORIZED);
}
}
Meu arquivo security.yaml, ficou da seguinte forma:
security:
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
custom_authenticator: App\Helpers\Security\Authenticator