【问题标题】:How to set rules in firebase firestore and realtime?如何在 Firebase Firestore 和实时中设置规则?
【发布时间】:2022-01-01 05:53:22
【问题描述】:

在 Firebase Firestore 中: 我有三个不同的集合,1:-“用户”,2:-“ContactUs”,第三个“报告”。 在用户中,文档是由 uid 创建的,然后它内部有一个名为“uid”的字段。 在 ContactUs 和 Reports 中,文档是随机生成的,并且每次都不同。

我已经尝试了以下规则,但我不确定,请帮助我更正它。在 ContactUs 和 Reports 中,是否应该有 {userId} 或其他内容,因为它每次都不同,我将如何将其与 uid 进行比较,因为其中没有 uid 字段?

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
  allow write, update, delete: if
      request.auth.uid == userId;
      allow read: if request.auth.uid != null;
    
}
match /ContactUs/{userId} {  
  allow write, update, delete: if
      request.auth.uid == userId;
      allow read: if request.auth.uid != null;
    
}
match /Reports/{userId} {
  allow write, update, delete: if
      request.auth.uid == userId;
      allow read: if request.auth.uid != null;
    
  }

 }
}

在实时数据库中:我附上了一张照片供参考,它显示了用户开始新聊天时创建的孩子的详细信息。

我已经实时尝试了以下规则,但它显示:- 您的安全规则不安全。任何经过身份验证的用户都可以窃取、修改或删除您数据库中的数据。

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

请帮助我正确设置它们。谢谢。

【问题讨论】:

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


    【解决方案1】:

    Firestore 规则的工作方式与代码 CSS 相同。它从上到下读取,下面的规则可以覆盖之前的规则。所以首先你应该限制对整个数据库的访问。

    此规则应位于所有规则的顶部。

    match /{document=**} {
       allow read, write: if false;
    }
    

    write 单词等于所有单词加在一起 ​​create, update, delete 所以将这些单词分别用于不同的条件或仅使用 write 单词。

    如果我喜欢你,我会像这样为用户收集制定规则:

    match /users/{userId} {
      allow create, update: if 
         request.auth != null && request.resource.id == request.auth.uid;
      allow read: if request.auth != null && userId == request.auth.uid;
    }
    

    在上面的示例中,如果他的请求文档与他的uid 具有相同的id,则用户可以创建/更新文档,并且如果他请求的文档ID 等于他的uid,则可以读取。在这个规则中没有删除操作,所以他不能删除他的文档。

    实时数据库的工作方式非常相似,但您必须自己了解如何制定规则。

    【讨论】:

    • 还有 ContactUs 和 Reports 集合。我是否需要为他们制定不同的规则或不喜欢 match /ContactUs/ {userId}{...........
    • 关于集合中的其他文档,如果您希望用户能够创建许多文档,请使用他的 uid 创建一个像 isOwner 这样的字段,并编写规则,只有所有者才能读取更新删除。任何登录的人都可以创建一个新文档。
    • 会是这样的:resource.data.isOwner == request.auth.uid
    猜你喜欢
    • 2019-11-03
    • 2020-09-20
    • 2022-01-05
    • 2021-10-17
    • 2019-01-18
    • 1970-01-01
    • 2019-10-17
    • 2019-08-29
    • 2017-06-15
    相关资源
    最近更新 更多