Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

firebase_admin.initialize_app with databaseAuthVariableOverride

How backend (cloud function) may act with firebase as user instead admin access?

My code create firebase_admin.App object but during testing I see that the database is accessed not with the rights of the user I transferred.

backend = firebase_admin.initialize_app(credential=firebase_admin.credentials.Certificate(self.firebase_backend_account_info(project)))

userapp = firebase_admin.initialize_app(
credential=firebase_admin.credentials.Certificate(self.firebase_backend_account_info(self.project)),
name = str(time.time()),
options={'databaseAuthVariableOverride': {'uid': firebase_admin.auth.get_user_by_email(email = 'test@mydomain.com', app = backend ).uid}})
cli = firebase_admin.firestore.client(app = userapp)
cli.collection('Records').document('document').update({'123': 123}) # User have't access, this code can update document

0 1 288
1 REPLY 1

Hi @truboter,

Welcome to Google Cloud Community!

databaseAuthVariableOverride option to override the auth object used by your database rules. This means that only needed services could be accessed with limited privileges. Please check the sample code below:

var admin = require("firebase-admin");

// Fetch the service account key JSON file contents
var serviceAccount = require("path/to/serviceAccountKey.json");

// Initialize the app with a custom auth variable, limiting the server's access
admin
.initializeApp({
  credential
: admin.credential.cert(serviceAccount),
 
// The database URL depends on the location of the database
  databaseURL
: "https://[database-name].firebaseio.com",
  databaseAuthVariableOverride
: {
    uid
: "my-service-worker"
 
}
});

// The app only has access as defined in the Security Rules
var db = admin.database();
var ref = db.ref("/some_resource");
ref.once("value", function(snapshot) {
  console
.log(snapshot.val());
});

You may also want to set the admin SDK to act as an unauthenticated client by setting databaseAuthVariableOverride to null. Please check the sample code below:

var admin = require("firebase-admin");

// Fetch the service account key JSON file contents
var serviceAccount = require("path/to/serviceAccountKey.json");

// Initialize the app with a custom auth variable, limiting the server's access
admin
.initializeApp({
  credential
: admin.credential.cert(serviceAccount),
 
// The database URL depends on the location of the database
  databaseURL
: "https://[database-name].firebaseio.com",
  databaseAuthVariableOverride
: null
});

// The app only has access as defined in the Security Rules
var db = admin.database();
var ref = db.ref("/some_resource");
ref.once("value", function(snapshot) {
  console
.log(snapshot.val());
});

 You may refer to this documentation on Introduction to the Admin Database API for additional information.

Hope this helps.