在尝试编写 python 脚本以使用基于服务的授权访问 GCS 时,我想出了以下内容。请注意,'key' 是我的 p12 文件的内容。
我正在尝试仅读取我帐户中的存储桶列表。我已经使用 GCS 的 Web 界面成功创建了一个存储桶,并且可以使用 gsutil 看到它。
当我执行下面的代码时,出现 403 错误。起初我以为我没有被正确授权,但我从这个非常有用的网页(使用基于网络的授权)进行了尝试,并且它可以正常工作。 https://developers.google.com/apis-explorer/#p/storage/v1beta1/storage.buckets.list?projectId= &_h=2&
当我查看标题和查询字符串并将它们与网站生成的请求的 keaders 和查询进行比较时,我看到没有授权标题,并且查询字符串中没有 key= 标记。我想我认为凭证授权会为我解决这个问题。
我究竟做错了什么?
代码:
credentials = SignedJwtAssertionCredentials(
'xxx-my-long-email-from-the-console@developer.gserviceaccount.com',
key,
scope='https://www.googleapis.com/auth/devstorage.full_control')
http = httplib2.Http()
http = credentials.authorize(http)
service = build("storage", "v1beta1", http=http)
# Build the request
request = service.buckets().list(projectId="159910083329")
# Diagnostic
pprint.pprint(request.headers)
pprint.pprint(request.to_json())
# Do it!
response = request.execute()
当我尝试执行时,我得到了 403。
最佳答案
我得到了这个工作,但是,我使用的代码与您发布的代码段没有根本的不同。以防万一您想将我的版本与您的版本进行比较,下面附上了一个对我有用的 Python 程序的完整副本。我最初得到 403,就像你一样,这是由于继承了你的项目 ID :)。更新该值以使用我的项目 ID 后,我得到了正确的存储桶列表。要检查的两件事:
#!/usr/bin/env python
import pprint
import oauth2client
from oauth2client.client import SignedJwtAssertionCredentials
import httplib2
from apiclient.discovery import build
f = open('key.p12', 'r')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
'REDACTED',
key,
scope='https://www.googleapis.com/auth/devstorage.full_control')
http = httplib2.Http()
http = credentials.authorize(http)
service = build("storage", "v1beta1", http=http)
# Build the request
request = service.buckets().list(projectId="REDACTED")
# Diagnostic
pprint.pprint(request.headers)
pprint.pprint(request.to_json())
# Do it!
response = request.execute()
pprint.pprint(response)
关于authorization - 无法获得服务帐户授权以使用 Python 客户端库 API 处理 GCS 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13694811/