'firestore: PERMISSION_DENIED: Missing or insufficient permissions

I am getting the Error

gettingdocuments.com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.

for the below code on else statement

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


Solution 1:[1]

Go in Database -> Rules ->

For development:

Change allow read, write: if false; to true;

Note: It's quick solution for development purpose only because it will turns off all the security. So, it's not recommended for production.

For production:

If authenticated from firebase: Change allow read, write: if false; to request.auth != null;

Solution 2:[2]

Go to Database -> Rules :

Then changed below rules

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

to below

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

Solution 3:[3]

So in my case I had the following DB rules:

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

As you can see there is a uid field on the story document to mark the owner.

Then in my code I was querying all the stories (Flutter):

Firestore.instance
          .collection('stories')
          .snapshots()

And it failed because I have already added some stories via different users. To fix it you need to add condition to the query:

Firestore.instance
          .collection('stories')
          .where('uid', isEqualTo: user.uid)
          .snapshots()

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

EDIT: from the link

Rules are not filters When writing queries to retrieve documents, keep in mind that security rules are not filters—queries are all or nothing. To save you time and resources, Cloud Firestore evaluates a query against its potential result set instead of the actual field values for all of your documents. If a query could potentially return documents that the client does not have permission to read, the entire request fails.

Solution 4:[4]

I also had the "Missing or insufficient permissions" error after specifying security rules. Turns out that the the rules are not recursive by default! i.e. if you wrote a rule like

match /users/{userId} {
  allow read, write: if request.auth != null && request.auth.uid == userId;
}

The rule will not apply to any subcollections under /users/{userId}. This was the reason for my error.

I fixed it by specifying the rule as:

match /users/{userId}/{document=**} {
  allow read, write: if request.auth != null && request.auth.uid == userId;
}

Read more at the relevant section of the documentation.

Solution 5:[5]

The above voted answers are dangerous for the health of your database. You can still make your database available just for reading and not for writing:

  service cloud.firestore {
    match /databases/{database}/documents {
     match /{document=**} {
       allow read: if true;
       allow write: if false;
      }
   }
}

Solution 6:[6]

If you try in Java Swing Application.

  1. Go To Firebase Console > Project Overview > Project Settings

  2. Then Go to Service Accounts Tab and Then Click on Generate New Private Key.

  3. You will get a .json file, place it in a known path

  4. Then Go to My Computer Properties, Advanced System Settings, Environment Variables.

  5. Create New Path Variable GOOGLE_APPLICATION_CREDENTIALS Value with your path to json file.

Solution 7:[7]

If someone lands here trying to access Firestore with a service-account:

I solved this issue by granting the service-account the Service Account User role in addition to the Cloud Datastore User role in the IAM settings of GCP.

Solution 8:[8]

Change here
set false to true

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

And publish new rules

enter image description here

Solution 9:[9]

Additionally, you may get this error if the collection reference from your code does not match the collection name on firebase.

For example the collection name on firebase is users, but your referencing it with db.collection("Users") or db.collection("user")

It is case sensitive as well.

Hope this helps someone

Solution 10:[10]

npm i --save firebase @angular/fire

in app.module make sure you imported

import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';

in imports

AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule,
    AngularFireAuthModule,

in realtime database rules make sure you have

{
  /* Visit  rules. */
  "rules": {
    ".read": true,
    ".write": true
  }
}

in cloud firestore rules make sure you have

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Solution 11:[11]

make sure your DB is not empty nor your query is for collection whom not exist

Solution 12:[12]

I had this error with Firebase Admin, the solution was configure the Firebase Admin correctly following this link

Solution 13:[13]

Go in Firestore's Database > Rules:

rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, get: if true;
          allow write: if false;
      }
    }
}

for more informatin: https://firebase.google.com/docs/rules/rules-language?authuser=0

100% working as of now!?

Solution 14:[14]

Check if the service account is added in IAM & Admin https://console.cloud.google.com/iam-admin/iam with an appropriate role such as Editor

Solution 15:[15]

the problem is that you tried to read or write data to realtime database or firestore before the user has be authenticated. please try to check the scope of your code. hope it helped!

Solution 16:[16]

At this time, June 2020, by default the firebase is defined by time. Define the time to meet your needs.

allow read, write: if request.time < timestamp.date(2020, 7, 10);

Please note: your DB still open to anyone. I suggest, please read the documentation and configure the DB the way that is useful for you.

Solution 17:[17]

https://console.firebase.google.com

Develop -> Database -> Rules -> set read, write -> true

enter image description here

enter image description here

Solution 18:[18]

time limit may be over

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    // This rule allows anyone on the internet to view, edit, and delete
    // all data in your Firestore database. It is useful for getting
    // started, but it is configured to expire after 30 days because it
    // leaves your app open to attackers. At that time, all client
    // requests to your Firestore database will be denied.
    //
    // Make sure to write security rules for your app before that time, or else
    // your app will lose access to your Firestore database
    match /{document=**} {
      allow read, write: if request.time < timestamp.date(2020,7, 1);
    }
  }
}

there change date for nowadays in this line:

 allow read, write: if request.time < timestamp.date(2020,7, 1);

Solution 19:[19]

maybe you need to remove the date

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if
          request.time < timestamp.date(2021, 12, 12);
    }
  }
}

Solution 20:[20]

For me it was the issue with the date. Updated it and the issue was resolved.

Allow read/write:

 if request.time < timestamp.date(2020, 5, 21);

Edit: If you are still confused and unable to figure out what's the issue just have a look at the rules section in your firebase console.

Solution 21:[21]

GO to rules in firebase and edit rules ..... (provide a timestamp or set to false) My solution.

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.time < timestamp.date(2021, 8, 18);
    }
  }
}

Solution 22:[22]

Go to firebase console => cloud firestore database and add rule allowing users to read and write.

=> allow read, write

Solution 23:[23]

I have managed to resolve the issue in my case. I've got 2 errors:

  1. PERMISSION_DENIED: Missing or insufficient permissions.
  2. Cannot enable Firestore for this project.

Steps to fix this issue:

Part 1.

  1. Go to the https://console.firebase.google.com/
  2. Firestore Database -> Delete all collections
  3. Firestore Database -> Rules -> Delete all rules history

Part 2.

  1. Go to the https://console.cloud.google.com/
  2. Find in menu: APIs & Services -> Enabled APIs & Services
  3. Disable 3 services: "Cloud Firestore API”, “Firebase Rules API”, "Cloud Storage for Firebase API”
  4. Find in menu: Firestore -> It will automatically enable "Cloud Firestore API” & “Firebase Rules API” services and will create Firestore Database.
  5. Enable "Cloud Storage for Firebase API”.

The most important thing is to create a Firestore Database from the Google Cloud Console.

Solution 24:[24]

Your rules should be like this for this case however the message says that it is not the suggested way, but if you do this you can do inserts with no permission error

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

Solution 25:[25]

Go To Apple Certificates, Identifiers & Profiles : Select Your Key Upload firebase and Make Check For : Access the DeviceCheck and AppAttest APIs to get data that your associated

enter image description here