Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony JWT token: exception when token is expired

I am using JWT Token Bundle for user authentication. When the token is expired I get 500 server error. Instead of this how can I return JsonResponse with error code and message?

Here is my authenticator class:

 class JwtTokenAuthentication extends AbstractGuardAuthenticator
{
/**
 * @var JWTEncoderInterface
 */
private $jwtEncoder;

/**
 * @var EntityManager
 */
private $em;

public function __construct(JWTEncoderInterface $jwtEncoder, EntityManager $em)
{
    $this->jwtEncoder = $jwtEncoder;
    $this->em = $em;
}


public function getCredentials(Request $request)
{
    $extractor = new AuthorizationHeaderTokenExtractor(
        'Bearer',
        'Authorization'
    );
    $token = $extractor->extract($request);
    if (!$token) {
        return null;
    }

    return $token;
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $data = $this->jwtEncoder->decode($credentials);
    if(!$data){
      return null;
    }
    $user = $this->em->getRepository("AlumnetCoreBundle:User")->find($data["email"]);
    return $user;
}

public function checkCredentials($credentials, UserInterface $user)
{
    return true;
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    //todo
}

public function start(Request $request, AuthenticationException $authException = null)
{
    return new JsonResponse([
        'errorMessage' => 'auth required'
    ], Response::HTTP_UNAUTHORIZED);
}
}
like image 975
blahblah Avatar asked Oct 30 '22 09:10

blahblah


1 Answers

You can decode the token in a try-catch:

try {
    $data = $this->jwtEncoder->decode($credentials);
} catch (\Exception $e) {
    throw new \Symfony\Component\Security\Core\Exception\BadCredentialsException($e->getMessage(), 0, $e);
}

But you might have to implement the missing onAuthenticationFailure since throwing this exception will make it called. Something like:

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    return new JsonResponse([
        'errorMessage' => $exception->getMessage(),
    ], Response::HTTP_UNAUTHORIZED);
}

Btw, LexikJWTAuthenticationBundle comes with a built-in JWTTokenAuthenticator since its 2.0 version. I suggest you to try using it before implementing your own authenticator, or at least extend it.

like image 86
chalasr Avatar answered Jan 02 '23 20:01

chalasr