Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable querying collection in Firebase Cloud Firestore with rules

I am using Firebase Cloud Firestore, and I want to modify my rules to restrict users from querying a collection.

This should not be allowed:

firestore().collection("users").get()

But this should be allowed:

firestore().collection("users").doc("someUserId").get()

Currently, my rules look like this:

match /users/{userId} {
    allow read;
}

but this rule allows the "users" collection to be queried.

How can I allow single document gets, but not collection queries?

like image 820
dshukertjr Avatar asked Feb 07 '18 08:02

dshukertjr


People also ask

Does firebase Admin bypass rules?

The Firebase Admin SDKs access your database using a service account. Service accounts ignore the Cloud Firestore Security Rules, similar to how you can edit documents in the Firebase Console directly yourself.

How do you set rules in cloud firestore?

To set up and deploy your first set of rules, open the Rules tab in the Cloud Firestore section of the Firebase console. Write your rules in the online editor, then click Publish.

How do I stop firestore from reading?

The only change you can make to decrease the number of reads would be to change the value that you pass to the limit() function.

How do I protect Firebase firestore?

Firestore offers robust access management and authentication through two different methods, depending on the client libraries you use. For mobile and web client libraries, use Firebase Authentication and Firestore Security Rules to handle serverless authentication, authorization, and data validation.


2 Answers

You can break read rules into get and list. Rules for get apply to requests for single documents, and rules for list apply to queries and requests for collections (docs).

match /users/{userId} {

  //signed in users can get individual documents
  allow get: if request.auth.uid != null;

  //no one can query the collection
  allow list: if false;
}
like image 105
Juan Lara Avatar answered Oct 16 '22 12:10

Juan Lara


Just allow get and you'll be good:

match /users/{userId} {
    allow get;
}

Reference: https://firebase.google.com/docs/rules/rules-language#:~:text=Convenience%20methods-,read,-Any%20type%20of

like image 1
Sanjay Verma Avatar answered Oct 16 '22 10:10

Sanjay Verma