3
votes

I have a set of Firebase Functions that works as an API for an application.

These Firebase Functions connect to the database with admin privileges as this:

const serviceAccount = require(`./config/xxx-firebase-adminsdk.json`);
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: DATABASE_URL,
});

I was able to create a custom token and I'm receiving/decoding it in the server but I cannot make use of the security rules because the Firebase function is authenticated with admin privileges.

Is there a way of impersonating the credentials or maybe pass a different user when accessing the database?

1

1 Answers

5
votes

You can initialize the admin SDK with user-level privileges as described in the documentation:

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://databaseName.firebaseio.com",
  databaseAuthVariableOverride: {
    uid: "the-user-id"
  }
}, "some-other-name");

"some-other-name" is required if you've already initialized the default instance. See initializeApp() for more details.

You obviously have to know the UID of the authenticated user in order to make this work. Also, it should be clear that you have to init the SDK every time you want to do something with a different user, which means you're going to have to init on every function call where the UID could be different.