250

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,411
  • 7
  • 35
  • 58
SUHAS REKHU
  • 2,553
  • 2
  • 9
  • 13

25 Answers25

363

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
  • 5,588
  • 2
  • 21
  • 28
  • 70
    note it allows everybody to read,write your database without any authorization. – saigopi.me Sep 12 '18 at 11:26
  • 192
    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
  • 21
    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
  • 15
    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
  • 4
    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
123

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,402
  • 1
  • 14
  • 19
  • 24
    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. – AFD Nov 19 '19 at 13:08
62

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
  • 6,956
  • 12
  • 59
  • 95
rwozniak
  • 1,176
  • 14
  • 15
21

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
  • 5,835
  • 4
  • 32
  • 54
19

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
  • 787
  • 6
  • 18
19

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
  • 3,938
  • 7
  • 44
  • 71
Nadun Liyanage
  • 406
  • 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
12

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
  • 510
  • 6
  • 15
7

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
  • 1,290
  • 11
  • 16
5

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,205
  • 2
  • 21
  • 26
  • 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
5

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
  • 81
  • 1
  • 3
4

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

itzhar
  • 12,149
  • 6
  • 54
  • 60
3

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

wisetap.dev
  • 4,433
  • 2
  • 21
  • 32
3

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
  • 513
  • 4
  • 9
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,279
  • 4
  • 32
  • 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
  • 852
  • 11
  • 25
1

https://console.firebase.google.com

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

enter image description here

enter image description here

Giang
  • 3,341
  • 28
  • 26
1

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
  • 301
  • 4
  • 6
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);
    }
  }
}
titleLogin
  • 549
  • 1
  • 8
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
  • 194
  • 1
  • 9
0

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

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

=> allow read, write

0

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
  • 55,661
  • 11
  • 60
  • 99
Andrey M.
  • 43
  • 4
-1

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

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