如何在Symfony中以编程方式验证jwt令牌?

时间:2019-03-23 23:59:43

标签: symfony jwt lexikjwtauthbundle

使用 LexikJWTAuthenticationBundle ,可以在控制器内验证传递的令牌吗?

p.s。我知道我可以执行$this->getUser()来返回用户的身份(如果用户已通过身份验证),否则返回null。但这不是我所追求的。

我想知道是否有某种isTokenValid('the-token-string');给出了 true / false 响应?

1 个答案:

答案 0 :(得分:2)

将JWTEncoderInterface注入您的控制器,

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

然后在您的方法中,您可以像这样解码令牌

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

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

如果未引发异常,则可以使用令牌。请注意,如果

会引发异常
  • 令牌无效
  • 令牌已过期
  • 令牌未验证

但是如果您想具体知道发生了哪一个,则应该注入
 控制器的JWSProviderInterface

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

并在您的方法中调用它的加载操作

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
   }
相关问题