【问题标题】:Obtain a service account credentials within a Cloud Functions to call a google service outside GCP在 Cloud Functions 中获取服务帐户凭据以在 GCP 之外调用 google 服务
【发布时间】:2020-10-21 06:18:40
【问题描述】:

我的场景:我需要使用服务帐户从云函数中使用 google-api-python-client 调用 Google DBM API。

更新

这里是我尝试运行的示例代码:

import google.auth
from googleapiclient.discovery import build
from google.auth.transport import requests

API_NAME = 'doubleclickbidmanager'
API_VERSION = 'v1.1'
SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']

credentials, project_id = google.auth.default(scopes=SCOPES)

print(credentials.service_account_email)
# prints "default"

credentials.refresh(requests.Request())
print(credentials.service_account_email)
# prints "[service-account]@[project].iam.gserviceaccount.com"

service = build(API_NAME, API_VERSION, credentials=credentials)
service.queries().listqueries().execute()
# local: return the queries
# in CF: Encountered 403 Forbidden with reason "insufficientPermissions"

当我在本地运行时,设置环境变量GOOGLE_APPLICATION_CREDENTIALS=keyfile.json 工作正常。

但是在 Cloud Function 中运行时出现 403 错误。

keyfile.json 使用云函数中设置的相同服务帐户[service-account]@[project].iam.gserviceaccount.com

【问题讨论】:

  • But the emails in the returned credentials was default 是什么意思?您能否解释并显示日志跟踪以及如何打印此日志?
  • 我的意思是 credential.service_account_email=default 不是服务帐户电子邮件。我想这个属性应该等于 FUNCTION_IDENTITY 环境变量

标签: python google-cloud-platform google-cloud-functions google-api-python-client


【解决方案1】:

您必须强制库生成令牌以强制它完成所有字段。为此,只需调用一次重试,就像这样

import google.auth
credentials, project_id = google.auth.default(scopes=SCOPES)

from google.auth.transport import requests
credentials.refresh(requests.Request())
print(credentials._service_account_email)

build(API_NAME, API_VERSION, credentials=credentials)

【讨论】:

  • 在本地使用 credentials.refresh 运行并将 GOOGLE_APPLICATION_CREDENTIALS 设置为密钥文件可以正常工作。但是在 Cloud Functions 中运行时,API 调用出现 403 错误。
  • 您是否收到了正确的服务帐户电子邮件?如果是这样,剩下的代码是什么。您要调用哪个 API?
  • 我检查了服务帐户电子邮件,在 keyfile.json 和 Cloud Function 中是相同的。我用示例代码更新了问题。
  • 很遗憾,我没有 DBM 帐户。我尝试过这个。我激活 API。我得到了 403 但这是正常的,我没有帐户,而且我未经授权。我猜是您的 DBM 配置中的问题,而不是您的代码中的问题。您是否对 DBM 进行了 IP 检查或其他可能不同于您的本地来源和 Cloud Function 来源的东西?
  • 非常感谢,这应该在 GCP 中明确记录
猜你喜欢
  • 2020-05-18
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2023-01-31
  • 2014-09-24
  • 1970-01-01
  • 2015-04-29
相关资源
最近更新 更多