firebase firestore规则对除一个集合之外的所有集合的访问进行了身份验证

时间:2020-04-01 14:11:46

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

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

公共数据 protecteddata1 protecteddata2

我想拥有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;
    }
  }
}

3 个答案:

答案 0 :(得分:3)

此处的递归通配符允许访问所有集合:

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

一旦任何规则允许访问集合,该访问都无法被其他任何规则撤销。

您要做的是按照自己的规则调用每个单独的集合。是的,这很痛苦,但这是您唯一的选择。这也使规则的读者可以很清楚地知道每个集合打算允许什么。

还值得注意的是,该规则实际上根本不做任何事情,因为它与任何文档都不匹配:

    match /publicdata {
       allow read;
    }

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

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

请记住,规则要与文档匹配才能访问,而不是集合。

答案 1 :(得分:1)

您可以使用我创建的以下功能来实现

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; 
    }
  }
}   

接受,如果它对您有用。可在评论中提出更多问题。

答案 2 :(得分:0)

因为 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;
    }
  }
}
相关问题