【问题标题】:Why firebase_firestore security rules not worked for document read为什么 firebase_firestore 安全规则不适用于文档读取
【发布时间】:2021-03-31 17:56:44
【问题描述】:

我目前正在开发一个应用程序,并且该用户需要创建一个新帐户。您输入名字和姓氏,然后应用程序会自动建议一个唯一的用户名,它将是该用户的文档名称。我已将 Firestore 安全规则设置如下,

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

在用户输入用户名后,它会检查用户名是否被使用,然后移动到下一个屏幕。

  Future<bool> checkUsernameExist(String name)async{
    bool usernameExistSate;
    await firestore.collection('users').doc(name).get().then((docSnapShot){
      if(docSnapShot.exists){
        usernameExistSate = true;
      }else{
        usernameExistSate = false;
      }
    });
    return usernameExistSate;
  }

目前上述系统工作正常,没有任何问题。但是我有一个问题,在将 Firebase 安全规则设置为以下条件的情况下,用户如何能够阅读文档以检查是否存在类似的文档名称?

允许读、写:如果 request.auth != null;

【问题讨论】:

  • 用户需要先登录才能阅读该集合。如果这是您的用例的问题,请考虑不要求他们登录。

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


【解决方案1】:

首先,我不会使用用户名将您的数据存储在 Firestore 中,而是使用通过 google auth 进行身份验证时提供的 uid。这将允许您使用以下安全规则更安全地访问数据库: rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{document=**} {
      allow read, write, update, delete: if request.auth != null && request.auth.uid == userId;
      allow create: if request.auth != null;
    }
  }
}

对于您的第二个问题,我只需在名为 usernames 的 firebase 项目的根目录中创建第二个集合,所有用户名都存储在一个大列表中,以便您可以通过 firebase API 安全地查询它们。为此,您必须让经过身份验证的设备也可以访问此集合,例如将其添加到

匹配 /users/...

match /usernames/{document=**} {
      allow read, write, update, delete, create: if request.auth != null;
}

当然,您必须在进行更改时跟踪这两个列表。但是这样一来,在最坏的情况下,经过身份验证的用户只能访问他的数据和所有用户名。

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 2021-05-14
    • 1970-01-01
    • 2020-06-19
    • 2020-12-30
    相关资源
    最近更新 更多