【问题标题】:FIXED : Firestore security rules for subscribed users已修复:订阅用户的 Firestore 安全规则
【发布时间】:2020-07-24 01:25:59
【问题描述】:

我正在构建一个博客,并且我正在为数据库使用 firestore。我正在尝试编写安全规则,以便只有订阅的用户才能查看文章的内容和文章,但我希望每个人都能在主页上看到文章的标题和照片。

我的数据库架构是这样的:

我有一个文章集合,其中每个文档都是单独的文章,其中包含标题和照片等字段。在每个文章文档中都有一个“受保护”子集合,其中包含文章的内容,我希望只有订阅的用户能够获得该受保护的信息。

到目前为止我的规则是

 match /articles/{articleId} {
    allow read: if true;
            allow write: if request.auth.uid == 'someId';

    match /articles/{articleId}/protected/{protecedId} {
      allow read: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.subscription == true;

    }
  }

但是,这会阻止我的主页加载和显示任何文章。有人可以帮我弄清楚我的规则有什么问题吗?

更新: 我的规则现在看起来像这样:

 match /articles/{articleId} {
    allow read: if true;
            allow write: if request.auth.uid == 'someid';

     match /protected/{protectedId} {
      allow read: if true;
                allow write;
    }
  }

但是,我的主页再次无法加载。唯一的解决方案似乎是将 match /{document=**} 添加到我的规则中。但是,这意味着我的所有其他规则都将被覆盖。

固定:

我需要为我的所有集合和子集合编写规则。

【问题讨论】:

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


    【解决方案1】:

    您没有在规则中正确声明您的hierarchical data structure

    正如上面链接的文档中所解释的,“当嵌套匹配语句时,内部匹配语句的路径总是相对于外部匹配语句的路径”。

    因此,您应该删除/articles/{articleId}/protected/{protectedId}路径的第一部分,如下所示:

    service cloud.firestore {
        match /databases/{database}/documents {
           match /articles/{articleId} {
              allow read: if true;
              allow write: ....;
    
              match /protected/{protecedId} {
                allow read: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.subscription == true;
              }
           }
        }
    }
    

    【讨论】:

    • 嗯,这很奇怪。有了这些规则,每个人都可以阅读文章集(firebase.firestore().collection('articles').get().then(...))。我将调整答案以包含所有规则代码。也许您的问题出在其他地方。
    • 在我为所有集合和子集合添加规则时修复它。
    猜你喜欢
    • 2019-09-15
    • 2018-10-19
    • 2019-07-05
    • 2018-08-17
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多