node.jsfirebase-realtime-databasefirebase-authenticationfirebase-admin

Firebase Admin SDK - Permission Denied with Service Account in Realtime Database


I'm trying to use the Firebase Admin SDK to access my Realtime Database from a Node.js environment ( also try via c#, but same result). Despite setting up the service account and initializing the Firebase Admin SDK, I'm still getting a PERMISSION_DENIED error when trying to read data.

Service Account Initialization:

const admin = require('firebase-admin');
var serviceAccount = require('.\\serviceAccountKey.json');
var credential =  admin.credential.cert(serviceAccount);
console.log('Credits:', credential);
try{
admin.initializeApp({
  credential: credential,
  databaseURL: "***",//have a normal url, just hide it
   databaseAuthVariableOverride: {
    uid: "admin"
  }
}
);
console.log("initS")
}
catch{
    console.log("fail")
}
const db = admin.database();
const ref = db.ref('/TEST_ADMIN/');

ref.once('value')
  .then((snapshot) => {
    const numChildren = snapshot.numChildren();
    console.log('Number of nodes:', numChildren);
  })
  .catch((error) => {
    console.error('Error fetching data:', error);
  });

Database Rules:

{
  "rules": {
    "DATA": {
      "$uid": {
        ".read": "auth !== null && (auth.uid === $uid || auth.uid === 'admin')",
        ".write": "auth !== null && (auth.uid === $uid || auth.uid === 'admin')"
      }
    },
    "Players": {
      "$uid": {
        ".read": "auth !== null && (auth.uid === $uid || auth.uid === 'admin')",
        ".write": "auth !== null && (auth.uid === $uid || auth.uid === 'admin')"
      }
    },
    "Promo": {
      ".read": "true"
    },
      "TEST_ADMIN": {
      "$uid": {
        ".read": "auth !== null",
        ".write": "auth !== null"
      }
    }
  }
}

Error Message

Error fetching data: Error: permission_denied at /TEST_ADMIN: Client doesn't have permission to access the desired data.

I have verified that the serviceAccountKey.json file is correct and properly referenced.

Despite these settings, the PERMISSION_DENIED error persists, which suggests that auth might be null during the request.

Furthermore, I can retrieve data from 'Promo' where there are no authorization restrictions

Steps Taken:

How can I resolve the PERMISSION_DENIED error and ensure that the Firebase Admin SDK correctly authenticates with the admin UID to access the Realtime Database? Are there additional settings or configurations I need to adjust in Firebase or in my Node.js setup?


Solution

  • Your rules provide read access to /TEST_ADMIN/$uid, so to the node of a specific user. But your code tries to read all of /TEST_ADMIN. Since you have no rules for /TEST_ADMIN, the read is denied.

    If you want to allow any signed in user to read all of /TEST_ADMIN, move the ".read" rule up to that level:

    "TEST_ADMIN": {
      ".read": "auth !== null",
      ".write": "auth !== null"
    }