【问题标题】:firebase firestore rules authenticated access to all collections except onefirebase firestore 规则验证了对除一个之外的所有集合的访问权限
【发布时间】:2020-04-01 14:11:46
【问题描述】:

我有以下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;
    }
  }
}

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

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

        match /publicdata {
           allow read;
        }
    

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

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

    请记住,规则匹配文档的访问权限,而不是集合。

    【讨论】:

    • 将规则匹配到文档而不是集合的好处。我在阅读中错过了这一点
    • 似乎另一个答案似乎确实做了除了一个集合之外的所有验证
    【解决方案2】:

    您可以使用我创建的以下函数来执行此操作

    function isUserAuthenticated() {
        return request.auth.uid != null; 
    }
    

    然后你可以像这样使用它:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if isUserAuthenticated();
        }
        
        match /publicdata/{itemId} {
          allow read : if true;
          allow create : if isUserAuthenticated();
          allow update: if isUserAuthenticated();
          allow delete: if isUserAuthenticated();
        }
    
        /* Functions */
        function isUserAuthenticated() {
          return request.auth.uid != null; 
        }
      }
    }   
    

    【讨论】:

    • 得到一个空错误 - 但更改函数可以修复它: function isUserAuthenticated() { return request.auth != null; }
    • 很高兴我的回答对你有所帮助:)
    【解决方案3】:

    因为here 说:

    重叠匹配语句

    一个文档可以匹配多个匹配语句。在多个允许的情况下 表达式匹配请求,如果有任何一个,则允许访问 条件为真:...

    你可以用这个:

    rules_version = '2';
    service cloud.firestore {
    
      // Check if the request is authenticated
      function isAuthenticated() {
        return request.auth != null;
      }
    
      match /databases/{database}/documents {
        match /{document=**} {
            allow read, write: if isAuthenticated();
        }
        match /publicdata/{document=**} {
            allow read: if true;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多