首页 > 解决方案 > firebase firestore 规则验证了对除一个之外的所有集合的访问权限

问题描述

我有以下firestore结构,基本上是3个集合

公共数据受保护数据1 受保护数据2

我想要protecteddata1和protecteddata 2,实际上整个firestore数据库只作为经过身份验证的用户。但我希望公众拥有对“publicdata”集合的只读访问权限。

以下是我的尝试,但它不起作用

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

标签: firebasegoogle-cloud-firestorefirebase-security

解决方案


这里的递归通配符允许访问所有集合:

    match /{document=**} {
      allow read;
      allow write: if (request.auth.uid != null);
    }

一旦任何规则允许访问集合,该访问权限就不能被任何其他规则撤销。

您需要做的是按照自己的规则调用每个单独的集合。是的,这有点痛苦,但这是你唯一的选择。它还使您的规则的读者非常清楚您打算为每个集合允许什么。

另外值得注意的是,这条规则实际上并没有做任何事情,因为它不匹配任何文档:

    match /publicdata {
       allow read;
    }

如果要匹配 publicdata 集合中的文档,则需要一个与该集合中的文档匹配的通配符:

    match /publicdata/{id} {
       allow read;
    }

请记住,规则匹配文档以进行访问,而不是集合。


推荐阅读