gpt4 book ai didi

Symfony JWT token : exception when token is expired

转载 作者:行者123 更新时间:2023-12-02 17:03:10 25 4
gpt4 key购买 nike

我正在使用 JWT token 包进行用户身份验证。当 token 过期时,我收到 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 中解码 token :

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 .

关于Symfony JWT token : exception when token is expired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43137913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com