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



使用LexikJWTAuthenticationBundle,是否可以在控制器中验证传递的令牌?

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

我想知道是否有那种isTokenValid('the-token-string');给出真/假回答的东西?

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

最新更新