Home > Blockchain >  Configure Firebase RealTime Database security rules to read data securely
Configure Firebase RealTime Database security rules to read data securely

Time:06-07

I want to set secure rules for read the data from Firebase Realtime Database.

Authenticated user can only be able to access the data from database whose email address is matched with the stored key named email.

Here I am sharing the JSON Structure of the Realtime Database.

enter image description here

I have set the below read and write rules in the firebase database.

{
   "rules": { 
      "timestamp": {
          ".read": "data.child('email').val() == auth.token.email",
          ".write": "auth !== null",                            
      }
   }
}

With the above rules, I have test the read and write access with Firebase Rules Playground, but it seems not working. It is not allowing the authenticated user to read the data.

Note: I have already live the application with this RealTime Database JSON Structure. So, I do not want to change JSON structure

Can anybody help to me to solve this problem? Thanks in Advance.

CodePudding user response:

You need to adapt your rule as follows. As explained in the doc, you need to "use $ wildcard capture variables to point to sets of nodes at a level of the hierarchy".

{
   "rules": { 
      "$timestamp": {
          ".read": "data.child('email').val() == auth.token.email",
          ".write": "auth !== null",                            
      }
   }
}

In other words, your rule would be valid for the below timestamp node but not for the 1639531899477 or 1639531899488 ones:

- 1639531899477
   - date: ...
   - email: ...
- timestamp
   - date: ...
   - email: ...
- 1639531899488
   - date: ...
   - email: ...
  • Related