Configure the firestore security rules to allow users to only access their own data - efficiently

后端 未结 4 1804
庸人自扰
庸人自扰 2021-02-16 00:01

Using firestore with angularfire2 rc 2.

All is working very nicely in development with no effective security rules.

These are the no security rules - where the cli

相关标签:
4条回答
  • 2021-02-16 00:29

    The following setup worked for me (I've used allChildren as opposed to allSubcollection):

    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId}/{allChildren=**} {
          allow read, write: if request.auth.uid == userId;
        }
      }
    }
    

    allChildren will allow to read/write in any subcollections of a user document.

    More information on this wildcard matching is here

    0 讨论(0)
  • 2021-02-16 00:39

    I resolved this issue like this.

    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId} {
           match /{allSubcollections=**} {
            allow read, write: if request.auth.uid == userId;
          }
        }
      }
    }
    
    0 讨论(0)
  • 2021-02-16 00:48

    In my case, I needed the permissions for creating the user as well so the other solutions did not work for me. I had to also allow access to /users/{userId}. Here is my code:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId} {
          allow read, write: if request.auth.uid == userId;
          match /{allSubcollections=**} {
            allow read, write: if request.auth.uid == userId;
          }
        }
      }
    }
    
    0 讨论(0)
  • 2021-02-16 00:51

    The short answer is that {userId=**} results in userId being a path and not a string. This means that comparing it to request.auth.uid (which is a string) will fail. Instead, you'll likely want something like:

    service cloud.firestore {
        match /databases/{database}/documents {
            match /collectionA/{userId}/{allSubcollections=**} { 
                allow read, write: if request.auth.uid == userId;
            }
        }
    }
    

    This will guarantee that userId is a string, and then match the appropriate subcollections (note that again, allSubcollections will be a path).

    0 讨论(0)
提交回复
热议问题