使用服务帐户从python调用Google云函数进行身份验证

2024-05-23 13:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个触发器类型设置为HTTP的云函数,还有一个服务帐户,它拥有调用云函数的权限。我想从python脚本中调用cloud函数。我使用以下脚本调用函数:

from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp

credentials = service_account.Credentials.from_service_account_file('/path/to/service-account-credentials.json')

scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/cloud-platform'])

authed_http = AuthorizedHttp(scoped_credentials)

response = authed_http.request('GET', 'https://test-123456.cloudfunctions.net/my-cloud-function')

print(response.status)

我得到了未经授权的(401)错误响应。这是正确的调用方式吗


Tags: 函数fromhttpsimport脚本authhttpcloud
1条回答
网友
1楼 · 发布于 2024-05-23 13:36:50

为了能够调用您的云函数,您需要一个针对云函数端点的ID令牌

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession


url = 'https://test-123456.cloudfunctions.net/my-cloud-function'

creds = service_account.IDTokenCredentials.from_service_account_file(
       '/path/to/service-account-credentials.json', target_audience=url)

authed_session = AuthorizedSession(creds)

# make authenticated request and print the response, status_code
resp = authed_session.get(url)
print(resp.status_code)
print(resp.text)

相关问题 更多 >