Jahid Shohel
Jahid Shohel

Reputation: 1485

Firebase security rules for nodejs app

I am new to firebase. I have below given code -

var config = {
    apiKey: ".....",
    authDomain: "....",
    databaseURL: ".....",
    storageBucket: "...."
};

firebase.initializeApp(config);

function writeData(socialType, userName, name, message) {
   database.ref("/" + socialType + "/" + userName + "/").set({
       name: name,
       message: message
   });
}
writeData("fb", "Jhon", "booo1", "message1");

I wonder what should be the security rules for these kind(i mean access with api key, and there is no login. In fact on firebase nodejs library firebase.auth() the auth method doesn't exist). I don't want to allow anonymous access, I want to let access if there is a valid api key.

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

For this security rules I get permission_denied error. Which probably makes sense, because there is no auth since I am not authenticating, but accessing through api key.

NOTE: I don't want to use service account. I want to use api key to access (read/write) data

Upvotes: 0

Views: 1969

Answers (3)

xchrisbradley
xchrisbradley

Reputation: 503

You have to manually call the signInWithEmail method on each endpoint before you access a firestore collection. Its annoying but no workaround

return await firebase.auth().signInWithEmailAndPassword("###", "###").then(async () => {
    const user = await firebase.firestore().collection('user_info').doc('123').get()
    return user.data();
})

Upvotes: 0

Scott Buckstaff
Scott Buckstaff

Reputation: 618

The current issue with your rules is the:

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

Since it appears that you don't have a login. If the browser code has the proper api keys you can use the firebase anonymous auth to allow auth !== null to succeed.

Also in the future I would suggest using the !== over the != to improve reliabilty

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 599976

The API key just identifies your project to the Firebase servers. It does not authenticate your node.js process with Firebase, nor does it grant you permission to access any data in the database.

To authenticate from your node.js process with Firebase, you will have to follow one of the methods outlined in the documentation. All of these require the use of a service account in some way, either to directly access the database or to sign a custom token. This is simply the way Firebase Authentication works for server-side processes and there is no way to avoid it.

Upvotes: 1

Related Questions