Search code examples
google-cloud-firestorefirebase-security

Can't access Firestore after etting "allow all authenticated"


I'm initializing FireStore in my Chrome extension like they explain in the docs:

import { initializeApp } from "firebase/app";
initializeApp({apiKey:'...', ...});

Then I call setDoc to store a document. Everything is fine when I set allow read, write: true in the access rules. But when I change it to allow read, write: if request.auth != null, all my Firestore requests start failing with Error adding document: FirebaseError: [code=permission-denied]: Missing or insufficient permissions.

I assumed that providing my Firestore API key and other data in the initialization code would automatically make it authenticated. However, Firestore thinks that my requests are anonymous for some reason. How do I fix this?

Here's my config:

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

Solution

  • The request.auth check if the request is coming from authenticated user in firebase authentication.

    The Firestore API key is only to send the request to the correct firebase project, but it doesn't make the request.auth != null.

    You need to authenticate against firebase authentication in order to get request.auth != null. But in your case I beleive you don't want the users to authenticate, so you need some other security rule to get what you really want to check.