Search code examples
symfonyjwtlexikjwtauthbundle

How to validate a jwt token programmatically in Symfony?


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 ?


Solution

  • 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
       }