Search code examples
node.jsfirebasefirebase-realtime-databasefirebase-security

How to add auth details to firebase request to access realtime database?


I am using the real-time database for my project and I have my security rules as follow:

{
 “rules”: {
 “.read”: “auth != null”,
 “.write”: “auth != null”
 }
}

Now I want to read and write the information to my database from the backend server and while doing that I want to authenticate the user before accessing the database. I will have only one user who will access the database and update the data. How do I do this using firebase authentication?


Solution

  • For server side applications, you can use Firebase Admin SDK that bypasses any security rules. If you want to allow only your server to access the DB, you can block public access by setting the rules to:

    {
      "rules": {
        ".read": false,
        ".write": false
      }
    }
    

    The Admin SDK can still access the database. However, do ensure that the server side function can be accessed only by authorized users and no API is exposed to public without any validation.


    If you want to use Client SDK then you'll have to login with Firebase Auth SDK before you can make requests to database and allow make sure security rules allow your user to read/write like:

    {
      "rules": {
        ".read": "auth.uid == 'your_uid'",
        ".write": "auth.uid == 'your_uid'"
      }
    }