Symfony JWT令牌:令牌过期时的异常

我正在使用JWT Token Bundle进行用户身份验证.当令牌过期时,我得到500服务器错误.而不是这个如何返回JsonResponse与错误代码和消息?

这是我的身份验证员类:

 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);
}
}

最佳答案 您可以在try-catch中解码令牌:

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

但是你可能不得不实现丢失的onAuthenticationFailure,因为抛出这个异常会使它被调用.就像是:

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

顺便说一句,LexikJWTAuthenticationBundle自2.0版以来就内置了JWTTokenAuthenticator.我建议你在实现自己的身份验证器之前尝试使用它,或至少extend it.

点赞