Search code examples
node.jsfirebase-adminfirebase-tools

Can I use the Auth Token of a user in Firebase CLI as credentials for Firebase Admin SDK?


If you're using firebase-tools as a module, you can get the refresh token of a user by

import { getGlobalDefaultAccount } from "firebase-tools/lib/auth.js";
const account = getGlobalDefaultAccount();
console.log(account.tokens.refresh_token);

I'm looking for a way to use the logged in user's(firebase-tools) refresh token as the credential for the Firebase Admin SDK. Something like:

import { initializeApp, refreshToken } from "firebase-admin/app";

const admin = initializeApp({
  credential: refreshToken(account.tokens.refresh_token),
});

I've tried running the code snippet above, but it looks like the refreshToken method interprets the account.tokens.refresh_token as a path to a file(maybe because it's a string). So I tried changing it to an object like so:

import { initializeApp, refreshToken } from "firebase-admin/app";

const admin = initializeApp({
  credential: refreshToken({
    refresh_token: account.tokens.refresh_token,
  }),
});

However, it's now raising an error stating that it's missing the client_secret and client_id properties, which the account object does not have. AFAIK, only service accounts have those.


Solution

  • So I figured out this was possible by using GOOGLE_APPLICATION_CREDENTIALS.

    Firebase Tools has a method called getCredentialPathAsync(), which from what I can tell, locates a credential file somewhere on your machine, and if there's none it generates a credentials file, then returns the path. You can set GOOGLE_APPLICATION_CREDENTIALS to the location of this file.

    import { getGlobalDefaultAccount } from "firebase-tools/lib/auth.js";
    import { getCredentialPathAsync } from "firebase-tools/lib/defaultCredentials.js";
    import { initializeApp } from "firebase-admin/app";
    
    async function main() {
        const account = getGlobalDefaultAccount() // Get the logged in account
        const credPath = await getCredentialPathAsync(account) // Get the path
        process.env.GOOGLE_APPLICATION_CREDENTIALS = credPath // Set the environment variable
        const firebaseApp = initializeApp({
            projectId: "PROJECT_ID",
        }) // Initialize the Admin SDK
    }
    
    main()