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

Firebase认证调用Cloud Functions失败:请求未通过身份验证

解决React调用Firebase Auth保护的Gen2 Cloud Function认证问题

1. 确认Cloud Run服务的权限配置

Gen2 Cloud Function部署在Cloud Run上,因此Cloud Run服务本身的权限才是控制访问的核心,而非仅Cloud Function的权限:

  • 进入Cloud Run控制台,找到对应服务的「权限」页面
  • 确保allAuthenticatedUsers主体已被分配Cloud Run Invoker角色(而非Cloud Functions Invoker)
  • 若未添加,点击「添加权限」,输入allAuthenticatedUsers,选择角色「Cloud Run > Cloud Run Invoker」并保存

2. 修正ID Token的传递方式

Firebase的httpsCallable方法对Gen2函数可能无法自动处理认证头,建议改用直接fetch请求传递ID Token:

const callCloudFunction = async () => {
  try {
    if (!auth.currentUser) {
      throw new Error("用户未认证");
    }
    // 获取Firebase ID Token
    const token = await auth.currentUser.getIdToken();
    // 使用Cloud Function的代理URL或直接Cloud Run服务URL
    const url = "https://YOUR_REGION-YOUR_PROJECT_ID.cloudfunctions.net/hello_world";
    // 或Cloud Run直接URL:"https://hello-world-xxxxxx-uc.a.run.app"
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`
      },
      body: JSON.stringify({ /* 传递给函数的参数 */ })
    });

    if (!response.ok) {
      throw new Error(`请求失败:${response.statusText}`);
    }

    const data = await response.json();
    console.log(data);
    setResult(data);
  } catch (error) {
    console.error("调用云函数出错:", error);
    setError(error.message || error.toString());
  }
};

3. 验证Firebase Functions初始化配置

确保Firebase应用和Functions实例初始化时指定了正确的区域(需与Cloud Function部署的区域一致):

import { initializeApp } from "firebase/app";
import { getFunctions } from "firebase/functions";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  // 其他配置项
};

const app = initializeApp(firebaseConfig);
// 指定函数部署的区域,例如"us-central1"
const functions = getFunctions(app, "YOUR_REGION");

4. 检查ID Token的有效性

使用Google的Token Info端点验证获取的ID Token是否有效:

curl "https://oauth2.googleapis.com/tokeninfo?id_token=YOUR_TOKEN"

确保返回结果中:

  • aud字段匹配你的Firebase项目ID
  • exp字段未过期(当前时间小于该值)
  • iss字段为https://securetoken.google.com/YOUR_PROJECT_ID

5. 查看Cloud Run日志获取详细错误

进入Cloud Run控制台的「日志」页面,查看具体的认证错误信息:

  • 若提示The caller does not have permission:检查Cloud Run的权限配置是否正确
  • 若提示Invalid token:确认ID Token的获取和传递过程无误
  • 若提示Token expired:确保每次调用前重新获取ID Token(而非缓存旧令牌)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:06:05