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

Firebase模拟器中onDocumentCreatedWithAuthContext无法获取正确认证信息

问题:Firestore模拟器中onDocumentCreatedWithAuthContext无法获取正确认证信息

我需要在Firestore文档创建时构建特定关联文档,且需知晓文档创建者。根据Firebase官方文档,应使用包含认证信息的onDocumentCreatedWithAuthContext触发器实现。目前仅在本地使用最新版Firebase模拟器(未部署到Firebase),编写的函数无法获取正确认证信息,日志输出:

{"severity":"INFO","message":"unknown fake-auth-id@gmail.com"}

函数代码如下:

"use strict";

// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const {logger} = require("firebase-functions");
const {onRequest} = require("firebase-functions/v2/https");
const {onDocumentCreatedWithAuthContext} = require("firebase-functions/v2/firestore");

// The Firebase Admin SDK to access Firestore.
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");

initializeApp();

exports.createFamilyLinks = onDocumentCreatedWithAuthContext("/thecollection/{documentId}", (event) => {
  const { authType, authId } = event;
  logger.log(authType, authId);
});

请问这是否是Firebase模拟器的限制,还是该功能本就无法正常工作?

参考文档(中文翻译):Firebase官方文档中关于第二代Firestore事件触发器的认证上下文说明,提到onDocumentCreatedWithAuthContext触发器可以获取触发文档操作的用户认证信息,适用于需要验证操作发起者身份的场景。


回答

结论

这是Firebase本地模拟器的当前限制,并非功能本身存在问题。

详细说明

  • 本地Firestore模拟器在触发onDocumentCreatedWithAuthContext时,默认会生成模拟的认证数据(即你日志中看到的unknown fake-auth-id@gmail.com),无法传递真实的用户认证ID和类型。
  • 该触发器部署到Firebase生产环境后,能够正确捕获触发文档创建操作的用户认证上下文(包括authType和authId),完全符合官方文档描述的功能。

本地调试方案

如果需要在本地验证认证相关逻辑,可尝试以下方式:

  1. 在函数代码中手动模拟不同的authType和authId值,测试各逻辑分支
  2. 使用Firebase Emulator Suite的UI或CLI工具,手动触发事件时指定自定义认证参数(部分场景支持)
  3. 临时将函数部署到Firebase测试环境,进行真实认证场景的验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:10:06