Karsh Soni
Karsh Soni

Reputation: 51

How to write security rules for firebase firestore when request data and in case where we have not used firebase authentication?

I have used Firebase Firestore for database storage. I had a scenario in which i need to manage users login and logout using phone number and OTP. and as Firebase authentication manages authentication using email id or if you want to use it with phone number every time you need to verify it using OTP which was not feasible for my application so, I created my own process of authentication in which I am using OTP authentication once and I store users data to the collection and then after when users login I directly check it from collection.

It is perfectly working now but as I am facing issues while changing security rules as I want to restrict user in reading database. But I don't know how to write it as I have found many solution till now but that all were having auth in request but as I am not using auth I may not have auth in request and could find it null.

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

I have given read and write access to all the collection so, anyone having key can access db but I want to restrict it using security rules and I have kind of found a way of restricting user when creating or updating as I will be getting resource when requesting for set or update but in case of reading or getting data it might not have resources as i am not passing any data . So please help me if you know how can I write such rules. Thanks In Advance...

Upvotes: 2

Views: 680

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

To allow only users that are authentication with Firebase access to data, you rules would be:

allow read, write: if request.auth.uid != null;

It isn't possible to do the same without Firebase Authentication, as the only way to pass data about the user into security rules is through Firebase Authentication.

If you have your own authentication mechanism, you can implement that as a custom provider within Firebase Authentication. In this approach you use server-side code to generate a Firebase token based on the information you have about the user, and the information from that token then becomes available in the security rules under auth.token.

Upvotes: 2

Related Questions