Kashif Kashif - 5 months ago 44
Swift Question

Swift: Firebase: How to ensure no one can access my db except my app

My Swift iOS app only uses Firebase Anonymous Login. I am concerned about security of my Firebase Database as apparently anyone can access or delete my data (through a browser etc?).

How can I secure my db so only my iOS app can access it?

I would have expected that the Firebase dashboard allow to generate an API key which I can embed in my app, but that does not seem to be the case.

Answer

You need to write security rules.

Anyone can see your URL, but security rules are how you dictate who has access to what pieces of data.

These rules act like annotations on your data structure and specify what constraints must be satisfied to allow the read or write.

Let's say you want to secure your database so only authenticated users can access the database. These are the default rules of the Realtime Database.

{
   "rules": {
     ".read": "auth != null",
     ".write": "auth != null"
   }
}

The auth variable a server side value that stores the current authenticated user. The rule checks to see if that variable has a value and therefore contains a logged in user.

I would have expected that the Firebase dashboard allow to generate an API key which I can embed in my app, but that does not seem to be the case.

The Firebase console will give you a secret key, which gives you full access regardless of rules. But if you embed this in your app then it is no longer secure. This is why you use authentication because the this creates tokens against that secret key for the specific logged in user.