Ad

Firebase Security Rules To Specific Collection?

I have three collections, Collect 1 and Collection 2 that can only be read by authenticated users. The third Collection is Users which only authenticated users can read, write, update and delete but only the document with their respective UID. The current rules are applied for all the collection. Current security rules are:

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

Answer

I just want to add some detail or example here. In this rule, user's UID is stored as document ID.

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

I have done some testing code in local emulator:

firebase.firestore().doc('/users/'+user.uid).get().then(() => {
                console.log("user self path granted")
            }).catch(() => console.log("user other path deny"));
            
firebase.firestore().doc('/users/other').get().then(() => {
                console.log("user other path granted")
            }).catch(() => console.log("user other path deny"));
            
firebase.firestore().doc('/collection1/tCa4m3nGNjX4s3i1Uvc7').get().then(() => {
                console.log("collection1 path granted")
            }).catch(() => console.log("collection1 path deny"));
            
firebase.firestore().doc('/collection2/tCa4m3nGNjX4s3i1Uvc7').get().then(() => {
                console.log("collection2 path granted")
            }).catch(() => console.log("collection2 path deny"));
            
firebase.firestore().doc('/collection3/OvGk404uSdMFQAwN1qoA').get().then(() => {
                console.log("collection3 path granted")
            }).catch(() => console.log("collection3 path deny"));

Data structure in Firestore

Output

user self path granted
user other path deny
collection1 path granted
collection2 path granted
collection3 path deny
Ad
source: stackoverflow.com
Ad