Chapters

Hide chapters

Saving Data on Android

Second Edition · Android 11 · Kotlin 1.5 · Android Studio 4.2

Using Firebase

Section 3: 11 chapters
Show chapters Hide chapters

20. Securing Data in Cloud Firestore
Written by Harun Wangereka

In the previous chapters, you implemented all the features to the WhatsUp app except the most important one. You haven’t implemented any security rules, which means anyone has access to your data.

In this chapter, you’ll learn what security rules in Cloud Firestore exist and how to add them to your database to make your data safe.

What are Security Rules?

To set up your own security system you’d need to set up your own server that acts as a proxy between your mobile clients and the remote database. That server would need to process all the requests that are sent to the database and make sure that the client is accessing only the data that it is allowed to see.

Security rules handle security for you. You don’t need to set up your own security system.

How Security Rules Work

Security rules check the requests that are coming to the database and let through those that meet the criteria and reject the ones that don’t. So for example, if your database only allows writing data to the authenticated client and an unauthenticated user tries to write something to the database, then the database will reject that request.

Any request that comes to the database involves the document. You’re either trying to write the document to the database, read the document from the database, update an existing document, or something similar. Cloud Firestore will take a look at the security rules that apply to the document that your request contains. It will then run a set of tests that you wrote to determine if it will allow the request or not.

In a nutshell, security rules consist of two things:

  1. Specifying which documents you are securing.
  2. What logic you’re using to secure them.

Getting started

To see how the security rules look like open your Firestore Database in the console. Open the Rules tab at the top.

Cloud Firestore Security Rules.
Cloud Firestore Security Rules.

This is where you can see your current logic for the security rules. These are the default security rules that you added while creating Firestore Database. To be able to create your own rules, you need to understand the security rules syntax as in the image above.

You start by specifying your Security Rules versions as:

rules_version = 2

By default, version one of the security rules is the one used. So here, you’re specifying version two of the security rules. Using this version enables you to do more queries like collection group queries. This version also changes the following behavior of recursive wildcards:

  • Recursive wildcards match zero or more path items. In version one, the wildcards can’t match an empty path and must return one or more path items.
  • In version one, recursive wildcards can only be at the end of a match statement. In version two, you can place your wildcard anywhere in the match statement. Check the official documentation (https://firebase.google.com/docs/firestore/security/get-started#security_rules_version_2) to see the differences in the behavior.

On the next line you have a match block:

match /databases/{database}/documents

This line indicates the path that all the documents belong to. By default, all the documents belong to the /databases/{database}/documents path. {database} in curly brackets is a wildcard that matches any database name. You’ll learn more about wildcards later. Next, you have another match block:

match /{document=**} {
      ...
}

This is where you set the rules for the specific document by specifying the path to that document. match specifies the path to the document. document=** is a recursive wildcard that matches any document in the entire database.

In your current database, you have a posts collection that contains a specific post. The path to the specific post looks like this:

/databases/{database}/documents/posts/{postId}

If you only want to write a security rule that applies to that specific path you’d do it like this:

match /databases/{database}/documents {
    match posts/{postId} {
      ...
    }
}

From the above snippet, the first match block, As you can see, Firestore lets you nest the paths.

Now, your posts collection could have a subcollection. You could add a separate rule for that subcollection like this:

match /databases/{database}/documents {
    match posts/{postId} {
      match subcollection/{documentId} {
          ...
      }
    }
}

There is one important thing to notice when looking at these nested rules. The rules you add to the top-level match posts/{postId} do not apply to the inner match statements. Security rules in Cloud Firestore do not cascade.

Adding Security Rules

Your WhatsUp app is still not safe. You’ll add security rules next to restrict the access to data. Open Firestore Database in the console and tap Rules. Replace the exisiting rule with:

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

This rule allows read and write access on all documents for any signed-in user. The allow expression specifies when to allow the writing or reading of data.

When you’re done with writing the rules to the editor click Publish.

Firebase Security Rules Editor.
Firebase Security Rules Editor.

Usually, it takes a minute for the security rules to make an effect, but sometimes it can take up to 10 minutes. Before you start testing make sure you wait a couple of minutes.

Testing the Security Rules

Firestore has the Rules Playground which you can use to test your rules. You’ll be using the Rules Playground to test the rule you’ve created.

Security Rules Playground.
Security Rules Playground.

Click the Data tab, open posts collection and copy the ID of one post. Go back to Rules and tap the Up arrow in the Rules Playground section. This opens the Rules Playground window.

Next, do the following:

  1. Under the Simulation type field leave it set to get.
  2. Under the Location field enter the path to the specific post. In my case the path looks like this:
posts/posts/FNlxMWV6kZUgyr9vPFv8

The posts/FNlxMWV6kZUgyr9vPFv8 is the ID of the post. Replace that value with the ID you copied earlier.

Leave the Authenticated switch in the inactive state.

Now, tap Run. You should see an error message:

Security Rules Failure.
Security Rules Failure.

Your request didn’t succeed because you simulated an unauthenticated request. The Rules Playground shows you the rule which your request doesn’t meet and shows you the line.

Now change the Authenticated switch to an active state. Leave the authentication fields that appear with their default values, and tap Run again.

Security Rules test request is successful.
Security Rules test request is successful.

Your request is now successful since it meets all the conditions in your rules. Now all users that want to read and write to your database have to be authenticated. It prevents unauthorized reads and writes which at times can be from unwanted parties and can increase your usage and cost.

Monitoring Security Rules

Firebase also provides statistics for your set rules. You can access your rules data by tapping the Monitor rules tab which is next to the Edit rules tab.

The rules graph.
The rules graph.

From this, Firestore provides the following information:

  • Total allows. This is the number of reads and writes for your apps and users who meet your set criteria.
  • Total denies. Number of reads and write denials for your apps or users.
  • Total errors. The number of errors encountered in your rules.

There’s a graph for the statistics too.

Key points

  • Security rules check the requests that are coming to the database. The rules let through those that meet the criteria and reject the ones that don’t.
  • Security rules consist of two things. One is specifying which documents you are securing. The second thing is what logic you’re using to secure them.
  • In the Rules tab in the Firebase Console, you can see your current security configuration.
  • match statement specifies the path to the document.
  • allow expression specifies when to allow the writing or reading of data.
  • Security rules in Cloud Firestore do not cascade.
  • Cloud Firestore provides the Rule Playground feature that you can use to test your rules.

Where to go from here?

In this chapter, you learned the basics of the Cloud Firestore’s Security rules. Your WhatsUp app now only allows authenticated users to access the data.

To learn more about writing conditions, structuring and testing Security rules check out the official guidelines: https://firebase.google.com/docs/firestore/security/rules-structure.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.