0

Using LexikJWTAuthenticationBundle, it is possible to validate a passed token within a controller?

p.s. I am aware that I can do $this->getUser() that returns the User if the user was authenticated and null otherwise. But that is not what I'm after.

I wish to know if there is something of the sort isTokenValid('the-token-string'); that gives a true/false response ?

Niket Pathak
  • 6,323
  • 1
  • 39
  • 51

1 Answers1

4

inject JWTEncoderInterface to your controller,

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

then in your method you can decode the token like this

try {
      $this->jwtEncoder->decode($token);

    } catch (JWTDecodeFailureException $ex) {
            // if no exception thrown then the token could be used
    }

if no exception is thrown then the token could be used. be aware that the exception is thrown if

  • token is not valid
  • token is expired
  • token is not verified

but if you want to specifically know which one is occurred you should inject
JWSProviderInterface to your controller

public function __construct(JWSProviderInterface $jwsProvider)
{
  $this->jwsProvider = $jwsProvider;
}

and in your method call load action of it like this

try{
      $jws = $this->jwsProvider->load($token);

   }catch(\Exception $e){

   }

   if (!$jws->isInvalid()) {
         //if  token is valid
    }

    if (!$jws->isExpired()) {
         //if  token is not expired
   }

   if ($jws->isVerified()) {
        //if  token is verified
   }
  • 1
    You don't need to use jws provider to check that, the `JWTDecodeFailureException` also contains method `getReason()` which you can check against the constants: `JWTDecodeFailureException::EXPIRED_TOKEN`, `JWTDecodeFailureException::UNVERIFIED_TOKEN`, `JWTDecodeFailureException::INVALID_TOKEN`. – Rikudou_Sennin Jul 11 '19 at 13:32