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

Firestore注册用户无法创建个人文档:权限问题求助

Firestore创建用户文档权限错误排查与解决

问题背景

注册用户后尝试在Firestore的users/${uid}路径创建文档时,持续收到「Missing or insufficient permissions」错误,尝试过以下两条安全规则:

规则1

match /users/{documents=**} {
    allow read, create, update: if request.auth != null && request.auth.uid == resource.id
}

规则2

match /users/{uid=**} {
      allow read, create, update: if request.auth != null && request.auth.uid == uid
}

对应的前端注册并创建文档代码:

createUserWithEmailAndPassword(auth, emailInput, passwordInput).then(
  (UserCredential) => {
    console.log(UserCredential);
    uid = UserCredential.user.uid;
    sendEmailVerification(auth.currentUser).then(() => {
      toast.success(
        "Account created and email verification sent! Please check your inbox/spam folder",
        {
          duration: 10000,
        }
      );
      setDoc(doc(db, "users", uid), {
        userSettings: ["example", 0],
      });
      router.push("/verify");
    });
  }
);

错误原因分析

  1. 规则1失效原因:resource.id仅针对已存在的文档生效(比如更新、读取操作),执行create创建文档时,resource对象尚未存在,因此resource.id为null,直接导致权限校验不通过。
  2. 规则2失效原因:使用了递归通配符{uid=**},该通配符会匹配users/下的所有子路径(包括子集合),但我们需要的是精确匹配users下的单个用户文档ID,通配符写法错误导致匹配逻辑不符合预期。

解决方案

使用精确匹配的安全规则,针对users/{uid}路径设置权限:

match /users/{uid} {
  allow create, read, update: if request.auth != null && request.auth.uid == uid;
}

可选加固规则

如果需要进一步确保用户创建的文档ID与自身uid严格一致(防止前端传入错误ID),可以添加额外校验:

match /users/{uid} {
  allow create: if request.auth != null && request.auth.uid == uid && request.resource.id == uid;
  allow read, update: if request.auth != null && request.auth.uid == uid;
}

前端代码说明

你的前端代码逻辑是正确的,创建用户后获取uid并在users/${uid}路径创建文档,这部分无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:55:22