How to let specific API to run write/read requests

2019-08-25 09:11发布

问题:

Today I have the following rule on my firestore:

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

I can't execute requests from my API since it's not sign in (is there any way to auth through CLI only?). But I want to make sure that only my API make these requests.

Is there any way to add a specific header on my request and validate it on firebase rules?

If this is not the best approach, which one would be?

Context: - Using auth through google provider only.

回答1:

only my API make these requests

This is not possible with a Cloud hosted API like this. Since any client must be able to make such calls, all configuration information must be present in the client that you ship to your users. And that means that a malicious user can take that configuration data and make their own (equivalent or very different) calls.

Adding a custom header (if possible) would also not help, as they could just as easily get that header and use it in their own requests. So while there are good use-cases for adding additional data to the request, added security isn't one of them.

What you can (and should) do is validate that any data written to your database conforms to the business requirements of your app. Don't rely on the client-side code doing the right thing, but validate in your security rules that the incoming data is valid.

For more information, see:

  • the documentation on validating data in security rules
  • the video with 5 tips to secure your app
  • this excellent sample of validating data on AngularFirebase.com
  • and this previous question on the topic: How do I prevent un-authorized access to my Firebase Database?. While it is about the Firebase Realtime Database, the logic in the accepted answer applies to all Firebase products.