-
I'm following this page on how to setup JWT authentication and when I try it out, I get a 401, but looking at the logs, it doesn't even look to be using my handler class, which I'm totally lost on. here is my security.yaml: security:
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers:
App\Entity\User:
algorithm: 'bcrypt'
cost: 15
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
stateless: true
provider: app_user_provider
# setup JWT handler.
# https://symfony.com/doc/current/security/access_token.html
access_token:
token_handler: App\Security\JwtHandler
token_extractors: header but in the logs, I see this:
Am I missing a step? I feel like I followed the documentation so I'm lost on why it's using AccessTokenAuthenticator instead of my own. this is my token handler object: <?php
namespace App\Security;
use App\Contracts\Services\JwtServiceInterface;
use App\Repository\UserRepository;
use SensitiveParameter;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
readonly class JwtHandler implements AccessTokenHandlerInterface
{
public function __construct(private JwtServiceInterface $jwtService, private UserRepository $userRepository)
{
}
public function getUserBadgeFrom(#[SensitiveParameter] string $accessToken): UserBadge
{
if ($this->jwtService->isTokenValid($accessToken)) {
$identifier = $this->jwtService->parseJwt($accessToken, 'email');
// should be a rare occurrence but check anyway.
if ($identifier === null) {
throw new BadCredentialsException('Invalid credentials.');
}
$user = $this->userRepository->find($identifier);
if ($user === null) {
throw new BadCredentialsException('Invalid credentials.');
}
return new UserBadge($user->getUserIdentifier());
}
throw new BadCredentialsException('Invalid credentials.');
}
} I appreciate any help on what I'm possibly doing wrong as I don't know why this is not working. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Your Symfony’s Check how your access token is supposed to be extracted from the request, and configure |
Beta Was this translation helpful? Give feedback.
Your
JwtHandler
is not an authenticator: its responsibility is to return aUserBadge
from an access token.Symfony’s
AccessTokenAuthenticator
is the authenticator so it’s expected it gets called, but in your case theHeaderAccessTokenExtractor
fails to get the access token from the request, so yourJwtHandler
is not called.Check how your access token is supposed to be extracted from the request, and configure
token_extractors
accordingly.