谷歌云存储与谷歌api客户端php和JSON凭据,但在一段时间后得到403错误


Google Cloud Storage with google-api-client-php and JSON credential but got 403 error after awhile

我正在通过带有JSON凭据的Google api客户端php SDK使用Google云存储服务,并应用示例代码,如:

putenv("GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Storage::DEVSTORAGE_FULL_CONTROL);
$storage = new Google_Service_Storage($client);
$ret = $storage->buckets->listBuckets("project-id");

然而,在我创建凭据的最初几个小时后,这些代码就可以了,但几小时后,我收到了相同代码/凭据文件的"拒绝权限"错误。

PHP Fatal error:  Uncaught exception 'Google_Service_Exception' with message '{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "forbidden",
    "message": "Forbidden"
   }
  ],
  "code": 403,
  "message": "Forbidden"
 }
}

我不知道这是代码级别还是服务级别的问题。。。

确保您的服务帐户在GCP:中具有正确的权限

在控制台中,转到:

Api Manager>凭据>管理服务帐户>权限>添加成员

在弹出屏幕上,粘贴您的服务帐户的电子邮件地址,并授予其"可以编辑"的访问权限。这样就可以了。