【问题标题】:Firebase rules are giving PERMISSION DENIED on user trying to save favorited itemsFirebase 规则对尝试保存收藏项目的用户给予 PERMISSION DENIED
【发布时间】:2020-07-24 08:00:23
【问题描述】:

这是我的 Firestore 目录结构:

items \ {document} \ 1 item with date, image etc
users \ {document} \ favoriteItems

启动时:应用下载项目列表。

这些是我的老规矩,显然不适合生产:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

但是按照旧规则,我没有得到错误。所以它必须在规则中。

当用户第一次收藏某项时,users 集合中尚不存在该用户。 users 子目录有document=** 通配符:

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

但是这些规则给出了以下错误:

Firestore: (21.4.2) [Firestore]: Listen for Query(target=Query(users/vsfcRpgewjNdFfQomf7MohcOMcA3/favoriteItems order by name);limitType=LIMIT_TO_FIRST) 失败:状态{code=PERMISSION_DENIED , description=缺少或权限不足。, cause=null}

这似乎很明显,因为第一次document 还不存在。但是,当它存在时,我也会收到相同的错误消息。这有什么适当的规则?

【问题讨论】:

    标签: android firebase google-cloud-firestore firebase-security


    【解决方案1】:

    您正在尝试从集合 users/vsfcRpgewjNdFfQomf7MohcOMcA3/favoriteItems 中读取数据,但只为 users/vsfcRpgewjNdFfQomf7MohcOMcA3 定义了规则。由于您没有在这些规则中授予递归访问权限,因此拒绝访问嵌套集合。

    您需要使用recursive wildcard 允许嵌套访问:

    match /users/{document=**} {
      allow read, write: if request.auth.uid == request.resource.data.author_uid
    }
    

    或者,允许访问特定的子集合:

    match /users/{document} {
      allow read, write: if request.auth.uid == request.resource.data.author_uid
      match /favoriteItems/{favorite} {
          allow read, write: if request.auth.uid == request.resource.data.author_uid
      }
    }
    

    如果嵌套集合的规则与包含文档的权限不同,则后者更有用。

    【讨论】:

    • 它对两个规则集给出了相同的错误:rules_version = '2';服务 cloud.firestore { match /databases/{database}/documents { match /items/{document} { 允许读取,写入:如果 request.auth.uid != null; } match /users/{document=**} { 允许读,写:如果 request.auth.uid == request.resource.data.author_uid } } }
    • 我很确定这是您的规则/代码中的问题之一,但可能还有更多。请编辑您的问题以包含更新的规则,以及您可以触发问题的最少代码。确保此代码没有外部依赖项,因此它可以独立运行。如果存在任何外部依赖项,请记录该依赖项的值并将该日志记录的输出包含在问题中。
    • 谢谢,编辑了这个问题。使用旧规则时,一切正常,所以问题似乎出在我认为的规则中..
    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 2018-01-17
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多