python - 使用服务帐户从 python 调用 Google Cloud Function 进行身份验证
问题描述
我有一个触发器类型设置为 HTTP 的云功能,还有一个有权调用云功能的服务帐户。我想从 python 脚本调用云函数。我正在使用以下脚本来调用该函数:
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)
我收到 Unauthorized ( 401 ) 错误作为响应。这是正确的调用方式吗?
解决方案
为了能够调用您的云函数,您需要一个针对云函数端点的 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)
推荐阅读
- reactjs - 我们如何覆盖子组件的 DOM 属性,例如:tabIndex
- python - 如何从文本文件的中间反向迭代?
- shell - 命令在 bash 中工作,但不在 Makefile 中
- python - Django REST Framework 返回 403 而不是 405
- winapi - 如果异步完成,ReadFile() 是否总是返回 FALSE?
- python - 如何创建仅填充对角线的嵌套列表(矩阵)?
- android - 导航到同一目的地但从android中的不同起点时如何使用不同的参数
- pandas - 即使索引值恰好一致,也可以跨 pandas MultiIndex 级别广播
- javascript - 如何在事件侦听器定义的事件上运行不带参数的函数
- html - 为什么我的导航切换按钮不起作用?