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

Flutter应用Firebase Firestore规则异常:授权用户无法访问他人食谱

问题排查与解决方案

核心原因是Firestore的exists()函数会严格遵循目标文档的安全规则,而非仅检查文档物理存在性。当前你的外层/users/{userId}规则限制了只有文档所有者才能读取该路径下的内容,当非所有者用户触发exists()查询/users/$(userId)/usersAllowedToRead/$(request.auth.uid)时,会被外层规则拦截,导致exists()返回false,即使目标文档实际存在。

修正后的安全规则

给usersAllowedToRead子集合单独配置规则,允许认证用户读取以自己UID为ID的授权文档,确保exists()查询能正常执行:

match /databases/{database}/documents {
  match /users/{userId} {
    // 允许用户读写自己的文档
    allow read, write: if request.auth != null && request.auth.uid == userId;

    // 单独配置授权子集合的规则
    match /usersAllowedToRead/{allowedUid} {
      // 允许认证用户读取自己在授权列表中的条目
      allow read: if request.auth != null && request.auth.uid == allowedUid;
    }

    match /recipes/{recipeId} {
      // 读取权限:所有者或被授权用户
      allow read: if request.auth != null && 
        (request.auth.uid == userId || 
         exists(/databases/$(database)/documents/users/$(userId)/usersAllowedToRead/$(request.auth.uid)));
      // 写入权限仅开放给所有者
      allow write: if request.auth != null && request.auth.uid == userId;
    }
  }  
}

额外排查点

  • 确认usersAllowedToRead中的文档ID完全匹配当前用户的UID(Firestore文档ID大小写敏感,注意拼写、大小写差异)
  • 在规则测试平台中,检查请求的auth.uid和目标userId是否设置正确
  • 确认数据库中确实存在路径/users/[目标用户ID]/usersAllowedToRead/[当前用户ID]下的文档(仅创建子集合不生效,必须存在对应UID的文档实体)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:02:36