0
votes

I'm experimenting with Firebase and curious about the security rules.

Let's say you have a firebase data set represented as simply as:

{
 "myNewData" : "Some String"
}

How could you write a rule so that only an object that gets written has the key name myNewData ?

I'm using the POST method and the data is structured in Firebase as follows:

-myFireBaseapp
  -someData
       -RandomFirebaseKey
           -myNewData
       -RandomFirebaseKey
           -myNewData

in the simulator I came up with

{
  "rules": {
      ".read":true,
        "$someData":{
       ".write":true,         
        ".validate": "newData.hasChild('myNewData')"
        }

    }
  }

which works in the simulator but not in postman.

POST

http://myfirebase.app.bucket/someData.json

   {
     "myNewData" : "Some String"
    }

Thanks for any info.

1
Show the minimal code that makes a REST call that fails.Frank van Puffelen
@FrankvanPuffelen REST call falls in postman. Added post call abovegregdevs
That request is not sending any data, so will not satisfy the the security rules. Without a minimal, complete example of what you're trying to do, it's hard to help. In this case for example, the two samples of you data structure vary on whether myNewData is a key of a value. I'll write up an answer that I hope is helpful.Frank van Puffelen
@FrankvanPuffelen actually the data I'm trying to send is above. It's just the key/value "myNewData" : "Some String"gregdevs
@FrankvanPuffelen when I remove the rules the request from postman works but of course , not ideal for my situation.gregdevs

1 Answers

1
votes

If you want your data to always have a key /someData/<anyKey>/myNewData with any value, you can validate that with

{
  "rules": {
      ".read":true,
      "someData":{
          "$anyKey": {
              ".write":true,         
              ".validate": "newData.hasChild('myNewData')"
          }
       }
   }
 }

If you squint your eyes, you can still see the path in these rules /someData/$anyKey/myNewData.

If you also want to validate that the value of myNewData is a string, you'd expand the rules to:

{
  "rules": {
      ".read":true,
      "someData":{
          "$anyKey": {
              ".write":true,         
              ".validate": "newData.hasChild('myNewData')",
              "myNewData": {
                  ".validate": "data.isString()"
              },
              "$other": {
                  ".validate": false
              }
          }
       }
   }
 }

I also added a "$other: { ".validate": false } to that last sample, which ensures that writes with any non-specified keys are rejects. So now the /someData/$anyKey can only contain a myNewData property that is a string.

This is all covered in the Firebase documentation on Using $ Variables to Capture Path Segments, which I highly recommend studying.