How to setup Firestore security rules correctly

2019-07-18 09:53发布

Though it looks simple, I am still struggling to setup some basic Firestore rules, which are not working as expected.

For scenarios and queries posted below, this database is used:

Database Screen

Scenario 1

Am not able to figure out database name? I thought it's restaurants, but with this assumption, below code didn’t work, and getting PERMISSION_DENIED exception:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if database == "restaurants";
    }
  }
}

Scenario 2

Collection restaurants have 10 documents, as appearing in above screen, I have hard coded those 10, and allowed them to read and write as below, but its not working, and getting same PERMISSION_DENIED exception:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {

     allow read : if document in ['2uFMIc2BSH6oslxEABpB','8GMNVxVUb1HzRAk2QmmX',
      'AryyMURod8AeWAfBVavF','AvnpKGMeUWDSfowFLpwa','H0qi7gI8WmSVobu19G49',
      'H2xhfoj0Rn75BH9nnbuI','NRfgppqWRfj3DtHDlft4','R9gZ0hTxCPXwSeV2prNV',
      'YgXXwndeIfZx6rUhdlc4','v22FlL7LBBY851N8sIvQ'] ;

      allow write : if document in ['2uFMIc2BSH6oslxEABpB','8GMNVxVUb1HzRAk2QmmX',
      'AryyMURod8AeWAfBVavF','AvnpKGMeUWDSfowFLpwa','H0qi7gI8WmSVobu19G49',
      'H2xhfoj0Rn75BH9nnbuI','NRfgppqWRfj3DtHDlft4','R9gZ0hTxCPXwSeV2prNV',
      'YgXXwndeIfZx6rUhdlc4','v22FlL7LBBY851N8sIvQ'] ;


    }
  }
}

These 2 may not be very practical scenarios, but its more for my understanding.

1条回答
ら.Afraid
2楼-- · 2019-07-18 10:32
  1. In your first example, database is the name of your database, which is probably something like "(default)".

  2. In your second example, document is going to be the full path of your document; that's what that =** wildcard does -- it's a "everything else in my path" kind of wildcard. So it'll equal something like restaurants/2uFMIc2BSH6oslxEABpB

If you want to create a rule that says, "A user can read any document in my restaurants collection" you want something like this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /restaurants/{restaurantID} {
      allow read, write: if true;
    }
  }
}

If you want to do something interesting with the document ID of your individual restaurants, you probably want to do something more like this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /restaurants/{restaurantID} {
      allow read, write: if restaurantID == '2uFMIc2BSH6oslxEABpB; ;
    }
  }
}
查看更多
登录 后发表回答