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

Nik*_*hak 0 symfony jwt lexikjwtauthbundle

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

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

我想知道是否有某种东西isTokenValid('the-token-string');可以给出真/假响应?

Maj*_*far 5

将 JWTEncoderInterface 注入您的控制器,

public function __construct(JWTEncoderInterface $jwtEncoder)
{
  $this->jwtEncoder = $jwtEncoder;
}
Run Code Online (Sandbox Code Playgroud)

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

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

    } catch (JWTDecodeFailureException $ex) {
            // if no exception thrown then the token could be used
    }
Run Code Online (Sandbox Code Playgroud)

如果没有抛出异常,则可以使用令牌。请注意,如果出现以下情况,则会引发异常

  • 令牌无效
  • 令牌已过期
  • 令牌未验证

但如果你想具体知道发生了哪一种情况,你应该将
JWSProviderInterface 注入到你的控制器中

public function __construct(JWSProviderInterface $jwsProvider)
{
  $this->jwsProvider = $jwsProvider;
}
Run Code Online (Sandbox Code Playgroud)

并在你的方法中调用它的加载动作,如下所示

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
   }
Run Code Online (Sandbox Code Playgroud)