解码来自Google的JWT字符串失败[php]

2022-04-11 00:00:00 json jwt decode google-oauth php

我正在尝试用PHP解码JWT加密串。该字符串是有效的,因为它可以在以下位置完全解码:Working Demo

我正在使用ThisGITHUB进行解码。

我的代码片段是,它以数组形式从Google获取公钥,效果很好。但解码部分出现以下错误。

include('JWT.php');

$refresh = false;
if (file_exists('oauthkey')) {
   $age = time() - filemtime('oauthkey');
   if ($age > 20000)
      $refresh = true;   
} else
   $refresh = true;

if ($refresh) {
   $oauthKey = file_get_contents('https://www.googleapis.com/oauth2/v1/certs')
      or die('Failed to retrieve google public key.');
   $keyFile = fopen('oauthkey', 'w') or die ('Failed to open public key file for writing.');
   fwrite($keyFile, $oauthKey);
   fclose($keyFile);
} else {
   $keyFile = fopen('oauthkey', 'r') or die ('Failed to open public key file for reading.');
   $oauthKey = fread($keyFile, 5000) or die ('Failed to read from public key file.');
   fclose($keyFile);   
}
$oauthKey = json_decode($oauthKey, true); // get key from Google in Array

$jwtstring = 'eyJhbGciOiJS...'; // full long JWT encoded string

$bla = JWT::decode($jwtstring, $oauthKey);

echo print_r($bla);

错误:

PHP Notice:  Undefined index: 433d0da18366fcdc43301fd1e142294a6209e451 in /home/domain.com/php-jwt-master/Authentication/JWT.php on line 64
PHP Warning:  openssl_verify(): supplied key param cannot be coerced into a public key in /home/domain.com/php-jwt-master/Authentication/JWT.php on line 179
PHP Fatal error:  Uncaught exception 'DomainException' with message 'OpenSSL unable to verify data: ' in /home/domain.com/php-jwt-master/Authentication/JWT.php:181
Stack trace:
#0 /home/domain.com/php-jwt-master/Authentication/JWT.php(71): JWT::verify('eyJhbGciOiJSUzI...', '+??????0?????SK...', NULL, 'RS256')
#1 /home/domain.com/php-jwt-master/Authentication/testjwt.php(31): JWT::decode('eyJhbGciOiJSUzI...', Array)
#2 {main}
  thrown in /home/domain.com/php-jwt-master/Authentication/JWT.php on line 181

解决方案

发现问题。

必须将‘False’添加到DECODE语句。

$bla = JWT::decode($jwtstring, $oauthKey, false);

相关文章