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

无法将Firebase Cloud Function设为公开的权限问题求助

Firebase Cloud Function 401权限问题解决思路

问题概况

创建的Firebase Cloud Function发起请求时一直返回401错误,提示:

The request was not authorized to invoke this service

尝试两种公开函数的操作均失败:

  • 直接在Cloud Run添加allUsers为主体并授予cloud run invoker权限,触发预条件错误
  • 通过函数详情页的Cloud Run链接开启未认证调用,触发组织策略报错:

The 'Domain Restricted Sharing' organization policy (constraints/iam.allowedPolicyMemberDomains) is enforced. Only principals in allowed domains can be added as principals in the policy. Correct the principal emails and try again

当前使用管理员账号,但无IAM或组织策略修改权限。

核心原因

你的谷歌云组织启用了constraints/iam.allowedPolicyMemberDomains策略,限制仅允许特定域名内的主体被添加到IAM权限中,因此无法直接添加allUsers这类公开主体。

可行解决方案

1. 使用服务账号签名JWT调用函数

  • 创建一个新的服务账号,为其授予目标Cloud Run服务的Cloud Run Invoker权限
  • 下载该服务账号的密钥文件,使用google-auth-library库生成JWT令牌
  • 调用函数时,在请求头中添加Authorization: Bearer <生成的JWT>

2. 限定特定域名用户访问

如果组织策略允许你的公司域名,可添加该域名下的所有用户作为主体:

  • 在Cloud Run权限设置中,添加主体user:*@your-company-domain.com
  • 授予其Cloud Run Invoker权限,该域名内的用户即可通过谷歌账号认证访问函数

3. 通过Firebase Auth验证访问

在函数中加入Firebase Auth令牌验证逻辑,仅允许已认证用户访问:

const admin = require('firebase-admin');
admin.initializeApp();

exports.yourFunctionName = async (req, res) => {
  // 从请求头获取身份令牌
  const idToken = req.headers.authorization?.split('Bearer ')[1];
  if (!idToken) {
    return res.status(401).send('缺少身份令牌');
  }

  try {
    // 验证令牌有效性
    const decodedToken = await admin.auth().verifyIdToken(idToken);
    // 执行你的业务逻辑
    res.status(200).json({ message: '请求成功', user: decodedToken.uid });
  } catch (error) {
    res.status(401).send('无效的身份令牌');
  }
};

前端调用时,先通过Firebase Auth获取用户的idToken,再将其放入请求头的Authorization字段中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:13:21