使用服务帐户请求Google Cloud Storage REST API的OAuth2访问令牌时出现invalid_grant错误

问题描述 投票:1回答:4

我正在为存储API创建API请求(GET存储桶),其中一个必需参数是“授权”标头。

请注意,我使用服务帐户访问API。

我按照文档https://developers.google.com/accounts/docs/OAuth2ServiceAccount获取“Authorization”标头的访问令牌,以便我可以向其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”错误?

php rest google-api google-cloud-storage
4个回答
2
投票

您的问题可能是服务器的时间。

我遇到了谷歌分析的问题:我的所有代码都是正确的,但与谷歌的时间相比,我的服务器的时间在未来几秒钟。您可以将服务器的时间延迟几分钟来进行测试。

如果它工作,您可以使用NTP,例如,以保持服务器时钟正确。


0
投票

这是一个简单的PHP程序,用于说明如何在Google Cloud Storage RESTful HTTP界面中使用服务帐户。我用服务帐户测试了这段代码,似乎工作正常。如果您有任何其他问题,请与我们联系。

<?php

require_once 'apiClient.php';

// Define constants.
const CLIENT_ID = 'YOUR_CLIENT_ID_GOES_HERE';
const SERVICE_ACCOUNT_NAME = 'YOUR_SERVICE_ACCOUNT_NAME_GOES_HERE';
const KEY_FILE = 'key.p12';
const BUCKET = 'marc-us';

// Obtain OAuth 2.0 access token for service account.
$client = new apiClient();
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new apiAssertionCredentials(
  SERVICE_ACCOUNT_NAME,
  array('https://www.googleapis.com/auth/devstorage.full_control'),
  $key)
);
$client::$auth->refreshTokenWithAssertion();
$json = $client->getAccessToken();
$accessToken = json_decode($json)->access_token;

// Add access token to Authorization header of HTTP request.
$ch = curl_init('http://commondatastorage.googleapis.com/' . BUCKET);
curl_setopt($ch, CURLOPT_HTTPHEADER, 
            array('Authorization: OAuth ' . $accessToken));
$resp = curl_exec($ch);
curl_close($ch);

// Display results.
print '<h2>Response:</h2><pre>' . $resp . '</pre>';
?>

0
投票

我上次回复中的代码对我来说很好,所以我怀疑你面临环境问题。无论如何,我咨询了谷歌PHP客户端库的所有者,他提供了一种更好的方法来刷新访问令牌,而无需调用内部的refreshTokenWithAssertion()方法。他提出了这种技巧:

  $req = new apiHttpRequest(YOUR_URL);
  $val = $client->getIo()->authenticatedRequest($req);

对authenticatedRequest()的调用负责根据需要刷新访问令牌(如果设置了断言凭证)。我修改了上面的代码以使用这种方法,它对我来说很好。请注意,旧版本和新版本都适用于我,所以没有功能差异,但我认为新版本更好,因为它避免了内部调用,使用Google PHP客户端lib而不是curl来执行请求,结果更短,更简单的代码。

<?php

require_once 'apiClient.php';

// Define constants.
const SERVICE_ACCOUNT_NAME = 'YOUR_SERVICE_ACCOUNT_NAME';
const KEY_FILE = 'key.p12';
const BUCKET = 'marc-us';

// Obtain service account credentials assertion.
$client = new apiClient();
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new apiAssertionCredentials(
  SERVICE_ACCOUNT_NAME,
  array('https://www.googleapis.com/auth/devstorage.full_control'),
  $key)
);

// Create HTTP request, authorize and execute.
$req = new apiHttpRequest('http://commondatastorage.googleapis.com/' . BUCKET);
$resp = $client::getIo()->authenticatedRequest($req);

// Display results.
print '<h2>Response:</h2>' . $resp->getResponseBody();

?>

0
投票

我有同样的错误,但使用Java。我的问题是exp和iat的时间以秒为单位,GMT-5和API google Auth是格林尼治标准时间。然后我将时间改为GMT值,一切正常。

© www.soinside.com 2019 - 2024. All rights reserved.