Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular + firestore: how to allow public read access to a document

I am a student developer trying out the new Firestore in my angular app and got stuck on the security rules.

what i'm trying to achieve:

display a firestore document in an angular view using template binding. the document should be view-able to non-authenticated users.

the problem:

if a non-authenticated user tries to view the page a permissions error occurs:

ERROR Error: Missing or insufficient permissions. at new FirestoreError (error.js:164)

the template file:

<p>{{ (item | async)?.name }}</p>

the component.ts file:

interface Profile {
   name: string;
}
...
private itemDoc: AngularFirestoreDocument<Profile>;
item: Observable<Profile>;
...
ngOnInit() {

   this.itemDoc = this.afs.doc<Profile>('profiles/0mlC8uWaKeArzk0sfIfX');
   this.item = this.itemDoc.valueChanges();
}

firestore rules:

service cloud.firestore {
   match /databases/{database}/documents {
     match /{document=**} {
        allow read, write: if request.auth != null;
     }
   }
}
like image 327
Jacky Brown Avatar asked Oct 05 '17 19:10

Jacky Brown


1 Answers

As you know, access to your Cloud Firestore data is controlled by Security Rules. When you get an "insufficient permissions error" that means your read or write has been denied by rules.

In your case you have these rules:

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

Translated roughly to english, these say "allow reading or writing to any document in the database as long as the user is signed in".

So if you're getting an error, it means the user is not signed in (request.auth == null).

So you have two options:

Option 1: Add Auth to Your App

You can add Firebase Authentication to your app. The simplest thing that would satisfy your rules would be anonymous authentication:

firebase.auth().signInAnonymously()
.then(function() {
   // You're signed in, reads will work
})
.catch(function(error) {
  // Handle Errors here.
  // ...
});

Option 2: Change Your Security Rules

If you want all users to be able to read all of the data in your app, you could open up the rules as follows:

service cloud.firestore {
   match /databases/{database}/documents {
     match /{document=**} {
      allow read: if true;
      allow write: if request.auth != null;
      }
   }
}
like image 61
Sam Stern Avatar answered Sep 27 '22 19:09

Sam Stern