【问题标题】:How to validate a jwt token programmatically in Symfony?如何在 Symfony 中以编程方式验证 jwt 令牌?
【发布时间】:2019-03-23 23:59:43
【问题描述】:

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

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

我想知道是否有类似isTokenValid('the-token-string'); 的东西会给出 true/false 响应?

【问题讨论】:

    标签: symfony jwt lexikjwtauthbundle


    【解决方案1】:

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

    【讨论】:

    • 您不需要使用 jws 提供程序来检查,JWTDecodeFailureException 还包含方法 getReason() 您可以检查常量:JWTDecodeFailureException::EXPIRED_TOKENJWTDecodeFailureException::UNVERIFIED_TOKENJWTDecodeFailureException::INVALID_TOKEN .
    猜你喜欢
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2020-03-07
    • 2019-06-23
    • 1970-01-01
    相关资源
    最近更新 更多