Martin Müsli
Martin Müsli

Reputation: 1159

How to secure Firebase by checking for correct userID in the "official" Authentication database

I have users, registered with the EMail function of Firebase Authentication. Only authenticated users should write to my Firestore database.

My rule (from the documentation):

allow write: if request.auth != null;

allows access to every request where there is an non-null auth-object. This doesn't seem to be very secure. As you could just make a request with any auth = {something: "hacker"} object.

So, to avoid this problem. How do I check if the given request.auth.uid is actually the one from the Firebase Authentication service?

Upvotes: 1

Views: 83

Answers (2)

Kundan
Kundan

Reputation: 1952

These set of rules worked for me.

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

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

The request.auth variable is populated by Firebase automatically on the server, based on the ID token that is sent along from the client with each request. Minting an ID token for a given Firebase project, requires that you have access to the administrative credentials for that project.

This means that, as long as you ensure that you don't share the administrative credentials for your project publicly, nobody can inject their own information into the ID token, and this the request.auth object in your database is actually secure from tampering.


The rule in your question limits who can write data, as the user will need to be signed in to Firebase Authentication to be able to write. You'll typically also want to limit what the user can do, both by controlling the access (for example, only letting them access their own data), and by validating the data that they write.

Upvotes: 2

Related Questions