Search code examples
firebase-realtime-databasefirebase-authenticationfirebase-security

Security rules of realtime database doesn't work


I have a firebase realtime database as below: enter image description here

The key for each user is the uid of the authenticated user. enter image description here

Following the security rules tutorial, I created a simple security rule for authenticated users who have the correct User UID to access the users information. enter image description here

Part of the Javascript code to access the realtime database is:

fireusers = firebase.database().ref('/users');     

this.fireusers.orderByChild('identifier').equalTo(this.email).once("value").then((snapshot) => {
         var temp = snapshot.val();
         for (var tempkey in temp) {
             this.globalvar.userName = temp[tempkey].name
             this.globalvar.userCompany = temp[tempkey].company
         }
})

But the access is denied, and the error log is:

ERROR Error: Uncaught (in promise): Error: permission_denied at /users: Client doesn't have permission to access the desired data.
Error: permission_denied at /users: Client doesn't have permission to access the desired data.

Can you please help for solving this problem?


Solution

  • Your code (that you didn't share) is trying to read the /users node. Your rules don't grant anyone access to that node, so the read gets rejected.

    It is important to realize that Firebase security rules don't filter data, but instead merely check whether the code is trying to access any more data than it is allowed. And in your case it does, so it gets rejected.

    To read the data, try to only read the path for the current user's UID: /users/$uid.

    Also see: Restricting child/field access with security rules