Flutter Firebase Security Rules does not work

60 Views Asked by At

I am trying to change the security rules from

match /{document=**} {
   allow read, write;       
}

to allow only the authenticated users.

I changed this rule to:

allow read, write: if request.auth != null;

It works in the "rules playground" but when I run the app, it gives the error below:

[WriteStream]: (c1114d) Stream closed with status: Status{code=PERMISSION_DENIED,     description=Missing or insufficient permissions., cause=null}.

FirebaseFirestoreHostApi.documentReferenceSet     
(package:cloud_firestore_platform_interface/src/pigeon/messages.pigeon.dart:1009:7)

<asynchronous suspension>

MethodChannelDocumentReference.set       
  (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.   dart:35:7)
 <asynchronous suspension>

Actions:

My DB has collections inside collections in some of my collections, so, I changed the rule to :

this format in case of the collection "count" that only has documents:

match  /count/{document=**} {  
  allow read;
  allow write: if request.auth.uid !=null;       
}

and to this format if the collections (comments) has documents that have sub collections that have documents

match  /comments/{comments} {  
  allow read;
  allow write: if request.auth.uid !=null;
  
    match  /comments/{comments} {  
         allow read;
         allow write: if request.auth.uid !=null;
    }                                               
  }

If the above if request.auth.uid !=null; is replaced by true; everything works perfectly, but it is not secured since even unauthenticated users can write into the DB.

I am using Android Studio and Flutter.

1

There are 1 best solutions below

1
Sahil Totala On

First, you need to confirm that the user has logged in via Firebase authentication and if you want to secure all Firestore documents you can use this rule to give only authorized user access to data

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}