Reputation: 58
I have a program which on every page it loads my firebase credentials and initialises auth = firebase.auth(). Furthermore, I also include the auth.onStateChanged function to determine if there is any changes to the authentication state of the user.
However, upon attempting to retrieve information from the database (mainly on the refresh of my page), it says that:
Client doesn't have permission to access the desired data.
When I trying to retrieve data from a particular node, I have the rule "auth != null" and this doesn't work but when I change it too "auth == null" it does work. Hence, this implies that auth is not changing in the firebase database rules even though I have the auth.onStateChange function.
I am able to print the auth variable in the browser console and it is most definitely not null.
How do I go about fixing this issue on making sure that the auth is being established/connected before allowing the firebase security rules to check the auth variable?
main.js (client)
var config = {
apiKey: "X",
authDomain: "X",
databaseURL: "X",
projectId: "X",
storageBucket: "X",
messagingSenderId: "X",
appId: "X",
measurementId: "X"
};
firebase.initializeApp(config);
firebase.analytics();
var auth = firebase.auth();
auth.onAuthStateChanged(user => {
if (user) {
// code for signed in user
} else {
// code for not signed in user
}
});
index.js (server)
var firebase = require('firebase/app');
require("firebase/auth");
require('firebase/database');
require("firebase/firestore");
var admin = require('firebase-admin');
var config = {
apiKey: process.env.APIKEY,
authDomain: process.env.AUTHDOMAIN,
databaseURL: process.env.DATABASEURL,
projectId: process.env.PROJECTID,
storageBucket: process.env.STORAGEBUCKET,
messagingSenderId: process.env.MESSAGINGSENDERID,
appId: process.env.APPID,
measurementId: process.env.MEASUREMENTID
};
firebase.initializeApp(config);
admin.initializeApp({
credential: admin.credential.cert('./serviceAccountKeys directory'),
databaseURL: "X"
});
/*
using firebase commands to access firebase content such as:
- firebase.database().ref
*/
EDIT 1:
My query is "firebase.database().ref('db-bank/')"
and the database looks like this:
/db-bank/content1
The firebase rule is:
"db-bank": {
".read": "auth != null",
".write": false,
},
Upvotes: 0
Views: 1027
Reputation: 317322
Code that uses the Firebase Admin SDK on a backend is not affected by security rules. Read:
Rules only applies to client app code where a user is actually signed in.
Upvotes: 2