You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于用户Google身份的OAuth令牌调用Google Cloud Run Function

通过用户Google身份的OAuth令牌调用Cloud Run Function HTTP端点

已成功的调用方式

我已部署Cloud Run Function,使用gcloud CLI生成的身份令牌可以成功调用其HTTP端点:

curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" <你的Cloud Run Function URL>

尝试的Python实现及错误

我希望通过用户已登录的Google身份获取OAuth令牌,避免在用户设备上存放服务账号密钥,但调用返回401错误。Python代码如下:

flow = InstalledAppFlow.from_client_secrets_file(
    oauth_authorization_request_definition_file, ['openid'])
authorization_credentials = flow.run_local_server()

auth_token = authorization_credentials.id_token

headers = {
    "Authorization": f"Bearer {auth_token}",
    "Content-Type": "application/json"
}

response = requests.put(url, headers=headers)

错误提示:

Your client does not have permission to the requested URL

我已经通过gcloud CLI为用户授予了roles/run.invoker角色,但相关文档和控制台说明较为混乱。

问题定位

gcloud CLI获取的令牌中的**受众(audience)**与Python代码获取的令牌中的受众值不同。尝试在flow.run_local_server()中添加token_audience参数并填入gcloud获取的受众值时,出现以下错误:

oauthlib.oauth2.rfc6749.errors.CustomOAuth2Error: (invalid_audience) The audience client and the client need to be in the same project.

注:gcloud config显示的项目ID与Python代码中OAuth客户端所属项目ID一致。

附:Google Cloud Run Functions正从原Cloud Functions整合至Cloud Run,相关文档较多。

内容的提问来源于stack exchange,提问作者matanox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 08:52:15