首页 > 解决方案 > 如何使用 GOOGLE_APPLICATION_CREDENTIALS 环境变量来签署 Cloud Storage URL?

问题描述

如何使用提供给 Cloud Function的隐式GOOGLE_APPLICATION_CREDENTIALS环境变量来签署 Cloud Storage URL?

GOOGLE_APPLICATION_CREDENTIALS环境变量存在时,以下内容在本地工作,但KeyError在云函数内部运行时失败。

google_credentials = service_account.Credentials.from_service_account_file(
    os.environ['GOOGLE_APPLICATION_CREDENTIALS']
)
client_email = google_credentials.service_account_email
credential_scope = '{}/auto/storage/goog4_request'.format(datestamp)
credential = '{}/{}'.format(client_email, credential_scope)
# ...
signature = binascii.hexlify(
    google_credentials.signer.sign(string_to_sign)
).decode()

有问题的云功能将部署在多个环境中,因此我想避免必须实际部署凭据文件——这确实有效。

如果它是相关的,我正在使用 Python 3.7 并且我的解决方案基于这个例子。

标签: python-3.xgoogle-cloud-storagegoogle-cloud-functions

解决方案


部署函数时,应该不需要 GOOGLE_APPLICATION_CREDENTIALS。请查看此 [1] 以了解如何处理经过身份验证的请求。

正如您从 [2] 中看到的,云存储客户端库可能需要 IAM (iam.googleapis.com) API 和 iam.serviceAccounts.signBlob 权限。尽管 Cloud Functions 具有“默认应用程序凭据”,但它(通常)不包括 iam.serviceAccounts.signBlob 权限。

正如您在文档中看到的那样,您还需要确保您的服务帐户具有适当的角色。您还可以选择您的函数将使用哪个服务帐户来运行。

请让我知道此信息是否有助于解决您的问题。


[1] https://cloud.google.com/functions/docs/writing/http#authentication_and_cors
[2] https://cloud.google.com/functions/docs/writing/http#uploading_files_via_cloud_storage


推荐阅读