Last updated on April 8th, 2018 |
We are going to start preparing our app to go public, so the first thing we will need to do is update our security rules on the server, we do not want people connecting to the app and having access to someone else’s data.
Firebase Database Security Rules
There’s a comprehensive guide to security rules in Firebase Docs, and I have kept them simple for this post because I do believe that if you structure your data correctly, they do not need to be hard.
So, to structure your security rules, you will need to go to your firebase console:
console.firebase.google.com/project/YOURAPPNAMEHERE/database/data
By default the rules are there to allow access to only authenticated users:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
We need to set them, so it also checks that the user trying to access the information is the correct user, for our example let’s secure the users/userId
node so that only the owner can access it.
{
"rules": {
"users": {
"$uid": {
".read": "auth != null && $uid === auth.uid",
".write": "auth != null && $uid === auth.uid"
}
}
}
}
There we are saying that under the users
node there’s going to be a variable called uid
when you add the $ sign in here, it takes the value as a variable.
And we are saying that for a user to have read or write permissions to that node, their auth.uid
needs to match the $uid
variable.
In here auth is a variable that holds the authentication methods/properties.
There we ensure that only the user who owns the data can write/read it.
Storage Security
You should also set up rules for Firebase Storage, that way you can protect your users’ files.
You will need to go to:
console.firebase.google.com/project/YOURAPPGOESHERE/storage/rules
Identifying your user is only part of security. Once you know who they are, you need a way to control their access to files in Cloud Storage.
Cloud Storage lets you specify per file and per path authorization rules that live on our servers and determine access to the files in your app. For example, the default Storage Security Rules require Firebase Authentication to perform any read or write operations on all files:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Data Validation
Firebase Security Rules for Cloud Storage can also be used for data validation, including validating file name and path as well as file metadata properties such as contentType
and size
:
service firebase.storage {
match /b/{bucket}/o {
match /images/{imageId} {
// Only allow uploads of any image file that's less than 5MB
allow write: if request.resource.size < 5 * 1024 * 1024
&& request.resource.contentType.matches('image/.*');
}
}
}
If you want to take a deeper dive on Ionic + Firebase you should go through my FREE course: Build your first Firebase powered Ionic app.