PHP -使用OAuth 2.0的服务器到服务器应用程序-无效授权


PHP - Using OAuth 2.0 for Server to Server Applications - Invalid grant

我正在尝试使用Google Api日历,但我无法通过验证步骤。

在本教程之后,我写了一些php代码(是的,我知道,我应该使用API),给我"无效授予"作为响应。

我很固执,我真的知道我的错误在哪里。我想是符号步骤,但private_key是一个有效的结构体。我通过使用以下命令转换p12获得。pem:

openssl pkcs12 -in key。P12 -out密钥。pem节点

你能帮帮我吗?

谢谢。

<?php
$private_key = openssl_pkey_get_private('file://key.pem', 'notasecret');
$header = array("alg" => "RS256", "typ" => "JWT");
$header = base64_encode(utf8_encode(json_encode($header)));
$exp = time() + (60 * 60); 
$jwt_cs = array(
   "iss" => "************************@developer.gserviceaccount.com",
   "scope" => "https://www.googleapis.com/auth/calendar.readonly",
   "aud" => "https://accounts.google.com/o/oauth2/token",
   "exp" => $exp,
   "iat" => time(),
   "access_type" => "offline"
);
$jwt_cs = base64_encode(utf8_encode(json_encode($jwt_cs)));
openssl_sign($header.$jwt_cs, $sign, $private_key, 'sha256WithRSAEncryption');
$sign = base64_encode($sign);
$jwt = $header.$jwt_cs.$sign;
$login_data = array(
    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' => $jwt
);
$url='https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($login_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = json_decode(curl_exec($ch));
curl_close($ch);
var_dump($res)
?>

在计算签名时,需要将签名头和声明集用点'连接起来。’,即$header . '.' . $jwt_cs。在构建JWT时,还需要将标题、声明集和签名与点'连接起来。',即$header . '.' . $jwt_cs . '.' . $sign