reckoner
reckoner

Reputation: 2981

Angular app not able to access Firestore database?

I have an angular app with appropriate firebaseConfig that has the apiKey correctly configured. When the app is initialized it is supposed to go to the corresponding Firestore and collect the email addresses there and store them for later user authentication. The problem is that the app is unable to do this unless there is a user logged in. This is confusing because I thought that the app could access the Firestore database without having someone already authenticated. The only workaround I have been able to come up with is to set the Firestore rules to allow global read access. That way, when the app starts, it is guaranteed to have access to the database and emails therein.

What am I missing here?

Upvotes: 0

Views: 274

Answers (2)

Peter Haddad
Peter Haddad

Reputation: 80952

If your security rules are like this:

// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

Then only if the user is authenticated they can access the data. You can change your rules to the following:

// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }

        match /{collectionName}/{docId} {
      allow read: if collectionName == 'emailCollection';
    }
  }
}

This way if the user is authenticated then they can access all the documents, and if collection name is equal to emailCollection then a none authenticated user can access it.

https://firebase.google.com/docs/firestore/security/rules-structure#overlapping_match_statements

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317958

You're not missing anything. If you want users to be able to query Firestore collections without being authenticated ahead of time, that collection is going to need full public read access. It's not possible to write security rules that limit access to the database to a particular app or web site.

Upvotes: 0

Related Questions