Skip to content Skip to sidebar Skip to footer

In Firebase - How To Generate An Idtoken On The Server For Testing Purposes?

I want to test a a cloud function that creates users. In normal cases, inside the browser i generate an idToken and i send it to server via headers: Authorization : Bearer etcIdTo

Solution 1:

From Exchange custom token for an ID and refresh token, you can transform a custom token to an id token with the api. Hence, you just have to generate a custom token first from the uid, then transform it in a custom token. Here is my sample:

const admin = require('firebase-admin');
const config = require('config');
const rp = require('request-promise');

module.exports.getIdToken = async uid => {
  const customToken = await admin.auth().createCustomToken(uid)
  const res = awaitrp({
    url: `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=${config.get('firebase.apiKey')}`,
    method: 'POST',
    body: {
      token: customToken,
      returnSecureToken: true
    },
    json: true,
  });
  return res.idToken;
};

Solution 2:

L. Meyer's Answer Worked for me.

But, the rp npm package is deprecated and is no longer used. Here is the modified working code using axios.

const axios = require('axios').default;
const admin = require('firebase-admin');
constFIREBASE_API_KEY = 'YOUR_API_KEY_FROM_FIREBASE_CONSOLE';

const createIdTokenfromCustomToken = async uid => {
  try {
    const customToken = await admin.auth().createCustomToken(uid);

    const res = awaitaxios({
      url: `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=${FIREBASE_API_KEY}`,
      method: 'post',
      data: {
        token: customToken,
        returnSecureToken: true
      },
      json: true,
    });

    return res.data.idToken;

  } catch (e) {
    console.log(e);
  }
}

Solution 3:

curl 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=<FIREBASE_KEY>' -H 'Content-Type: application/json'--data-binary '{"email": "test@test.com","password":"test","returnSecureToken":true}'

If this curl doesn't run, try running the same thing on Postman. It works!

Post a Comment for "In Firebase - How To Generate An Idtoken On The Server For Testing Purposes?"