【问题标题】:How to only allow certain users to read Firestore database如何只允许某些用户读取 Firestore 数据库
【发布时间】:2020-11-21 16:13:08
【问题描述】:

我正在开发一个基于 Firestore 数据库的小型 Web 应用程序,我只想让某些用户访问(读取和写入)数据。它可能是 15 或 20 个 UID。我在根级别创建了一个名为“白名单”的集合,其中每个文档都有用户的 UID 和几个字段,其中包含用户 ID、用户名和用户电子邮件。

然后我写了我的规则如下:

service cloud.firestore {   match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null && data.child('whitelist').hasChild(auth.uid);
    }   } }

但是,我已尝试与我自己的用户一起查看它是否有效,即使白名单集合中有一个文档,用户也无法阅读任何内容。我做错了什么?

【问题讨论】:

  • 您可以将它们插入数据库的集合中,然后在规则中检查它是否存在于该集合中,或者您可以使用它们的 UID 创建对象,然后只允许访问那些 UID 匹配的对象
  • @ErayIsmailov 我已经有一个名为 users 的集合,其中有这些用户。它们中的每一个都是该集合中的一个文档。我该怎么做?

标签: google-cloud-firestore


【解决方案1】:
// This will check if the user is authenticated and his UID exists 
// in "haveAccess" collection which must be placed in root. You can use the same for ".write"

".read":"(auth !== null && data.child('haveAccess').hasChild(auth.uid))"

您可以在此处查看规则文档:Google Firebase Database Rules

【讨论】:

  • 我相信该指令适用于实时数据库,而我使用的是不同的 Firestore。我已尝试使其适应 Firestore 规则安全性,但它不起作用。我刚刚编辑了主要帖子以通知我所做的事情。不过谢谢!
【解决方案2】:

确保语句data.child('whitelist').hasChild(auth.uid) 返回true 是非常值得的。

同样根据Data validation,你应该使用resource.data

resource 变量引用请求的文档,resource.data 是存储在文档中的所有字段和值的映射。有关resource 变量的更多信息,请参阅the reference documentation

您可以尝试添加resource:

service cloud.firestore {   match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null && resource.data.child('whitelist').hasChild(auth.uid);
    }   } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2017-12-07
    • 1970-01-01
    • 2019-04-21
    • 2012-04-01
    • 1970-01-01
    相关资源
    最近更新 更多