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

如何让已登录用户通过Firebase Web SDK 9模块化版本在Firestore创建文档

Firebase v9 模块化SDK不需要手动传递secureToken,只要你使用同一个Firebase应用实例初始化Auth和Firestore服务,用户完成登录后,SDK会自动将用户的身份凭证附加到所有Firestore请求中,无需额外配置。

具体实现流程如下:

1. 初始化关联Auth和Firestore实例

确保Auth和Firestore使用同一个initializeApp返回的应用实例进行初始化,示例代码如下:

import { initializeApp } from "firebase/app";
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

// 替换为你的Firebase项目配置
const firebaseConfig = {
  apiKey: "你的API_KEY",
  authDomain: "你的AUTH_DOMAIN",
  projectId: "你的PROJECT_ID",
  // 其余配置从Firebase控制台获取
};

const app = initializeApp(firebaseConfig);
// 两个服务共享同一个app实例,SDK会自动关联鉴权信息
const auth = getAuth(app);
const db = getFirestore(app);

// 示例:邮箱密码登录逻辑
const userLogin = async (email, password) => {
  try {
    await signInWithEmailAndPassword(auth, email, password);
    // 登录成功后,SDK会自动缓存用户token,后续Firestore请求自动携带
  } catch (err) {
    console.error(err);
  }
}

2. 配置Firestore安全规则

和Realtime Database的规则逻辑一致,配置写入操作需要用户登录即可:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow read: if true;
      allow write: if request.auth != null;
    }
  }
}

3. 直接调用新增文档方法

你现有的addDoc代码不需要做任何修改,只要用户处于登录状态,请求会自动携带鉴权信息,正常通过安全规则校验:

const docRef = await addDoc(collection(db, 'posts'), { postData })

如果确实有特殊场景需要通过REST API调用Firestore而非使用官方SDK,可以手动携带token,方式为在请求URL中添加auth=<你的secureToken>参数,或是在请求头中添加Authorization: Bearer <你的secureToken>。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:15:01