Symfony JWT symbol: exception when token has expired
I am using JWT Token Bundle to authenticate users. When the token has expired I get 500 server errors. Instead, how can I return a JsonResponse with an error code and message?
Here is my authentication 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);
}
}
source to share
You can decode the token in 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
one as it gets thrown when this exception is thrown. Something like:
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
return new JsonResponse([
'errorMessage' => $exception->getMessage(),
], Response::HTTP_UNAUTHORIZED);
}
Btw, LexikJWTAuthenticationBundle comes with built JWTTokenAuthenticator
in version 2.0. I suggest you try using it before implementing your own authenticator, or at least extend it .
source to share
I wrap all my code in a try catch block, when a JWT Token Expired error is generated, it goes into the block catch
.
{"error": 1, "status": 400, msg ":" JWT token expired "" data ": []}
/**
* @Route("/api/tokens")
* @Method("POST")
*/
public function newTokenAction(Request $request)
{
try {
$data['_username'] = $request->get('_username');
$data['_password'] = $request->get('_password');
if (empty($data['_username']) || empty($data['_password'])) {
throw new \Exception('Username or password fields empty');
}
$user = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(array('username' => $data['_username']));
if (!$user) {
throw new \Exception('Username or password does not exist');
} else if ($user->hasRole('ROLE_SUPER_ADMIN')) {
throw new \Exception('Admin is not allowed to login through app');
} else if (!$user->getEnabled()) {
throw new \Exception('User is not enabled');
} else if ($user->getIsDeleted()) {
throw new \Exception('User does not exist any more');
}
$isValid = $this->get('security.password_encoder')->isPasswordValid($user, $data['_password']);
if (!$isValid) {
throw new \Exception('Bad Credentials');
}
$token = $this->get('lexik_jwt_authentication.encoder')->encode(array(
'username' => $data['_username'],
'exp' => time() + 3600,
'secret_key' => ____________,
));
$user->setAuthToken($token);
$em = $this->getEntityManager();
$em->persist($user);
$em->flush();
$json = $this->getJsonResponse(0, 200, 'User Logged In');
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response;
} catch (\Exception $e) {
// Using custom Execption class
$customApiProblem = new CustomApiProblem(self::API_ERROR_TRUE, $httpStatusCode, $e->getMessage());
$customApiProblem->set('data', $data);
$serializer = $this->container->get('jms_serializer');
$response_json = $serializer->serialize($customApiProblem->toArray(), 'json');
return new Response($response_json, $statusCode);
}
}
source to share