使用访问令牌签名Google Cloud Storage Blob

时间:2019-06-28 05:20:40

标签: google-cloud-platform google-api google-cloud-storage google-oauth

目标:使用OAuth2.0访问令牌生成签名URL

我找到的用于签名Google Cloud Storage Blob的示例和源代码都需要服务帐户凭据文件(特定于私钥)。例如:

https://cloud.google.com/storage/docs/access-control/signing-urls-with-helpers#storage-signed-url-get-object-python

但是,由于遵循the authorization flow discussed here,因此我只有OAuth2.0访问令牌(并且我没有访问GCS存储桶/对象的凭据文件和服务帐户的私钥)。因此,我想知道如何使用OAuth2.0访问令牌对Blob进行签名。

使用的代码:

我使用以下命令对blob进行签名:

@ViewChild('child1') child1: Child1;
@ViewChild('child2') child2: Child2; 
//.... so on

收到错误消息:


# 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)

1 个答案:

答案 0 :(得分:0)

如果您不想使用API​​密钥,则follow procedure described in this sample使用iamcredentials.signBlob() API远程签署URL的服务帐户无需分发API密钥。

(必须签名的)签名字符串具有以下格式:

signature_string = ('{verb}\n'
                    '{content_md5}\n'
                    '{content_type}\n'
                    '{expiration}\n'
                    '{resource}')