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

Firestore onCreate触发器获取当前认证用户UID时context.auth未定义

解决Firestore onCreate触发器中获取认证用户UID的问题

问题原因

你遇到的context.auth为undefined的情况,是因为Firestore的Cloud Functions触发器不会自动将客户端写入操作的用户认证信息传递到context.auth中。这个字段仅在通过Firebase Admin SDK发起写入操作且主动指定auth参数模拟用户时才会被填充,客户端通过Firebase SDK发起的写入不会触发该字段赋值。

可行解决方案

方案1:写入文档时主动存储用户UID

这是最直接且常用的方式:在客户端创建文档时,将当前认证用户的UID作为文档字段一起写入。

  • 客户端示例代码:
// 假设已初始化Firebase Auth和Firestore
const user = firebase.auth().currentUser;
if (user) {
  firebase.firestore().collection('someCollection').add({
    // 其他业务字段
    createdBy: user.uid // 添加用户UID字段
  });
}
  • 触发器中获取UID:
import * as functions from "firebase-functions";

export const mytriggerFunction = functions.firestore
  .document('someCollection/{documentId}')
  .onCreate((snapshot, context) => {
    const createdByUid = snapshot.data().createdBy;
    console.log("创建文档的用户UID:", createdByUid);
    return true;
  });

方案2:结合安全规则防止字段篡改

如果需要确保只有认证用户才能写入文档,同时避免客户端伪造createdBy字段,可以配合Firestore安全规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /someCollection/{docId} {
      allow create: if request.auth != null && request.resource.data.createdBy == request.auth.uid;
    }
  }
}

这条规则会强制要求写入的createdBy字段必须等于当前认证用户的UID,从根源上避免用户篡改身份信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:05:23