How to Secure Your Firebase Project
May 13, 2021 - 3 min read | 1,820 views
disclaimer: This is not by any means to be the best practice guide of using firebase in every project. Every project has its own needs and specifications. This guide may not be suitable with your needs.
Do you develop apps using Firebase? If so, we should know that our firebase configs will be exposed to the client (especially for web clients). Then what's the deal? Many possibilities can be happened and prevented. So many articles already covers on how to secure our firebase project by using security rules, authentication check, etc. I usually define my security rules using a package named @jahed/firebase-rules
. But how about preventing someone from making their own client and use our exposed firebase configs to do some shady stuffs towards our realtime database?
Apply Restrictions to the API Key
Every firebase project is a GCP (Google Cloud Platform) project, so we can go to Google Cloud console to configure further our firebase project. We can restrict the API key even though it is exposed. Just follow these steps:
- Go to https://console.cloud.google.com/apis,
- Select the desired firebase project,
- Go to
Credentials
menu, - Look for
API Keys
section, select the API key which has...(auto created by Firebase)
, - You will be directed to a page called
Restrict and rename API key
, go toApplication restrictions
section, selectHTTP referrers (web sites)
, add your production web client domain inWebsite restrictions
section. Don't addlocalhost
if you intend to use the firebase project for production. - Hit the
save
button to apply changes.
Voila! Your API key already restricted!
Use Different Firebase Project for Local Development
Now that we already apply restrictions to our API key, how about our local development (localhost
)? Well, we can just create a new firebase project which will be used for our local development.
Special Case: Develop Hybrid Mobile App Using Ionic
When developing hybrid app using ionic, chances are we gonna use the same firebase configs for Web and Android / iOS build (firebase web configs). Even though we made several firebase web configs, the API key will remain the same. If we apply restrictions to the API key to be only accessible for certain domain, then the API key won't be usable for the mobile build. Fortunately, there is a workaround for this. We can just create a new API key which don't have any domain restrictions just for our mobile build (the API key can't be easily accessed by the user anyway for Android / iOS build). So, we can use the same firebase configs for our web and mobile builds, but having different API key. Just go to https://console.cloud.google.com/apis/credentials (make sure you already select the corresponding project first), then just create a new API key which will be used for your mobile apps.
References
- Defining Firebase security rules
- Restrict API key