簡而言之,我想要在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的示例中聲明瞭相同的輸入。唯一的問題是簽名,我無法驗證,因爲密鑰與示例中使用的不同。 –