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

使用Cloud Functions在Firebase Storage创建文档遇未认证错误求助

问题分析与解决方案

出现FirebaseError: unauthenticated错误,核心原因是部署后的HTTP云函数默认需要认证才能调用,和你设置的Storage安全规则无关,以下是具体修复步骤:


1. 配置云函数的IAM调用权限

Firebase部署的on_request类型HTTP函数,默认仅允许项目所有者调用。需要给认证用户开放调用权限:

  • 打开Firebase控制台 → 云函数 → 找到upload_html_page函数
  • 进入「权限」标签页,点击「添加成员」
  • 在成员栏输入allAuthenticatedUsers,角色选择「Cloud Functions Invoker」,保存配置

2. 确认前端调用时用户已完成认证

虽然你提到应用已连接Firebase账号,但需确保调用云函数时用户处于已登录状态。可以在调用前增加状态校验:

import { getAuth, onAuthStateChanged } from "firebase/auth";
import { getApp } from './get-app';
import { getFunctions, httpsCallable } from 'firebase/functions';

const auth = getAuth(getApp());
const functions = getFunctions(getApp());

onAuthStateChanged(auth, async (user) => {
  if (!user) {
    console.error("用户未登录,无法调用云函数");
    return;
  }
  
  // 确认用户登录后再执行调用逻辑
  const payload = {
    htmlAsString: response.htmlAsString,
    documentId: documentId,
    actionId: actionId,
    eventId: eventId
  };
  const cloudFunction = httpsCallable(functions, "upload_html_page");
  try {
    const result = await cloudFunction(payload);
    return result.data;
  } catch (ex) {
    console.error("Error executing cloud function", name, ex);
    return null;
  }
});

3. 为云函数添加CORS处理(跨域场景)

如果前端和云函数不在同一域名下,需要在Python云函数中处理OPTIONS预检请求,否则认证头无法正常传递:

@https_fn.on_request()
def upload_html_page(req: https_fn.Request) -> https_fn.Response:
    """Store an entire recorded HTML page."""
    # 处理CORS预检请求
    if req.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }
        return https_fn.Response('', status=204, headers=headers)
    
    try:
        # 原业务逻辑保持不变
        data = req.get_json().get('data', {})
        print(f"Received data: {data}")

        html_content = data.get("htmlAsString")
        documentId = data.get('documentId')
        actionId = data.get('actionId')
        eventId = data.get('eventId')

        storage_client = gcs_storage.Client()
        bucket = storage_client.bucket('***SECRET FOR STACK OVERFLOW***')
        blob = bucket.blob(f"{documentId}/{eventId}_{actionId}")
        blob.upload_from_string(html_content)

        # 响应添加CORS头
        response = https_fn.Response(status=200)
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    except Exception as e:
        response = https_fn.Response(f"Error processing HTML content: {str(e)}", status=500)
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:45:09