我正在爲存儲API創建API請求(GET存儲桶),並且其中一個必需參數是「授權」標頭。使用服務帳戶爲Google Cloud Storage REST API請求OAuth2訪問令牌時發生invalid_grant錯誤
請注意,我用的是服務帳戶訪問API。
我跟着文檔https://developers.google.com/accounts/docs/OAuth2ServiceAccount獲得的「授權」標頭的訪問令牌,這樣我就可以發送授權的請求給他們的REST API。問題是我總是得到「invalid_grant」錯誤。
使用此代碼檢查出來:
<?php
error_reporting(E_ERROR);
const CLIENT_ID = 'XXXXXXXXXXXX.apps.googleusercontent.com';
const SERVICE_ACCOUNT = '[email protected]';
const KEY_FILE = 'XXX.p12';
function get_oauth_access_token()
{
$header[alg] = 'RS256';
$header[typ] = 'JWT';
$header = urlencode(base64_encode(utf8_encode(json_encode($header))));
$assertion_time = time();
$claim[iss] = CLIENT_ID; //also tried SERVICE_ACCOUNT here, no improvement
$claim[scope] = 'https://www.googleapis.com/auth/devstorage.read_only';
$claim[aud] = 'https://accounts.google.com/o/oauth2/token';
$claim[exp] = $assertion_time + 3600;
$claim[iat] = $assertion_time;
$claim = urlencode(base64_encode(utf8_encode(json_encode($claim))));
$data = $header . '.' . $claim;
$p12 = file_get_contents(KEY_FILE);
$cert = array();
openssl_pkcs12_read($p12, $cert, 'notasecret');
$priv_key_id = openssl_get_privatekey($cert[pkey]);
openssl_sign($data, $signature, $priv_key_id, 'sha256');
$signature = urlencode(base64_encode($signature));
$assertion = $data . '.' . $signature;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('grant_type'=>'assertion',
'assertion_type'=>'http://oauth.net/grant_type/jwt/1.0/bearer',
'assertion'=>$assertion));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
var_dump($result);
var_dump($error);
}
get_oauth_access_token();
有什麼不對這段代碼中導致「invalid_grant」的錯誤?
不,這是行不通的,因爲我已經在這裏說: https://groups.google.com/forum/?fromgroups#!topic/gs-discussion/3y_2XVE2q7U 你建議的代碼可能只是一個解決方法,並增加了膨脹,這需要SDK才能獲得訪問令牌。 –