2

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 ?

1 Answer 1

6

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
   }
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.