繁体   English   中英

Google Cloud Run:从 GCP 外部调用

[英]Google Cloud Run: Calling from outside 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 仅适用于应用引擎而不适用于云运行?

有没有人 go 对此有任何建议?

谢谢

好的,似乎有一个 IDTokenCredentials class 适用于此,因为它使用 Open ID Connect ID Tokens 而不是 OAuth 2.0 Access Tokens:

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。

如果您仍想获取您的ID 令牌而不使用 Dan 的响应中的方法,则有一个更新的代码:

import requests
import google.auth    
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)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
token = credentials.token
print('ID Token:', token)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM