Nadhas
Nadhas

Reputation: 5807

How to create Firebase Authentication custom token without service account json in nodejs?

I want to create a custom token without using a service account json. Tried the below config items: https://firebase.google.com/docs/auth/admin/create-custom-tokens#using_a_service_account_id

https://firebase.google.com/docs/auth/admin/create-custom-tokens#letting_the_admin_sdk_discover_a_service_account

and used the below code to generate a token

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

Getting the below error :

'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 metadata:80. Error code: ENOTFOUND'

Used the latest "firebase-admin" npm module.

Kindly advice.

Upvotes: 5

Views: 7520

Answers (4)

TheMrZZ
TheMrZZ

Reputation: 308

2022 Answer

In the latest firebase-admin version, simply providing serviceAccountId won't work. You also need to specify projectId:

admin.initializeApp({
  projectId: process.env.PROJECT_ID,
  serviceAccountId: process.env.SERVICE_ACCOUNT_ID,
})

If you don't, you will get the following error:

  errorInfo: {
    code: 'app/invalid-credential',
    message: 'Failed to determine project ID: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND'
  },

Upvotes: 6

Yanni TheDeveloper
Yanni TheDeveloper

Reputation: 406

You should initialize admin by passing your service account key(Download it from Firebase) to credential first. Use this code before calling admin.auth().

var serviceAccount = require('./ServiceAccountKey.json')

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

Upvotes: 2

Hiranya Jayathilaka
Hiranya Jayathilaka

Reputation: 7438

If your code is not running in a managed runtime in Google Cloud, you must either provide a service account JSON file or at very least the serviceAccountId app option.

admin.initializeApp({
  serviceAccountId: '[email protected]',
});

Upvotes: 6

andresmijares
andresmijares

Reputation: 3744

Short answer: You cannot, the sdk key is the only way to authenticate and authorize your app in order to grant permissions.

Long (not that long) answer: use a cloud function, if it is into your project, it will init it for you, so you don't have to use the key to instantiate the sdk

Upvotes: 0

Related Questions