【发布时间】:2021-10-06 06:20:08
【问题描述】:
我在 Google Cloud Function 中有一个简单的 node.js 函数(从我的网站代码内部调用),我之前使用了我在 Google Cloud SDK 中连接并使用它时获得的 id_token:gcloud auth print-identity-token ,但它只持续了 60 分钟,所以在那之后我的应用程序就不能再使用谷歌云功能了。
所以我尝试在服务帐户密钥的帮助下生成自己的令牌:https://cloud.google.com/docs/authentication/production#create_service_account
但是当我使用“授权:承载令牌”标头调用我的链接时,我总是得到一个“401 未授权”
可能是因为我不知道在“aud”值(在有效负载数组内)中放入什么
<?php
namespace MyProject\Parser;
use Firebase\JWT\JWT;
use GuzzleHttp\Client;
abstract class GoogleCloudParser extends AbstractParser
{
/**
* Returns the HTML for the given URL
* @param string $url
* @return string
* @throws \GuzzleHttp\Exception\GuzzleException
*/
protected function getHTML(string $url): string
{
$cloudFunctionURL = "https://region-project-name.cloudfunctions.net/function-name";
$token = $this->getToken();
$guzzle = new Client();
$response = $guzzle->get($cloudFunctionURL, [
'query' => ['url' => $url],
'headers' => [
'Authorization' => "Bearer " . $token
]
]);
return $response->getBody()->getContents();
}
/**
* Returns the authentification token for google cloud
* @return string
*/
protected function getToken()
{
$privateKey = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n";
$publicKey = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n";
$payload = [
'iss' => 'App-Engine-default-service-account@appspot.gserviceaccount.com',
'sub' => 'App-Engine-default-service-account@appspot.gserviceaccount.com',
'aud' => 'bucket-name',
'iat' => time(),
'exp' => (time() + 3600)
];
$header = [
"alg" => "RS256",
"typ" => "JWT",
"kid" => "private_key_id_of_app_engine_default_service-account"
];
$token = JWT::encode($payload, $privateKey, $header["alg"], $header["kid"]);
return $token;
}
}
我尝试了多种方法来添加“aud”,但我不知道该使用什么...我尝试使用我得到的存储桶名称:https://github.com/GoogleCloudPlatform/php-docs-samples/blob/78356e87cc54c1d46df52c0d2f47320329957ce5/auth/src/auth_api_explicit.php
使用 cmd 行:php src/auth_api_explicit.php myGoogleProjectID gcloud-service-account-file.json
我尝试使用“https://cloudfunctions.googleapis.com/”...
我尝试将我的函数名称的完整链接放在谷歌云函数中。
我认为我已经在 IAM 和 Google Cloud 平台内为我的服务帐户设置了所有内容。
请问有什么帮助吗?
【问题讨论】:
标签: php firebase google-cloud-functions jwt guzzle