Spotted a bug? Have a great idea? Help us make google.dev great!

Goals

In this codelab, you'll enhance a restaurant recommendation web app powered by Cloud Firestore.

What you'll learn

  • Use Firebase Authentication and security rules to secure Cloud Firestore data.

What you'll need

This codelab builds on the previous codelabs in this playlist. If you have not completed the previous codelabs, please do so before continuing here.

At the beginning of this codelab series, you set your app's security rules to completely open the database to any read or write. In a real application, you'd want to set much more fine-grained rules to prevent undesirable data access or modification.

  1. In the Firebase console's Develop section, click Database.
  2. Click the Rules tab (or click here to go directly to the Rules tab).
  3. Replace the defaults with the following rules, and then click Publish.

firestore.rules

rules_version = "2";
service cloud.firestore {
  match /databases/{database}/documents {

        // Restaurants:
        //   - Authenticated user can read
        //   - Authenticated user can create/update (for demo)
        //   - Validate updates
        //   - Deletes are not allowed
    match /restaurants/{restaurantId} {
      allow read, create: if request.auth != null;
      allow update: if request.auth != null
                    && request.resource.data.name == resource.data.name
      allow delete: if false;
      
      // Ratings:
      //   - Authenticated user can read
      //   - Authenticated user can create if userId matches
      //   - Deletes and updates are not allowed
      match /ratings/{ratingId} {
        allow read: if request.auth != null;
        allow create: if request.auth != null
                      && request.resource.data.userId == request.auth.uid;
        allow update, delete: if false;
        
        }
    }
  }
}

These rules restrict access to ensure that clients only make safe changes. For example:

  • Updates to a restaurant document can only change the ratings, not the name or any other immutable data.
  • Ratings can only be created if the user ID matches the signed-in user, which prevents spoofing.

As an alternative to using the Firebase console, you can use the Firebase command-line interface to deploy rules to your Firebase project. The firestore.rules file in your working directory already contains the rules above. To deploy these rules from your local file system (rather than using the Firebase console), run the following command:

firebase deploy --only firestore:rules

In this codelab, you learned how to secure data access with security rules.