【发布时间】:2016-10-30 23:36:02
【问题描述】:
简而言之,我想通过 Google API 上的服务帐户获取新的访问令牌。我使用了 OAuth 2.0 和 JWT 请求。我发现了很多类似的帖子,但没有一个回答我的问题。我所做的一切都符合Google OAuth 2.0 Server-to-Server request guide,但是当我发送 POST 请求时,我得到了“invalid_grant”的回报。任何想法为什么?这是我的代码:
$jwt_header_array = array( "alg" => "RS256",
"typ" => "JWT");
$jwt_claim_array = array( "iss" => "upload-file@feedking-1355.iam.gserviceaccount.com",
"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);
【问题讨论】:
-
从技术上讲,您需要对 JWT 元素进行 base64url 编码,而不仅仅是对它们进行 base64 编码
-
这些编码很好,因为我得到了正确的 JWT 标头并在 Google 的示例中声明,并使用来自该示例的相同输入。唯一的问题是签名,我无法验证,因为密钥与示例中使用的不同。
标签: php oauth-2.0 jwt google-api-php-client google-oauth