在基于 Firestore 的应用中,我使用以下查询来检索一些数据:
FirebaseFirestore.getInstance().collection("events").document( eventId ).collection("instances").get().addOnCompleteListener( .... )
这会给出权限被拒绝的堆栈跟踪:FirebaseFirestoreException:PERMISSION_DENIED:缺少权限或权限不足。
我的规则的相关部分如下:
match /events/{eventId} {
allow create: if isCurrentUser( request.resource.data.owner );
allow read: if isOwner(eventId) || isAnAdmin( eventId );
allow update: if isOwner( eventId ) || isAtLeastEventAdmin( eventId );
allow delete: if isOwner( eventId );
match /instances/{instanceId} {
allow read: if isOwner(eventId) || isAnAdmin( eventId );
allow write: if isOwner( eventId ) || isAtLeastInstanceAdmin( eventId );
}
}
在控制台模拟器中,对某个实例的查询工作正常,但是一旦我对“实例”集合启动查询,我就会遇到这个问题(这是我无法在模拟器中模拟的问题)。请注意,在这种情况下,isOwner( eventId )
返回 true。
如何启用实例查询?在我看来,“读取”权限应该足以允许查询?
最佳答案
如果查询可能包含任何权限失败的文档,查询将会失败。
https://firebase.google.com/docs/firestore/security/rules-query
以下安全规则使用 request.auth 和 resource.data 变量来限制每个故事对其作者的读写访问权限:
service cloud.firestore {
match /databases/{database}/documents {
match /stories/{storyid} {
// Only the authenticated user who authored the document can read or write
allow read, write: if request.auth.uid == resource.data.author;
}
}
}
假设您的应用程序包含一个页面,向用户显示他们创作的故事文档列表。您可能希望可以使用以下查询来填充此页面。但是,此查询将会失败,因为它不包含与您的安全规则相同的约束:
无效:查询约束与安全规则约束不匹配
//该查询将会失败
db.collection("stories").get()
即使当前用户实际上是每个故事文档的作者,查询也会失败。出现此行为的原因是,当 Cloud Firestore 应用您的安全规则时,它会根据其潜在结果集而不是数据库中文档的实际属性来评估查询。如果查询可能包含违反安全规则的文档,则查询将失败。
关于firebase - 应用程序中的 Firestore 查询给出权限被拒绝,而模拟器工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107132/