python - Google Cloud Run:从 GCP 外部调用
问题描述
我正在尝试访问安全的云运行服务。如果我从我的机器上尝试使用 SDK,它可以正常工作:
curl --header "Authorization: Bearer $(gcloud auth print-identity-token)"
但是,我无法使用 Python API 使用相同的服务帐户使其工作,我尝试使用 google-auth 获取访问令牌,但这给了我 401 身份验证错误。这是我用来尝试获取令牌的代码:
import google.auth
import google.auth.transport.requests
scopes = ['https://www.googleapis.com/auth/cloud-platform']
creds, projects = google.auth.default(scopes=scopes)
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)
# then using creds.token
查看文档:https ://cloud.google.com/run/docs/authenticating/service-to-service#calling_from_outside_gcp它说要遵循此处的示例代码:https ://cloud.google.com/iap/docs /authentication-howto#iap_make_request-python我似乎无法按照指南所说的启用 IAP 但似乎 IAP 仅适用于应用程序引擎而不适用于云运行?
有没有人对这个有任何建议?
谢谢
解决方案
好的,似乎有一个 IDTokenCredentials 类适用于此,因为它使用 Open ID Connect ID 令牌而不是 OAuth 2.0 访问令牌:
https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
service_url = 'example.com'
key_file = 'key.json'
credentials = service_account.IDTokenCredentials.from_service_account_file(
key_file, target_audience=service_url)
authed_session = AuthorizedSession(credentials)
response = authed_session.get(service_url)
这很令人困惑,因为我在文档中没有看到它,这让我想到了关于 IAP 的其他内容,我认为这些内容与 Cloud Run 无关。
推荐阅读
- c - 使用 O_CREAT O_WRONLY :如何获取文件中的当前位置并在末尾附加数据?
- javascript - 如何在使用react的useeffect返回语句中使用react.usecallback?
- c# - 如何在 C# 中使用 restapi 从 github 为用户(人)获取数据?
- java - 如何根据页眉/页脚高度动态调整页边距
- r - 在闪亮的应用程序中显示变量的摘要(summary())
- android - 如何仅在 Ubuntu 上安装 Android Studio 命令行工具
- hyperlink - Select2 - 带有外部链接的选项项目中的自定义输入字段
- nativescript - NativeScript Preview 生成 QR 码,但未在应用程序内部加载
- crystal-reports - 更改名称后如何在水晶报表中打破页面?
- python-3.x - 将数据帧合并为一个