我正在使用 JWT 令牌包进行用户身份验证。当令牌过期时,我收到 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);
}
}