简体   繁体   English

Firestore 安全规则 - 写入集合的权限有问题

[英]Firestore security rules - trouble with permission to write to a collection

I've attempted to set up a security rule where a person writing a document to a particular collection may only do so if their uid matches the uid contained in the document, but can't get it to work.我试图设置一个安全规则,其中将文档写入特定集合的人只能在他们的 uid 与文档中包含的 uid 匹配但无法使其工作时这样做。 In this case I am writing a document to a collection called 'embedUsers' and the document being written contains a uid field that was acquired when the user account was created.在这种情况下,我正在将一个文档写入一个名为“embedUsers”的集合,并且正在写入的文档包含一个在创建用户帐户时获取的 uid 字段。

The rules are set up as follows:规则设置如下:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {  
    match /embedUsers/{documents=**} {
      allow read: if true;
      allow write: if resource.data.uid == request.auth.uid;
    }
  }
}

The document is written by an Angular client, using the following code:文档由一位Angular客户编写,使用代码如下:

const userRef: AngularFirestoreDocument<UserModel> = this.afs.doc(`embedUsers/${user.accountAddress}`);
console.log("current logged in user", this.fireUser.uid);
try {
  console.log(user.uid);
  await userRef.set(user, { merge: true });
} catch (e) {
  console.error(`FireAuthService.updateUserData unexpected failure with error ${e.message}`)
  throw new Error("updateUserData failed");
}
console.log("wrote embed user successfully")

Although I have checked that the uid of the signed in user matches the uid field in the data object being written, this call to userRef.set fails with FireAuthService.updateUserData unexpected failure with error Missing or insufficient permissions.尽管我已检查登录用户的 uid 是否与正在写入的数据 object 中的 uid 字段相匹配,但此对userRef.set的调用失败并FireAuthService.updateUserData unexpected failure with error Missing or insufficient permissions. It seems like something must be wrong with my rules but I'm not sure what (if I change the rule to simply say allow write: if true; the document gets written as expected.看来我的规则一定有问题,但我不确定是什么(如果我将规则更改为简单地说allow write: if true;文档按预期写入。

As explained in the doc , "When writing data... the request.resource variable contains the future state of the document".文档中所述,“写入数据时... request.resource变量包含文档的未来 state”。 So you should adapt your rule to:所以你应该调整你的规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {  
    match /embedUsers/{documents=**} {
      allow read: if true;
      allow write: if request.resource.data.uid == request.auth.uid;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM