首页 > 解决方案 > Firebase 规则 - 用户只能编辑其数据

问题描述

我有一个 firebase 项目,我正在使用 FirebaseAuth 和 firebase 数据库。

我只有一个名为 baby 的集合,具有 name (String)、userId (String) 和 votes (Integer) 属性。userId 包含创建者的 user.uid。

我想创建一个规则,以便只有创建者用户才能更新或删除文档。任何人都可以阅读,注册用户可以创建。

所以我有以下规则:

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

有了这个,任何人都可以阅读,注册用户可以创建。但是,uid=userId 的用户无法更新。有谁知道问题出在哪里?

我检查了数据库,文档的 userID 属性是正确的(与用户 uid 相同)。

谢谢

标签: firebasegoogle-cloud-firestorefirebase-authenticationfirebase-security

解决方案


很可能{userId}不是文档 ID,因此request.auth.uid{userId}

确保在创建文档时指定文档 ID,它应该按预期工作。


推荐阅读