简体   繁体   English

如何验证用户JWT通过令牌传递是否正确

[英]How to validate the user JWT pass over Token is correct

My mean is not validate a correct format Token. 我的意思是不验证正确格式的令牌。

According to jwt/README.md at 3.2 · lcobucci/jwt This validate is validating a correct format Token, but when I set a value like http://example.org/token/123.123.123 ,this library will throw an exception, like this: 根据jwt / README.md的3.2·lcobucci / jwt,此验证正在验证正确格式的令牌,但是当我设置http://example.org/token/123.123.123类的值时,该库将引发异常,像这样:

在此处输入图片说明

How to validate the user JWT pass over Token is correct with 2 dots? 如何验证用户JWT通过令牌传递正确的2个点?

I already have a solution, share to all: 我已经有了一个解决方案,可以分享给所有人:

// $token from a HTTP request.
// Must have 2 dots.
if (substr_count($token, '.') === 2) {
    $preValidToken = base64_decode($token);
    // Get decoded token's last '}' position.
    $lastPos = strrpos($preValidToken, '}');
    if ($lastPos) {
        // Assemble Json string.
        $preValidToken = '[' . substr($preValidToken, 0, $lastPos + 1) . ']';
        $preValidToken = str_replace('}{', '},{', $preValidToken);
        // Convert to associative array.
        $preValidToken = json_decode($preValidToken, true);
        if ($preValidToken && is_array($preValidToken)) {
            var_dump($preValidToken);
            die;
            $token = (new Parser())->parse((string) $token);
            // Parses from a string
            // Do something here...
        }
    }
}
echo json_encode([
    'code' => 205,
    'msg' => 'Token not valid '
]);
exit();

If valided, $preValidToken will be a array , content like this: 如果有效,则$preValidToken将为array ,内容如下:

array (size=2)
  0 => 
    array (size=3)
      'typ' => string 'JWT' (length=3)
      'alg' => string 'HS256' (length=5)
      'jti' => string '123123123' (length=9)
  1 => 
    array (size=6)
      'iss' => string 'http://example.org' (length=13)
      'jti' => string '123123123' (length=9)
      'iat' => int 1524314239
      'nbf' => int 1524314299
      'exp' => int 1524317839
      'uid' => int 1

And then, we can verify that the token is valid through verifying this array, if no problem, we can execute next code line $token = (new Parser())->parse((string) $token); 然后,我们可以通过验证此数组来验证令牌是否有效,如果没有问题,我们可以执行下一个代码行$token = (new Parser())->parse((string) $token); without error. 没有错误。

I do not know if there is a better way? 不知道有没有更好的办法?

There's no need to pre-validate anything, because the library is giving you an exception; 无需预先验证任何内容,因为该库为您提供了一个例外。 the purpose of exceptions is that they can be caught in order to handle the situation. 例外的目的是为了处理这种情况而将其捕获。 So all you need is this: 因此,您需要的是:

try {
    $token_info = (new Parser())->parse((string) $token_string);
    // successful
} catch(RuntimeException $e) {
    // unsuccessful
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM