Search code examples
javascriptfirebasegoogle-cloud-firestorefirebase-security

Firestore rules not allowing read given valid UID


I have written the following firestore rule to limit reads on the users collection by only allowing the request if the caller's UID matches the document ID. There is parity between the users collections' document ID and the UID in Firebase Authentication.

    function isAuthenticated() {
      return request.auth.uid != null;
    }

    // Users collection
    match /users/{userId} {
      allow read: if isAuthenticated() 
        && request.auth.uid == userId;
    }

I have a document in the collection with ID Eli90wRvWkfKcOfn1C4DBDqxQTz1. When hitting firestore with the same authentication user, I get the following error:

Failed read with uid check

If I remove the check for the request.auth.uid == userId, it results in this rule and a successful read:

    // Users collection
    match /users/{userId} {
      allow read: if isAuthenticated();
    }

enter image description here

The query that is being called is:

export const getUser = (uid: string) => {
  return db.collection('users').where('id', '==', uid).limit(1).get();
};

I've seen many people use the UID check in their rules but why isn't it working in my case?


Solution

  • Your security rules match this code:

    db.collection('users').doc(uid).get();
    

    So here we access a single specific documents, with the document ID being the UID of the user.


    If you instead want to query for the UID in a field in the document(s), you can secure that with these rules:

    match /users/{doc} {
      allow read: if resource.data.id === request.auth.uid;
    }
    

    So now the rules match your original code, and only allow reading documents where the value of the uid field matches the uid of the current user.