我得到了错误
gettingdocuments.com.google.firebase.firestore.FirebaseFirestoreException:
PERMISSION_DENIED:缺少或权限不足。
对于下面关于else语句的代码
db.collection("users")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
s(document.getId() + " => " + document.getData());
}
} else {
s("Error getting documents."+ task.getException());
}
}
});
所以在我的情况下,我有以下DB规则:
service cloud.firestore {
match /databases/{database}/documents {
match /stories/{story} {
function isSignedIn() {
return request.auth.uid != null;
}
allow read, write: if isSignedIn() && request.auth.uid == resource.data.uid
}
}
}
正如您所看到的,故事文档上有一个uid字段用来标记所有者。
然后在我的代码中,我查询了所有的故事(Flutter):
Firestore.instance
.collection('stories')
.snapshots()
它失败了,因为我已经通过不同的用户添加了一些故事。
要解决这个问题,你需要在查询中添加条件:
Firestore.instance
.collection('stories')
.where('uid', isEqualTo: user.uid)
.snapshots()
更多详情请访问:https://firebase.google.com/docs/firestore/security/rules-query
编辑:从链接
规则不是过滤器
在编写检索文档的查询时,请保持
请记住,安全规则不是过滤器—查询都是或
什么都没有。为了节省您的时间和资源,Cloud Firestore会评估一个
根据其潜在结果集而不是实际字段查询
所有文档的值。查询是否可能返回
客户端没有权限读取的文档,全部删除
请求失败。
在指定安全规则后,我还出现了“缺少或权限不足”错误。事实证明,默认情况下规则不是递归的!例如,如果你写了一个规则
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
该规则将不适用于/users/{userId}下的任何子集合。这就是我犯错误的原因。
我通过指定规则来修复它:
match /users/{userId}/{document=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
在文档的相关部分中阅读更多信息。