使用访问规则中的字段写入Firestore时缺少权限或权限不足

时间:2017-10-08 20:39:47

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

尝试写入Firestore时出错。

我正在尝试使用包含用户uid的字段作为我的安全规则。

service cloud.firestore {
  match /databases/{database}/documents {

    match /messages/{document=**} {
      allow read: if resource.data.user_uid == request.auth.uid;
      allow write: if resource.data.user_uid == request.auth.uid;
    }
  }
}

如果我的Firestore数据库中有数据,则读取规则正常 - 但是当我尝试编写时,我得到:Error: Missing or insufficient permissions. 我写这条规则有什么问题吗?

P.S。如果我将规则更改为此,我可以写入我的数据库 - 但这对我的目的来说不够安全:

 match /messages/{document=**} {
      allow read: if resource.data.user_uid == request.auth.uid;
      allow write: if request.auth != null;
    }

4 个答案:

答案 0 :(得分:16)

resource.data是指已存储的数据,因此您的规则允许用户仅更新已包含其用户ID的数据。

您可能想要检查的是request.resource.data,这是新数据。

这里有关于这些字段和其他安全规则的相当广泛的文档:https://firebase.google.com/docs/firestore/security/rules-conditions

答案 1 :(得分:7)

这个问题和被接受的答案对我非常有用。我最终使用了一套略有不同的规则,以防他人发现它们有用。

像OP一样,我将用户ID(uid)与资源一起存储。但是,当我要创建新资源时,还没有uid。我使用example in the documentation得出了如下安全规则:

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

答案 2 :(得分:2)

您可以使数据库仅用于读取而不能用于写入:

  service cloud.firestore {
    match /databases/{database}/documents {
     match /{document=**} {
       allow read: if true;
       allow write: if false;
      }
   }
}

答案 3 :(得分:0)

对我来说,这组代码适用于 Firestore 安全

 rules_version = '2';
  service cloud.firestore {
   match /databases/{database}/documents {
   match /{document=**} {
   allow read,write: if true;
          }
        }
      }
相关问题