如何正确授权对 Google Cloud Storage API 的请求?

zna*_*nat 5 google-cloud-storage google-cloud-iam

我正在尝试使用 Google Cloud Storage JSON API 通过 http 调用从存储桶中检索文件。

我在与存储桶位于同一项目中的 GCE 中的 Container 中卷曲,并且服务帐户具有对存储桶的读取访问权限

这是请求的模式:

https://storage.googleapis.com/{bucket}/{object}
Run Code Online (Sandbox Code Playgroud)

根据 API 控制台,我不需要任何特别的东西,因为服务帐户提供了应用程序默认凭据。但是,我一直有这个:

Anonymous caller does not have storage.objects.get
Run Code Online (Sandbox Code Playgroud)

我还尝试为项目创建一个 API 密钥并将其附加到 url ( https://storage.googleapis.com/{bucket}/{object}?key={key}) 但我仍然遇到相同的 401 错误。

如何授权查询此 API 的请求?

Joh*_*ley 4

您使用的 URL 不正确。API 使用以 开头的 URL https://www.googleapis.com/storage/v1/b

不建议使用 API 密钥。相反,您应该使用Bearer: token. 我将展示这两种方法。

要获取 gcloud 默认配置的访问令牌:

gcloud auth print-access-token

然后在您的请求中使用该令牌curl。将 TOKEN 替换为 gcloud 命令中的令牌。

列出存储桶:

curl -s -H "Authorization: Bearer TOKEN" https://www.googleapis.com/storage/v1/b

curl https://www.googleapis.com/storage/v1/b?key=APIKEY
Run Code Online (Sandbox Code Playgroud)

列出对象:

curl -s -H "Authorization: Bearer TOKEN" https://www.googleapis.com/storage/v1/b/examplebucket/o

curl https://www.googleapis.com/storage/v1/b/examplebucket/o?key=APIKEY
Run Code Online (Sandbox Code Playgroud)

API 参考:列出存储桶