簡體   English   中英

為什么 firebase_firestore 安全規則不適用於文檔讀取

[英]Why firebase_firestore security rules not worked for document read

我目前正在開發一個應用程序,用戶需要創建一個新帳戶。 您輸入名字和姓氏,然后應用程序會自動建議一個唯一的用戶名,這將是該用戶的文檔名稱。 我已將 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 安全規則設置為以下條件,用戶如何能夠讀取文檔以檢查是否存在相似的文檔名稱?

允許讀、寫:if request.auth;= null;

首先,我不會使用用戶名將您的數據存儲在 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;
    }
  }
}

對於你的第二個問題,我只是在 firebase 項目的根目錄中創建第二個集合,例如usernames ,所有用戶名都存儲在一個大列表中,這樣你就可以通過 firebase API 安全地查詢它們。為此你必須給經過身份驗證的設備也可以通過例如在下面添加它來訪問此集合

匹配/用戶/...

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

當然,您必須在進行更改時跟蹤這兩個列表。 但是通過這種方式,經過身份驗證的用戶在最壞的情況下只能訪問他的數據和所有用戶名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM