Firestore rule to read collection

2019-08-25 03:00发布

问题:

Firestore rule to read collection overrides document rule to deny unauthorized access of other users data.

Here's my scenario, I'm getting the user information with the phone number associated by the Authentication and the Document in the database. I'm querying the whole /users collection with where clause and in the Firestore Rules I'm letting anyone to read /users collection, but I think this is insecure.

Javascript

const phone_number = firebase.auth().currentUser.phoneNumber // Example: "+5521988887777"
const usersRef = firebase.firestore().collection('users')

usersRef.where("phone_number", "==", phone_number).limit(1).get()
  .then(snapshot => {
    const doc = snapshot.docs[0]

Firestore Rules

service cloud.firestore {
  match /databases/{database}/documents {
    match /users {
      allow read;
    }
    match /users/{user} {
      allow read, write: if request.auth != null && request.auth.token.phone_number == resource.data.phone_number;
    }
  }
}

I'm trying to achieve a workaround to the issue, thanks.

回答1:

To correct the security rule I have removed the first condition to allow all reads (as commented above).

Working Firestore Rules

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{user} {
      allow read, write: if request.auth != null && request.auth.token.phone_number == resource.data.phone_number;
    }
  }
}