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

Leo*_*mer 27 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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我的Firestore数据库中有数据,那么读取规则可以正常工作 - 但是当我尝试编写时,我得到:Error: Missing or insufficient permissions. 这个写规则是否存在我做错的事情?

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

 match /messages/{document=**} {
      allow read: if resource.data.user_uid == request.auth.uid;
      allow write: if request.auth != null;
    }
Run Code Online (Sandbox Code Playgroud)

Sca*_*ami 20

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

您可能想要检查的是request.resource.data哪些是新数据.

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


qui*_*bit 11

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

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

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)