首页 > 解决方案 > 在 Cloud Functions 中获取服务帐户凭据以在 GCP 之外调用 google 服务

问题描述

我的场景:我需要google-api-python-client使用服务帐户从 Cloud Function 调用 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 错误。

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

标签: pythongoogle-cloud-platformgoogle-cloud-functionsgoogle-api-python-client

解决方案


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

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)

推荐阅读