Firestore query in app gives permission denied, while simulator works fine

折月煮酒 提交于 2019-12-23 15:57:07

问题


In my Firestore based app I use the following query to retrieve some data:

FirebaseFirestore.getInstance().collection("events").document( eventId ).collection("instances").get().addOnCompleteListener( .... )

This gives a permission denied stacktrace: FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.

The relevant part of my rules is as follows:

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 );
      }
    } 

Within the console simulator a query for a certain instance works fine, but as soon as I launch a query on the "instances" collection I get this issue (this is something I cannot simulate in the simulator). Note that isOwner( eventId ) returns true in this situation.

How can I enable queries for the instances? In my opnion the 'read' permission should be enough to allow queries?


回答1:


Queries will fail if the query could contain any document that fails permissions.

https://firebase.google.com/docs/firestore/security/rules-query

The following security rule uses the request.auth and resource.data variables to restrict read and write access for each story to its author:

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;
    }
  }
}

Suppose that your app includes a page that shows the user a list of story documents that they authored. You might expect that you could use the following query to populate this page. However, this query will fail, because it does not include the same constraints as your security rules:

Invalid: Query constraints do not match security rules constraints

// This query will fail

db.collection("stories").get()

The query fails even if the current user actually is the author of every story document. The reason for this behavior is that when Cloud Firestore applies your security rules, it evaluates the query against its potential result set, not against the actual properties of documents in your database. If a query could potentially include documents that violate your security rules, the query will fail.



来源:https://stackoverflow.com/questions/51107132/firestore-query-in-app-gives-permission-denied-while-simulator-works-fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!