javaandroidfirebase-realtime-databasefirebase-authenticationfirebase-security

How to set the read and write rules for a specific user in Firebase Realtime Database?


In my app I'm using Firebase authentication, and I also have an entry in the Firebase Realtime Database where I store other user information, like, full name, age, gender, etc. What I want to do is to connect the authenticated user to its user information in Firebase Realtime Database, and, in the rules, to only allow the user to read and write to his own user information in the Firebase Realtime Database.


Solution

  • Assuming that you a database schema that looks like this:

    Firebase-root
       |
       --- users
             |
             --- $userId
                  |
                  --- fullName: "John"
                  |
                  --- age: 22
                  |
                  --- gender: "male"
    

    To grant read/write access to the owner of the user account whose UID exactly matches the key ($userId), please use the following rules:

    {
      "rules": {
        "users": {
          "$userId": {
            ".read": "$userId === auth.uid",
            ".write": "$userId === auth.uid"
          }
        }
      }
    }