简而言之,我想要在Google API上获取带有服务帐户的新访问令牌。我使用了OAuth 2.0和JWT请求。我发现了很多类似的帖子,但其中没有人回答我的问题。我做了一切符合Google OAuth 2.0 Server-to-Server request guide,但是当我发送POST请求时,我得到了“invalid_grant”的回报。任何想法为什么?这里是我的代码:PHP Google API OAuth2 JWT对新访问令牌的请求显示为“invalid_grant”
$jwt_header_array = array( "alg" => "RS256",
"typ" => "JWT");
$jwt_claim_array = array( "iss" => "[email protected]",
"scope" => "https://www.googleapis.com/auth/drive.file",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"exp" => time()+3600,
"iat" => time());
$jwt_header = base64_encode(json_encode($jwt_header_array));
$jwt_claim = base64_encode(json_encode($jwt_claim_array));
$key = "-----BEGIN PRIVATE KEY----- privat_key_downloaded_from_google_console -----END PRIVATE KEY-----\n";
$pkeyid = openssl_pkey_get_private($key);
openssl_sign($jwt_header.'.'.$jwt_claim, $jwt_signature, $pkeyid, "sha256");
$jwt_signature = base64_encode($jwt_signature);
$jwt = $jwt_header.'.'.$jwt_claim.'.'.$jwt_signature;
echo $jwt.'<br /><br />';
$url = 'https://www.googleapis.com/oauth2/v4/token';
$query = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion='.$jwt;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$result = curl_exec($ch);
var_dump($result);
从技术上说,您需要base64对JWT元素进行url编码,而不仅仅是base64对它们进行编码 –
这些编码是很好的,因为我得到了正确的JWT头文件,并在Google的示例中声明了相同的输入。唯一的问题是签名,我无法验证,因为密钥与示例中使用的不同。 –