329

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());
             }
         }
     });
Banana
  • 2,435
  • 7
  • 34
  • 60
SUHAS REKHU
  • 3,363
  • 2
  • 10
  • 13
  • Is the user logged in? – Suhayl SH Oct 05 '17 at 16:10
  • 10
    Have you set the rules under Security Tab in Firebase Console? – Suhayl SH Oct 05 '17 at 16:11
  • 1
    My mistake, I didn't see the drop box for the cloud firestore. I was checking in realtime database only. – SUHAS REKHU Oct 05 '17 at 16:31
  • check https://stackoverflow.com/a/46636036/1028256 – Mixaz Oct 23 '17 at 21:06
  • https://stackoverflow.com/a/47270946/3166417 – itzhar Nov 13 '17 at 18:17
  • https://stackoverflow.com/questions/67048409/reading-from-cloud-firestore-missing-or-insufficient-permissions-in-xamarin-fo – AspiringApollo Apr 12 '21 at 14:28
  • There is some useful information written in this article, [How to fix Firestore Error: PERMISSION_DENIED: Missing or insufficient permissions](https://medium.com/firebase-tips-tricks/how-to-fix-firestore-error-permission-denied-missing-or-insufficient-permissions-777d591f404), that might help. – Alex Mamo Jun 17 '21 at 11:25
  • I used all possible solutions from this topic - neither of them helped me get rid of this error i my android app. However, for my colleague everything just works fine. – Lingviston Jan 02 '23 at 12:50
  • if you've accidentally deleted the permission that are firebase-service account then follow this: https://stackoverflow.com/a/76790535/14190819 – Ammar Jul 28 '23 at 19:27

31 Answers31

473

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;

Luvnish Monga
  • 7,072
  • 3
  • 23
  • 30
  • 77
    note it allows everybody to read,write your database without any authorization. – saigopi.me Sep 12 '18 at 11:26
  • 228
    This is a horrible solution, this literally just disables security. Go read this instead: https://firebase.google.com/docs/firestore/security/get-started – Duncan Lukkenaer Oct 30 '18 at 15:21
  • 2
    @ojonugwaochalifu because this is working for everyone – Luvnish Monga Jan 02 '19 at 10:22
  • 26
    Like @DuncanLuk said, it's a terrible solution. I wouldn't even call it a solution – Ojonugwa Jude Ochalifu Jan 03 '19 at 06:51
  • 1
    A quick and correct answer for people who just read about Firestore from guides (even official ones) that mentions nothing about this. – rlatief Feb 08 '19 at 04:59
  • 1
    I think it's a very useful solution if you're new to firebase, but not a good one as the app development progresses. – Joshua May 22 '19 at 23:15
  • 19
    Best solution to get started really fast. Security concerns could be fixed later actually. – Viacheslav Dobromyslov Aug 25 '19 at 00:51
  • this is not a solution, the solution below by @Md Nakibul Hassan should be the correctly accepted answer. – Thr3e Sep 02 '19 at 09:11
  • 11
    This is NOT a solution. "I'm having issues with security rules, let's just disable them altogether!" – TheRyan722 Nov 18 '19 at 22:00
  • Note - if you are developing locally you also need to change the contents of the `firestore.rules` file. https://firebase.google.com/docs/firestore/security/get-started#deploying_rules – jlhasson Mar 18 '20 at 14:49
  • What is the problem if the goal of a db is to get writable and readable by anyone ? For example, if users can posts and read messages wrote by others users without being logged. – Nitneq Jun 17 '20 at 15:39
  • How does this answer get so many upvotes and how is it accepted as the solution ? It's NOT even a solution. It can be for a start on a local environment, but Firestore rules then need to be set sooner rather than later. – John Doe Apr 13 '21 at 05:58
  • Please let me know if anyone has a solution for this? – Ask17 Nov 29 '21 at 07:39
  • Don't forget to put `match /{document=**}` instead of `match/{your previous documents}`. – LoukasPap Dec 29 '21 at 21:52
  • @LuvnishMonga, I follow the method you provided and still have this problem. How can I solve it please? – My Car Mar 28 '22 at 12:02
  • @MyCar Please provide a screenshot and mention environment – Luvnish Monga Mar 30 '22 at 06:00
  • Chiming in to agree that this is not a solution. Security is not something that can easily just be snapped on top of a system—it should be considered from the start, and understanding how firestore rules work with queries is important. – Nathan Jul 05 '23 at 22:04
143

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;
    }
  }
}
Md Nakibul Hassan
  • 2,716
  • 1
  • 15
  • 19
  • 36
    This is a bad idea, this makes ALL documents writable by ANY authenticated user, even stuff that belongs to other users, stuff that should only be writable by admin or never been writable at all. Please keep the first piece of code as it's a guard against unimplemented security rules. – Noxxys Jun 11 '19 at 12:56
  • 1
    Note that if you let people sign up (with Google SSO for example) they will automatically have access to all of your data. – ForrestLyman Aug 14 '19 at 07:29
  • 3
    I want to allow my authenticated users (a small number) to access all the documents, so this recipe is perfect for my case. – Andrei Drynov Nov 19 '19 at 13:08
75

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.

Elia Weiss
  • 8,324
  • 13
  • 70
  • 110
rwozniak
  • 1,326
  • 15
  • 15
35

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.

xji
  • 7,341
  • 4
  • 40
  • 61
21

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.

TuGordoBello
  • 4,350
  • 9
  • 52
  • 78
Nadun Liyanage
  • 434
  • 3
  • 5
  • 3
    This was my issue too, there's information for this on the [docs](https://firebase.google.com/docs/admin/setup). – tris timb Jan 23 '20 at 02:28
20

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;
      }
   }
}
Ssubrat Rrudra
  • 870
  • 8
  • 20
15

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

Rasel Khan
  • 2,976
  • 19
  • 25
14

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.

maxarndt
  • 560
  • 7
  • 16
7

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

Anga
  • 2,450
  • 2
  • 24
  • 30
  • Isn't the collection created implicitly? In your example "Users" and "user" collection would get created as and when it is referenced. – Bala TJ Jul 18 '19 at 10:23
  • Information can be found here. https://codelabs.developers.google.com/codelabs/firestore-android/#3 – Bala TJ Jul 18 '19 at 10:24
  • 1
    @DevTJ you're correct when it's an `add` or `set` request, but from the question it's a `get` request. I have experienced this before – Anga Jul 18 '19 at 20:28
7

Approved answer is very dangerous as anyone can read or write to your database without any permission. I suggest using this.

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

This will allow authorized personnel to write the database while anyone can read the database which in case visitors to the website.

6

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;
    }
  }
}
M.Mar
  • 91
  • 1
  • 3
6

There are lots of good answers, but as this is the top Google response for Firestore permission denied errors, I thought I would add an answer for beginners and rookies.

Why Security Rules?

If you wrote your own backend, you would have users ask your server for something, and the server would decide what they are allowed to do. For example your server wouldn't allow user1 to delete all of user2's data.

But since your users are interacting with Firebase directly, you can't really trust anything your users are sending you. User1 could just change the user id on his delete request to 'user2' for example.

Firestore Security Rules are where you tell Firestore aka your backend server, who is allowed to read and write what data.

This video from the Firestore team is extremely helpful.

enter image description here https://www.youtube.com/watch?v=eW5MdE3ZcAw

If you are hitting 'missing or insufficient permissions' errors I would strongly suggest you watch the full 22 minutes of this video, before you try anything else.

I went from 1/10 to 7/10 understand of how the security rules work, and why I was getting the error from this video alone.

The getting started guide is also useful and can help answer questions the video doesn't cover. https://firebase.google.com/docs/firestore/security/get-started

Joshua Dance
  • 8,847
  • 4
  • 67
  • 72
5

For development and Test

From: enter image description here

To: enter image description here

mohammed gamal
  • 299
  • 3
  • 4
3

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

Rodrigo João Bertotti
  • 5,179
  • 2
  • 23
  • 34
2

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

itzhar
  • 12,743
  • 6
  • 56
  • 63
2

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

Pramendra Gupta
  • 14,667
  • 4
  • 33
  • 34
2

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!

2

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.

Richardd
  • 956
  • 14
  • 27
  • This is not even a solution, this is kinda a joke. Who wants to use their database only to a certain time while everyone can access it? – GLHF Feb 11 '23 at 14:38
2

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);
Söhrab Vahidli
  • 587
  • 7
  • 10
2

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!

Bilal Ahmad
  • 781
  • 8
  • 10
2

original code:

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

change code:

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

After a few days of research, I figured out that Firestore security rule for request.auth is only going to be valid if the request is made client side, after the auth state of the user has been initialized and is set to != null. If your request is (by any chance) requesting for data server side while using request.auth != null as a rule, it will be rejected. Not sure if there is any solution to this yet, but I'll try to find one or come up with one. Do leave a comment if you guys have any ideas.

raven2218
  • 61
  • 3
1

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);
    }
  }
}
rnewed_user
  • 1,386
  • 7
  • 13
1

Adding another reason for this - AppCheck. I had it enabled on a new project (created ~ May 2022) but hadn't completed the integration steps which caused the "Missing or insufficient permissions" error.

To resolve, first complete the AppCheck setup steps listed under the AppCheck section in Firebase. I used the ReCAPTCHA provider for my web application, you'll need to copy the ReCAPTCHA public key to use in your codebase.

Next add the AppCheck initialisaiton code to wherever you initialise the firebase app. Mine looks like this in React:

  import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check';

  // ......

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);

  self['FIREBASE_APPCHECK_DEBUG_TOKEN'] = true;
  // Pass your reCAPTCHA v3 site key (public key) to activate(). Make sure this
  // key is the counterpart to the secret key you set in the Firebase console.
  initializeAppCheck(app, {
    provider: new ReCaptchaV3Provider('PASTE KEY HERE'),

    // Optional argument. If true, the SDK automatically refreshes App Check
    // tokens as needed.
    isTokenAutoRefreshEnabled: true,
  });

Note the FIREBASE_APPCHECK_DEBUG_TOKEN line prints a debug token in your browser console, you'll need to copy this back into the Firebase console under AppCheck to complete the setup, afterwhich you can comment/delete that line.

This fixed my issue.

Further info:

  1. https://firebase.google.com/docs/app-check/web/recaptcha-provider
  2. https://firebase.google.com/docs/app-check/web/debug-provider?authuser=0&hl=en
Chris Webb
  • 752
  • 7
  • 22
1

To me the problem was that AppCheck was also activated in my Firestore console. So I had to so what the guide stated in the app check Flutter guide

https://firebase.google.com/docs/app-check/flutter/debug-provider?hl=it&authuser=0

Turned on the androidDebugProvider: true, copied the debug token from the console and pasted it in the Firestore section (AppCheck --> app --> add debug token) and it worked immediately.

0

https://console.firebase.google.com

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

enter image description here

enter image description here

Giang
  • 3,553
  • 30
  • 28
0

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.

Wakas Abbasid
  • 372
  • 2
  • 11
0

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

=> allow read, write

-1

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

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.

cigien
  • 57,834
  • 11
  • 73
  • 112
Andrey M.
  • 41
  • 4
-2

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