Firebase custom token in NodeJS (fastify framework)

35 Views Asked by At

I would like to create a custom token from my fastify server.

Now, I am reading the following, exceptionally poor, guide: https://firebase.google.com/docs/auth/admin/create-custom-tokens

They have this (incomplete in my opinion) example:

const uid = 'some-uid';

getAuth()
  .createCustomToken(uid)
  .then((customToken) => {
    // Send token back to client
  })
  .catch((error) => {
    console.log('Error creating custom token:', error);
  });

The first thing I do not understand is where the method getAuth() comes from. There is zero explanation in the official documentation. My guess would be that it comes from the firebase-admin. However I do not understand how to use it.

The second non-sense thing, related to the above is when I created a project in firebase console I got the following:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "api_key",
  authDomain: "xyz",
  projectId: "xyz",
  storageBucket: "xyz",
  messagingSenderId: "000",
  appId: "0xyz",
  measurementId: "xyz0"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

However I do not understand how to use it in the firebase-admin.

Even if I do the following:

const admin = require('firebase-admin');
admin.initializeApp(firebaseConfig);

I get the message:

errorInfo: { code: 'auth/invalid-credential', message: 'Failed to determine service account. Make sure to initialize the SDK with a service account credential. Alternatively specify a service account with iam.serviceAccounts.signBlob permission. Original error: Error: Error while making request: getaddrinfo ENOTFOUND metadata. Error code: ENOTFOUND' },
codePrefix: 'auth'

Any help would be much appreciated as I have wasted a lot of time due to the incompleteness of the firebase documentation.

1

There are 1 best solutions below

0
Frank van Puffelen On

You're mixing the client-side SDK (firebase) and the server-side Admin SDK (firebase-admin), which is not a good idea.

To mint a custom token you (only) need the Admin SDK, so get rid of the other firebase dependency. Then initialize the SDK as described in the documentation, which means you provide it with administrative credentials (in one of the ways shown here) that allow it to (amongst others) mint a custom token.