Firestore规则:执行setData时出错,PERMISSION_DENIED

时间:2020-04-29 21:37:33

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

我有以下几行内容可将数据写入用户集合:

  final databaseReference = Firestore.instance;
  await databaseReference.collection("users")
      .document(userData['uid'])
      .setData(userData);

userData是:{uid:b4WRYgXae8QIq9e3jTHscMPjvtk1,电话:+17031110000}。

我应用了以下规则,其中包含第allow write: if (request.auth.uid == resource.data.uid)

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{docId} {
      allow read: if (true);
      allow write: if (request.auth.uid == resource.data.uid)
      allow read, write: if (request.auth.uid == 'xxxxx')
    }
    match /orders/{docId} {
      allow read, write: if (request.auth.uid == resource.data.uid)
      allow read, write: if (request.auth.uid == 'xxxxx')
    }
  }
}

但是颤抖,我出现了以下错误:

  I/System.out(  931): (HTTPLog)-Static: isSBSettingEnabled false
    I/System.out(  931): (HTTPLog)-Static: isSBSettingEnabled false
    W/Firestore(  931): (21.4.2) [Firestore]: Write failed at users/b4WRYgXae8QIq9e3jTHscMPjvtk1: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
    E/flutter (  931): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(Error performing setData, PERMISSION_DENIED: Missing or insufficient 

1 个答案:

答案 0 :(得分:1)

在安全规则中,resource是指文档中现有数据。如果没有现有文档,则那里没有任何值,并且对其内容的任何检查都将失败,该规则将拒绝访问。

传入的文档数据在request.resource中,因此您可能需要更改规则,如下所示:

allow write: if (request.auth.uid == request.resource.data.uid);

这将要求客户端始终为用户集合中的文档提供一个与自己的Auth uid匹配的uid字段。