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

React应用经GCP IAM认证后无法访问Cloud Run后端API问题

问题描述

我有一个通过Google IAM认证的React应用,无法使用认证生成的令牌访问GCP Cloud Run上的后端REST API,但使用gcloud auth print-identity-token手动生成的令牌可以正常访问。按理论,GCP认证生成的令牌应该能连接Cloud Run后端API。

相关代码片段

import { useGoogleLogin } from '@react-oauth/google';
const handleGoogleLogin = useGoogleLogin({ scope: google.scope,....})

认证响应内容

access_token: "ya29.a0AeTM1ieQABEf023ELeFTMXNyG322M_m5oKheJrCRkmms92ilXeITOiFp1hSV7Cz0Fsb1pMvdnSdzooq5Ls1fr2MCWUN6rLNN3YQj masked"
authuser: "1"
expires_in: 3598
hd: "company.com"
prompt: "none"
scope: "email profile https://www.googleapis.com/auth/cloud-identity.devices.lookup https://www.googleapis.com/auth/cloud-identity.groups https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-identity.groups.readonly openid"
token_type: "Bearer"
解决方案
  • 令牌类型不匹配:你当前获取的是OAuth 2.0的access_token,但Cloud Run要求的是ID令牌(ID Token),gcloud auth print-identity-token生成的正是ID令牌,而@react-oauth/google默认返回access_token。
  • 调整认证请求配置:在useGoogleLogin中添加response_type: 'id_token'参数,同时指定client_id和nonce(安全要求),确保scope包含openid(你的响应里已满足)。示例代码:
import { useGoogleLogin } from '@react-oauth/google';
const handleGoogleLogin = useGoogleLogin({
  scope: google.scope,
  response_type: 'id_token',
  client_id: '你的GCP OAuth客户端ID',
  nonce: '随机生成的安全字符串', // 防止重放攻击,建议每次请求生成不同值
  onSuccess: (response) => {
    const idToken = response.id_token;
    // 使用此id_token请求Cloud Run API
  }
});
  • 验证令牌受众:Cloud Run要求ID令牌的aud(受众)字段必须匹配你的服务URL。可以通过本地解码令牌(避免使用在线工具)检查aud值是否为你的Cloud Run服务地址。
  • 确认用户权限:确保通过Google登录的用户在Cloud Run服务的IAM配置中拥有roles/run.invoker角色,手动令牌能访问说明权限基础没问题,但需确认登录账号与gcloud使用的账号权限一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:35:16