Security Rules

Firebase Security Rules (basics) #

Deploying with the Firebase CLI #

Rules can be deployed with the help of Firebase CLI. This allows tracking rules with Git and simplifies tracking of rule update history.

For publicly exposed open-source apps, when tracking rules with a VCS (on GitLab, GitHub, etc.), consider keeping security rules in a separate private repository.

If a project had been previously initialized without some config options, the project configuration, firebase.json, can be updated manually to include addtional features.

The example below shows a simple config with storage (object storage) and firestore (database) features:

{
  "firestore": {
    "rules": "firestore.rules"
  },
  "storage": {
    "rules": "storage.rules"
  }
}

Firebase security rule files firestore.rules and storage.rules have their own format. For more details see the official docs:

Deploying the Firestore Database Config #

Here’s a slightly fleshed out firebase.json example for a specific database (when working on a multi-database Firebase project):

{
  "firestore": {
    "database": "non-default-database",
    "location": "database-region, e.g., asia-northeast1",
    "rules": "firebase.d/firestore.rules",
    "indexes": "firebase.d/firestore.indexes.json"
  }
}

To deploy only the firestore database rules and indexes run:

firebase deploy --only firestore

Deploying the Cloud Storage Config #

To deploy only the object storage security rules run:

firebase deploy --only storage

Sample Firestore Database Rules #

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {

    match /path/to/{docId} {
      // allow signed in users to read docs at the specific path
      allow read: if request.auth != null;

      // allow admins to write docs at the specific path
      allow write: if request.auth != null && request.auth.token.isadmin;
    }

  }
}

Sample Storage Rules #

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {

    match /public_user_content/{userId}/{allPaths=**} {
      // allow signed in users to read public files of any user
      allow read: if request.auth != null;

      // allow users to upload files under their unique public prefix
      allow write: if userId == request.auth.uid;
    }

    match /private_user_content/{userId}/{allPaths=**} {
      // allow users to read and write files under their private prefix
      allow read, write: if userId == request.auth.uid;
    }

  }
}