firebasefirebase-realtime-databasefirebase-security

How to Restrict Firebase Realtime Database `.write` Access to Only Specific Child Keys


I've been tried to made a rules in Firebase Realtime Database. So, i wants to allow .write if newData only has these two child which data1 and data1.

{
  "rules": {
    ".read" : false,
    "$user": {
      ".read": true,
      ".write": "newData.hasChildren(['data1', 'data2']) && !newData.hasChild('other')"
    }
  }
}

It succeed not allowed the newData that doesn't have neither of ['data1', 'data2']. But the problem is, it will also allowed every data that have both of ['data1', 'data2'] and more other child. In this part of rules as you can see !newData.hasChild('other') I've tried to select any other child as other without $ mark, turns out it didn't worked


Solution

  • Your rule only rejects the write of there is a child named other, which is not the use-case you're looking to implement.

    To allow writing data1 and data2 only, you need to define rules one level deeper:

    {
      "rules": {
        ".read" : false,
        "$user": {
          ".read": true,
          ".write": "newData.hasChildren(['data1', 'data2'])",
          "data1": { ".validate": true },
          "data2": { ".validate": true },
          "$other": { ".validate": false }
        }
      }
    }
    

    So now the data1 and data2 children are considered valid, but any other children (as indicated by the $other rule) are invalid/rejected.