【发布时间】:2019-11-10 01:55:41
【问题描述】:
目标:使用 OAuth2.0 访问令牌生成签名 URL
我找到的用于签署 Google Cloud Storage Blob 的示例和源代码都需要服务帐户凭据文件(具体来说是私钥)。例如:
但是,由于我关注the authorization flow discussed here,因此我只有 OAuth2.0 访问令牌(并且我没有有权访问 GCS 存储桶/对象的服务帐户的凭据文件和私钥)。因此,我想知道如何使用 OAuth2.0 访问令牌对 blob 进行签名。
使用的代码:
我使用以下方式对 blob 进行签名:
# First, get access token:
service_account = "<email address of a service account>"
access_token = build(
serviceName='iamcredentials',
version='v1',
http=http
).projects().serviceAccounts().generateAccessToken(
name="projects/{}/serviceAccounts/{}".format(
"-",
service_account),
body=body
).execute()["accessToken"]
credentials = AccessTokenCredentials(access_token, "MyAgent/1.0", None)
# Second, use the access token to sign a blob
url = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{}:signBlob".format(service_account)
encoded = base64.b64encode(blob)
sign_blob_request_body = {"payload": encoded}
response = requests.post(url,
data=json.dumps(sign_blob_request_body),
headers={
'Content-Type': 'application/json',
'Authorization': 'Bearer {}'.format(credentials.access_token)})
signature = response.json()["signedBlob"]
# Third, use the signature to create signed URL:
encoded_signature = base64.b64encode(signature)
signed_url = "https://storage.googleapis.com/<BUCKET>/<OBJECT>?" \
"GoogleAccessId={}&" \
"Expires={}&" \
"Signature={}".format(service_account,
expiration,
encoded_signature)
收到的错误信息:
<Error>
<Code>SignatureDoesNotMatch</Code>
<Message>
The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.
</Message>
<StringToSign>GET 1561832204 /<BUCKET>/<OBJECT></StringToSign>
</Error>
【问题讨论】:
-
也可以考虑使用blob.generate_signed_url,here you have example code how to sign url
-
如何使用访问令牌运行该方法?你有一个工作的例子吗?具体来说,如何构造带有访问令牌的客户端?
-
使用 blob.generate_signed_url 您不需要访问令牌。要使用访问令牌而不使用 API 密钥,请检查更新的答案。
标签: google-cloud-platform google-api google-cloud-storage google-oauth