【问题标题】:Improve Firestore rules改进 Firestore 规则
【发布时间】:2018-07-15 00:14:13
【问题描述】:

几天来,我一直在尝试改进保护数据库的 Firestore 规则。我似乎只是在每次编辑时都将所有人拒之门外。我现在使用的规则是在 Firestore documentation 中找到的基本规则。分别是:

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

但我想稍微扩展安全性以收紧编辑规则。我的数据库如下所示:

Users (collection) > User (document) > User specific data

我想要的是每个经过身份验证的用户都可以读取所有数据,但只有文档所属的用户(通过唯一的用户 ID)可以编辑/添加/删除他们的数据。

我希望你们中的某个人能指出我正确的方向,因为我似乎没有从官方文档中得到任何更明智的信息。

更新:我如何在我的 Android 应用中集成 Firestore。

user = FirebaseAuth.getInstance().getCurrentUser();
db = FirebaseFirestore.getInstance().collection("users");

CollectionReference colRef = db.document(user.getUid()).collection("watched");
colRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
       @Override
       public void onComplete(@NonNull Task<QuerySnapshot> task) {
          if (task.isSuccessful()) {
             ArrayList<Movie> tempItems = new ArrayList<>();
             for (DocumentSnapshot document : task.getResult()) {
                 // Handle data
             }
             } else {
                 Log.d(TAG, "Error getting documents: ",task.getException());
             }
          }
   });

【问题讨论】:

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


    【解决方案1】:

    我显然读错了有关 resource.data 的文档。我必须自己添加 author_id 字段。我不知道这一点,但一旦我添加了它,它就像一个魅力!

    【讨论】:

    • 你并不孤单。我认为 author_id 也是资源对象上的一个特殊元数据字段。
    【解决方案2】:

    您可以编写规则以确保请求用户的 uid 与文档的 author_id 字段匹配:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /Users/{User} {
          allow read: if request.auth.uid != null;
          allow create, update, delete: if request.auth.uid == resource.data.author_id;
        }
      }
    }
    

    【讨论】:

    • 我可能遗漏了一些东西,但是当我这样做时,通过 Firebase Android UI 进行身份验证的用户在任何读取时都会获得拒绝权限。
    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 2019-04-18
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 2019-08-14
    • 2019-01-09
    相关资源
    最近更新 更多