Google Cloud 如何使用 php 通过服务帐户获取 ID 令牌

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

我创建了一个服务帐户,为其创建了密钥并存储为 JSON 文件(其中包括

roles/cloudfunctions.invoker
角色),保存在本地。 并有一些代码尝试调用 GCP 上的 Cloud Functions。

我成功测试通过

curl

在本地调用我的函数
curl -X POST  -H "Authorization: bearer $(gcloud auth print-identity-token)" -H "Content-Type:application/json" -d '{"data" : {"id" : "121123"}}' "https://asia-northeast1-my-project-name.cloudfunctions.net/MyFunction"

现在我想在本地服务器上调用此函数,但不想安装具有“gcloud”命令的Cloud SDK(因为gcloud auth需要通过浏览器进行身份验证)。我将上面的 JSON 文件复制到该服务器本地,并尝试使用 Google APIs Client Library for PHP 生成 ID 令牌,该令牌相当于命令

gcloud auth print-identity-token
。我还参考了这个答案

require __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig('/path/to/json/file.json');
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$client->fetchAccessTokenWithAssertion();
$access_token = $client->getAccessToken();
var_dump($access_token);

如果我在这里有一个有效的令牌,我可以调用我的云函数,但是当 var_dump 这个 $access_token 时,它打印出一个奇怪的字符串(末尾有很多“点”) - 看起来像这样:

ab29.c.Kp4BDgaiwej12ckskW0waSinDiMRcayZoBm5tp1lvc2813uEZjraVbU-4hKXxG2euqNS9wxRUa1aEKOH7n5w_VAhIUW9821Cy7Ca0c7_sXVDr_Nwouj8sVZR6gnjUFx51n8azUTX-RFMJBGE4_MrPT3hIMYYeBlIxy_IEUHF932xKPWR0ulf-wOa0o...............................................................................................................................................................................................................................................................................................................................................................................................

这个access_token当然不能用。

我上面的步骤有什么问题吗?如果这种方式无法完成,您能否建议一种允许我在本地服务器上调用云函数的方法?

php google-cloud-functions google-authentication
1个回答
0
投票

我能够使其与最新版本的 API 客户端一起使用,代码如下:

$client = new Google\Client();
$client->setAuthConfig('/path/to/private-key.json');
$client->useApplicationDefaultCredentials();
$client->setScopes($scope);
$client->setApplicationName($appName);
$access_token = $client->fetchAccessTokenWithAssertion();
$bearerToken = $access_token['id_token'];

// Now you can authenticate API calls by adding the Authorization header:
// "Authorization: Bearer $bearerToken"

请务必设置私钥 JSON 文件的正确路径,并根据需要替换范围和应用程序名称。

对于使用 Google 客户端 API:

composer require google/apiclient:^2.15.0

参考:https://github.com/googleapis/google-api-php-client

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