Search code examples
fluttergoogle-cloud-firestorefirebase-security

Flutter Firestore Security Rules


I've been trying to get the Firestore rules to play nice for a while now and every time I think I get them right, another portion stops working for some reason.

I'm trying to have some simple rules, if you made the document that document and any child documents or collections, you can create, edit and delete them. I thought this was pretty simple but alas I keep getting permission denied errors.

Rules:

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

When doing just the match /users/{userId} I was able at one time able to create user documents but I couldn't create child documents or colletions.

When doing just the match /users/{userId}/{document=**} I could no longer create users but any existing users I could add child documents and collections and do everything expected.

This combination of both rules doesn't seem to work either.

I keep getting [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation. when I try to create a user with this statement:

    await FirebaseFirestore.instance.collection('users').doc(googleUser.uid).set(
      {
        'created': now,
        'lastLogin': now,
        'name': name,
        'email': email,
      },
    );

Now nothing works. I deleted all my authentication accounts and my Firestore data and wanted to start over but it simply will not create the data in Firestore.

Any suggestions would be greatly appreciated as I'm going in circles and nothing is working anymore which is extremely frustrating as it did at one point but no longer does.

edit All of my testing is being done on a real Android phone.


Solution

  • After walking away from my computer and thinking more, I figured out what it was. My App Check debug token changed somehow.

    Once I added the new value from the debug console everything started working again.

    I'll leave this answer here in case this saves anyone else some headaches in the future!

    Edit: Additionally, ones App Check debug token will change anytime you clear storage on your app on the device. Which is why mine was changing.