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

嵌套Firestore安全规则写入权限失效问题排查

Firestore写入权限问题排查

问题详情

当前使用的Firestore安全规则:

rules_version = '2';
service cloud.firestore {
 match /databases/{database}/documents {
  match /{document=**} {
    allow read: if request.auth != null;      
    match /users/{userId} {  
      allow write: if request.auth.uid == userId;
    }
  }
 }
}

读取权限正常,但执行以下写入代码时:

console.warn(auth.currentUser)
const docRef = doc(db, `users/${uid}/${flick.type}-${list}`, String(flick.id))

出现权限错误:

Uncaught (in promise) FirebaseError: Missing or insufficient permissions.

已确认auth.currentUser.uid正确,且Firestore中存在users/xyz(xyz为当前用户uid)路径的文档,但仍无法写入。

问题原因

你的安全规则中,match /users/{userId}仅匹配users/{userId}这个一级文档,而你实际写入的是users/{userId}/{子集合名称}/{文档ID}这种子集合层级的文档,原规则没有为该层级的路径赋予写入权限,因此触发权限不足错误。

修复方案

调整安全规则,让用户对自己users/{userId}路径下的**所有层级文档(包括子集合)**拥有写入权限,修改后的规则如下:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 所有文档的读取权限:已登录用户即可访问
    match /{document=**} {
      allow read: if request.auth != null;
    }
    // 用户自己的users路径下所有文档(含子集合)允许写入
    match /users/{userId}/{document=**} {
      allow write: if request.auth.uid == userId;
    }
  }
}

规则说明

  • {document=**}是通配符,匹配当前路径下的所有子文档和子集合,确保用户能操作自己users节点下的所有内容。
  • 将读取和写入规则分开定义,逻辑更清晰,避免嵌套匹配导致的路径覆盖问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 17:27:38