Starting with Security Rules on Cloud Firestore

0 Comments

With Cloud Firestore Security Rules, you can focus on building a great user experience without having to manage infrastructure or write server-side authentication and authorization code.

Security rules provide access control and data validation in a simple yet expressive format. To build user-based and role-based access systems that keep your users' data safe, you need to use Firebase Authentication with Cloud Firestore Security Rules.

You can find your security rules in the Rules tab in the Cloud Firestore section of the Firebase Console.

firestore-security-rules01

Security Rules

To start securing our database we need to understand how the security rules work, let’s take a look at the default ones that come when you create the app.

Below are some examples of basic rule sets. While these rules are valid, they are not recommended for production applications:

Auth Required

// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

Deny All

// Deny read/write access to all users under any conditions
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

Allow All

// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

The {document=**} path used in the examples above matches any document in the entire database. Continue on to the guide for structuring security rules to learn how to match specific data paths and work with hierarchical data.

Follow below the final example after rules change using Auth Required by sample:

firestore-security-rules02

firestore-security-rules03

Use the Firebase CLI

You can also deploy rules using the Firebase CLI. Using the CLI allows you to keep your rules under version control with your application code and deploy rules as part of your existing deployment process.

// Set up Firestore in your project directory, creates a .rules file
firebase init firestore

// Edit the generated .rules file to your desired security rules
// ...

// Deploy your .rules file
firebase deploy --only firestore:rules

References:

Other tips about Firebase

Our Ionic + Firebase Starter

Comments