Skip to content

[FR] Verifying emulated ID Tokens and creating session cookies only works in the Functions Emulator #2764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
favsss opened this issue Oct 30, 2020 · 43 comments

Comments

@favsss
Copy link

favsss commented Oct 30, 2020

[REQUIRED] Environment info

firebase-tools: 8.14.1

Platform: Windows 10

[REQUIRED] Test case

Currently emulating a scenario where a signed in user sends userToken from frontend and backend decoded this token and retrieves uid for fetching data from database.

const firebase = require('firebase/app');
require('firebase/auth');

const config = require('./config/firebaseConfig.json');

const firebaseConfig = {
  apiKey: config.apiKey,
  authDomain: config.authDomain,
  databaseURL: config.projectId,
  projectId: config.projectId,
  storageBucket: config.storageBucket,
  messagingSenderId: config.messagingSenderId,
  appId: config.appId,
  measurementId: config.measurementId
};

firebase.initializeApp(firebaseConfig);
firebase.auth().useEmulator("http://localhost:9099/");

const serviceAccountKey = require('./config/serviceAccountKey.json');

const admin = require('firebase-admin');

const databaseUrl = `http://localhost:9000/?ns=${config.projectId}`;
admin.initializeApp({
  credential: admin.credential.cert(serviceAccountKey),
  databaseURL: databaseUrl
});

const perform = async() => {
  const email = "[email protected]";
  const password = "password";
  await admin.auth().createUser({
    email: email,
    password: password
  });

  await firebase.auth().signInWithEmailAndPassword(email, password);
  const userToken = await firebase.auth().currentUser.getIdToken();

  // code fails here where admin is supposed to successfully verify id token
  await admin.auth().verifyIdToken(userToken);
};

perform();

[REQUIRED] Steps to reproduce

make sure that the following node packages are installed and firebase emulators for auth, firestore, and database are enabled:

 npm install -g firebase-tools
 npm install --save firebase
 npm install --save firebase-admin

[REQUIRED] Expected behavior

The userToken is decoded properly so that uid is extracted from the token for fetching data.

[REQUIRED] Actual behavior

It fails with Firebase ID token has no "kid" claim. The code is working normally except when using emulator.

WARNING: You are using the Auth Emulator, which is intended for local testing only.  Do not use with production credentials.
(node:24084) UnhandledPromiseRejectionWarning: Error: Firebase ID token has no "kid" claim. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
    at FirebaseAuthError.FirebaseError [as constructor]
@mjroeleveld
Copy link

I'm running into this as well. I can't verify idTokens created by the emulator.

@samtstern
Copy link
Contributor

@favs-sama where are you running the admin code?

Right now verifyIdToken() for auth emulator tokens only works inside the Functions emulator. This is out of a concern for security, short-circuiting verifyIdToken() is obviously dangerous if it accidentally happens in production so right now we only allow it in the Functions emulator, which we can control fully.

@favsss
Copy link
Author

favsss commented Oct 30, 2020

@samtstern originally i'm running the admin code verifyIdToken() in a backend prehandler function for handling user authorization; so, no i'm not running this inside a firebase function. although is there any other way to approach this kind of testing if currently verifyIdToken() for auth emulator is only accessible via functions emulator?

@samtstern
Copy link
Contributor

@favs-sama yeah right now the only way to test this is inside the Functions emulator. We do want to change this eventually but it requires us to build in a more secure version of verifyIdToken() that would be less dangerous to your server in the event of a configuration mistake!

So for now I'll consider this a feature request.

@malcolmdeck
Copy link
Contributor

I've created b/172262218 to track this feature request internally

@ricardoatsouza
Copy link

Also running into this. Will be watching this issue.

@samtstern samtstern changed the title Using Firebase Authentication emulator fails to decode userToken from signed in user Verifying emulated ID Tokens and creating session cookies only works in the Functions Emulator Nov 5, 2020
@samtstern
Copy link
Contributor

I changed the name of this issue to more accurately reflect the feature request and include the use case from #2770

@AudunWA
Copy link

AudunWA commented Nov 5, 2020

I'd need to verify/decode the token with the emulator as well.

@daniel-tucano
Copy link

@favs-sama where are you running the admin code?

Right now verifyIdToken() for auth emulator tokens only works inside the Functions emulator. This is out of a concern for security, short-circuiting verifyIdToken() is obviously dangerous if it accidentally happens in production so right now we only allow it in the Functions emulator, which we can control fully.

I was planing to use the auth emulator to do tests without some weird workarounds required at the moment. I think that this behaviour (or at least some imitation of it) should be implemented for testing purposes. This also should have been mentioned at the documentation, would have saved me some time haha

@MeghaB MeghaB changed the title Verifying emulated ID Tokens and creating session cookies only works in the Functions Emulator [FR] Verifying emulated ID Tokens and creating session cookies only works in the Functions Emulator Nov 16, 2020
@patelnets
Copy link

Does anyone have a workaround for this?

@mjgerace
Copy link

@samtstern just voicing my support for this - many, many engineers do not use https.callable and instead opt for express setups, myself included. Not being able to support this means that we have a lack of ability to test our client-server interaction through integration tests.

From an engineering perspective, shouldn't this be as easy as disabling the 'kid' claim check when a certain envvar is set to true (IE, an envvar that is only set when firebase is running emulator mode)? I don't particularly understand why this would be hard to facilitate.

@samtstern
Copy link
Contributor

@mjgerace we know how to do this, but we're being extra careful about security. If your production server ever got into a situation where it thought it should disable/skip ID token verification then you'd have a big problem!

In order to have something in time for the launch of the Auth Emulator we compromised on a simple solution in the Node.js Admin SDK that is only enabled inside the Functions emulator. We are actively working on a longer-term solution that we're happier with and when we finish it we will bring it to all of our Admin SDKs (Node, Java, Go, Python, etc) so that you can develop on your own server.

@mjgerace
Copy link

mjgerace commented Nov 25, 2020

@samtstern this makes total sense - is there any timeline for this work? In the meantime, would it be bad for our team to set an env var (FIREBASE_EMULATOR=1 yarn jest {test_file}) and otherwise workaround the issue in my actual auth middleware?

So long as I can modify the verifyIdToken() function, I could manually implement my suggested fix while I work on testing. Our app isn't in production and this would allow us to write tests without doing anything overly risky.

@samtstern
Copy link
Contributor

@mjgerace we never offer timelines but this is something we're actively working on, it's not on the backlog. If you want to work around this issue on your own server and you're confident you know how, go for it!

@daniel-tucano
Copy link

Does anyone have a workaround for this?

At the moment when I'm running tests i change NODE_ENV environment variable to "test" and, based on that, change the auth token checking code to use the decode function from 'jsonwebtoken' module instead of firebase auth

@nicoburns
Copy link

@samtstern Couldn't this be as simple as checking for the presence of the FIREBASE_AUTH_EMULATOR_HOST environment variable? If you are using the auth emulator then it is safe to assume that you're not running in production (or you already have some very serious security issues).

@samtstern
Copy link
Contributor

@nicoburns we use the presence of that environment variable to redirect any outbound HTTP requests the Admin SDK makes to the Auth API. However verifying ID Tokens and creating session cookies are mostly local operations that do not touch the Auth API. So changing how they work just based on the presence of an env var would create the possibility of someone remotely short-circuiting your Admin server's security, something we really really want to avoid.

We're working on changes to how the Admin SDK handles these operations that will make it safer to fix this issue.

@tudor07
Copy link

tudor07 commented Feb 5, 2021

any updates on this?

@jasonho-lynx
Copy link

The error seems to also happen despite using the Functions emulator - do you mean that it only works if verifyIdToken is used within a https.callable? I'm using Express in my Cloud Function instead

@yuchenshi
Copy link
Member

@athomasoriginal firebase/firebase-admin-java#493 tracks the Java Admin SDK feature request.

@vajahath
Copy link

vajahath commented Apr 6, 2021

@yuchenshi Let's update the Firebase documentation. It still says

When running in any other environment, such as Cloud Run or your own server, these tokens will be rejected by the Admin SDK.

ref: https://firebase.google.com/docs/emulator-suite/connect_auth#id_tokens

@yuchenshi
Copy link
Member

@vajahath We're updated the docs. Thanks for the heads up.

@artooras
Copy link

artooras commented Jul 12, 2021

Hi. A silly question perhaps, but where does one set the FIREBASE_AUTH_EMULATOR_HOST environment variable? The documentation doesn't explicitly state it. In which file should it be set? Where should it be located? @Joebayld , you seem to have figured it out, so any advice would be really appreciated... :) Thanks!

@v-kiniv
Copy link

v-kiniv commented Jul 12, 2021

Hi. A silly question perhaps, but where does one set the FIREBASE_AUTH_EMULATOR_HOST environment variable? The documentation doesn't explicitly state it. In which file should it be set? Where should it be located? @Joebayld , you seem to have figured it out, so any advice would be really appreciated... :) Thanks!

It's environment variable, you can set it globally in ~/.bash_profile or in terminal before firebase command:
FIREBASE_AUTH_EMULATOR_HOST=localhost:9099; firebase emulators:start.

For convenience use something like https://www.npmjs.com/package/dotenv, to separate configurations.

@artooras
Copy link

artooras commented Jul 12, 2021

Thanks @v-kiniv . Only I made it work by setting the variable on the dev script as opposed to the emulators script:

"dev": "FIREBASE_AUTH_EMULATOR_HOST=localhost:9099 next dev"

@harmandeep-singh
Copy link

This still existing in my case ,

    code: 'auth/argument-error',
    message: 'Firebase ID token has no "kid" claim. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'

i am using firebase latest :
"firebase-admin": "^9.11.0",
also set env. variable :
FIREBASE_AUTH_EMULATOR_HOST=localhost:9099

const idToken="eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6InJvaGFuLmtoYWFuYWlvQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiYXV0aF90aW1lIjoxNjI3NTY5NDA3LCJ1c2VyX2lkIjoiQ2VmQXV6ZlFsdG4yWkN2V1dIYU9rWE82YmhOMCIsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsicm9oYW4ua2hhYW5haW9AZ21haWwuY29tIl19LCJzaWduX2luX3Byb3ZpZGVyIjoicGFzc3dvcmQifSwiaWF0IjoxNjI3NTY5NDA3LCJleHAiOjE2Mjc1NzMwMDcsImF1ZCI6InNreWNybS0xYjYzOSIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9za3ljcm0tMWI2MzkiLCJzdWIiOiJDZWZBdXpmUWx0bjJaQ3ZXV0hhT2tYTzZiaE4wIn0.";

admin.auth().verifyIdToken(idToken).then((decodedToken) => {
        console.log("decode token", decodedToken);
})

@v-kiniv
Copy link

v-kiniv commented Jul 29, 2021

This still existing in my case ,

    code: 'auth/argument-error',
    message: 'Firebase ID token has no "kid" claim. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'

i am using firebase latest :
"firebase-admin": "^9.11.0",
also set env. variable :
FIREBASE_AUTH_EMULATOR_HOST=localhost:9099

const idToken="eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6InJvaGFuLmtoYWFuYWlvQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiYXV0aF90aW1lIjoxNjI3NTY5NDA3LCJ1c2VyX2lkIjoiQ2VmQXV6ZlFsdG4yWkN2V1dIYU9rWE82YmhOMCIsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsicm9oYW4ua2hhYW5haW9AZ21haWwuY29tIl19LCJzaWduX2luX3Byb3ZpZGVyIjoicGFzc3dvcmQifSwiaWF0IjoxNjI3NTY5NDA3LCJleHAiOjE2Mjc1NzMwMDcsImF1ZCI6InNreWNybS0xYjYzOSIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9za3ljcm0tMWI2MzkiLCJzdWIiOiJDZWZBdXpmUWx0bjJaQ3ZXV0hhT2tYTzZiaE4wIn0.";

admin.auth().verifyIdToken(idToken).then((decodedToken) => {
        console.log("decode token", decodedToken);
})

Make sure you've updated firebase-tools to the latest version:
npm i -g firebase-tools

@harmandeep-singh
Copy link

This still existing in my case ,

    code: 'auth/argument-error',
    message: 'Firebase ID token has no "kid" claim. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'

i am using firebase latest :
"firebase-admin": "^9.11.0",
also set env. variable :
FIREBASE_AUTH_EMULATOR_HOST=localhost:9099

const idToken="eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6InJvaGFuLmtoYWFuYWlvQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiYXV0aF90aW1lIjoxNjI3NTY5NDA3LCJ1c2VyX2lkIjoiQ2VmQXV6ZlFsdG4yWkN2V1dIYU9rWE82YmhOMCIsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsicm9oYW4ua2hhYW5haW9AZ21haWwuY29tIl19LCJzaWduX2luX3Byb3ZpZGVyIjoicGFzc3dvcmQifSwiaWF0IjoxNjI3NTY5NDA3LCJleHAiOjE2Mjc1NzMwMDcsImF1ZCI6InNreWNybS0xYjYzOSIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9za3ljcm0tMWI2MzkiLCJzdWIiOiJDZWZBdXpmUWx0bjJaQ3ZXV0hhT2tYTzZiaE4wIn0.";

admin.auth().verifyIdToken(idToken).then((decodedToken) => {
        console.log("decode token", decodedToken);
})

Make sure you've updated firebase-tools to the latest version:
npm i -g firebase-tools

sorry ! it was my Bad , after set env. reload the console can help if some one else stuck in same situation. 😀😀

@samlof
Copy link

samlof commented Aug 8, 2021

Any news on this for other SDKs? I'm developing with Go and came across this.

Not hard to bypass when you find this but takes an hour to figure out why and implement it

EDIT. Seems my problem was using old package. Firestore docs https://firebase.google.com/docs/firestore/quickstart#go tell to install the old GOPATH version and not /v4

@harmandeep-singh
Copy link

Everyone Having issue make sure by using : export FIREBASE_AUTH_EMULATOR_HOST=localhost:9099 for linux before running your application , double check that set's on your env., Linux : printenv will be helpful.

@aruntj
Copy link

aruntj commented Sep 14, 2021

Any news on this for other SDKs? I'm developing with Go and came across this.

Not hard to bypass when you find this but takes an hour to figure out why and implement it

EDIT. Seems my problem was using old package. Firestore docs https://firebase.google.com/docs/firestore/quickstart#go tell to install the old GOPATH version and not /v4

Oh my! You're a life saver! Following the docs does lead go users right into this issue. Thanks for this. And thanks firebase team!

alexcastillo added a commit to neurosity/oauth2-firebase-auth that referenced this issue Jan 31, 2022
@rromanchuk
Copy link

Is there an implementation (or merge) reference of the type of branching FIREBASE_AUTH_EMULATOR_HOST is doing during jwt decoding of unsigned emulator tokens? AKA, I don't have a Admin SDK so decoding/verification fails so need to implement myself.

@jalvini
Copy link

jalvini commented Dec 26, 2022

This is still happening to me.

I am logging the user in using the following piece of code in Swift:

Auth.auth().signIn(withEmail: email, password: password)

I am then passing in an ID token to the backend web call like so:

let userIDToken = try await signIn.result?.user.getIDToken() ?? ""
await web.webCall(endpoint: userIDToken)

Finally, I am using Express/Cloud Run on the backend and verifying my token like this:

let idToken = await admin.auth().verifyIdToken(req.body.idToken);
const uid = idToken.uid;

console.log(uid);

However, I am getting the following error message:

FirebaseAuthError: Firebase ID token has no "kid" claim. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.

When I go to that URL, it tells me to do exactly what Im doing, so what am I doing wrong?

@taeold
Copy link
Contributor

taeold commented Dec 27, 2022

@jalvini If you are having issues, can you file a new bug?

@HigorAlves
Copy link

Even with the env var Im getting this error:

FirebaseAppError: Error while making request: connect ECONNREFUSED ::1:9099. Error code: ECONNREFUSED

chrisvxd pushed a commit to chrisvxd/oauth2-firebase-auth that referenced this issue May 25, 2023
* FIX: Error: Firebase ID token has no kid claim. firebase/firebase-tools#2764

* FEAT: add cors support for /token endpoint

* FEAT: add cors support, response_type and redirect param to /consent endpoint

* FIX: post /consent does not send response

* FEAT: /authentication add supprot to custom consent url

* FIX: post /consent was missing await

* FEAT: post/ authorize/conset pass redirect_uri, query and fragments as well

* add .npmrc to .gitignore

* 0.3.0

* REVERT: add .npmrc to .gitignore

* FEAT: validateScope -> support multiple comman separated scopes

* 0.3.1

* FEAT: createOrUpdateAccessToken -> Create firebase custom token for custom auth and set scopes as claims for security rules

* 0.3.2

* FEAT: createOrUpdateAccessToken -> pass authId as custom claim to access it when removing access

* 0.3.3

* FIX: always split/join scope by space

* 0.3.4

* FEAT: support passing scope separator string via configuration

* 0.3.5

* RFR: save custom token calim scopes as string as firebase database rules do not support arrays

* 0.3.6

* FEAT: add new claim to custom token to id oauth is used

* 0.3.7

* FEAT: authentication -> add support for redirect param

* FEAT: add support for multiple redirect uris

* CHORE: update package.json to @neurosity/oauth2-firebase-auth

* 0.4.0

* FIX: allow redirect uris to have any path, enforce host and protocol

* 0.4.1

* FEAT: functions now support runtime options via runWith argument option

* 0.5.0

* ADD: prepublish script

* 0.5.1

* ADD: clean scrips

* 0.5.2
chrisvxd pushed a commit to chrisvxd/oauth2-firebase-auth that referenced this issue May 25, 2023
* FIX: Error: Firebase ID token has no kid claim. firebase/firebase-tools#2764

* FEAT: add cors support for /token endpoint

* FEAT: add cors support, response_type and redirect param to /consent endpoint

* FIX: post /consent does not send response

* FEAT: /authentication add supprot to custom consent url

* FIX: post /consent was missing await

* FEAT: post/ authorize/conset pass redirect_uri, query and fragments as well

* add .npmrc to .gitignore

* 0.3.0

* REVERT: add .npmrc to .gitignore

* FEAT: validateScope -> support multiple comman separated scopes

* 0.3.1

* FEAT: createOrUpdateAccessToken -> Create firebase custom token for custom auth and set scopes as claims for security rules

* 0.3.2

* FEAT: createOrUpdateAccessToken -> pass authId as custom claim to access it when removing access

* 0.3.3

* FIX: always split/join scope by space

* 0.3.4

* FEAT: support passing scope separator string via configuration

* 0.3.5

* RFR: save custom token calim scopes as string as firebase database rules do not support arrays

* 0.3.6

* FEAT: add new claim to custom token to id oauth is used

* 0.3.7

* FEAT: authentication -> add support for redirect param

* FEAT: add support for multiple redirect uris

* CHORE: update package.json to @neurosity/oauth2-firebase-auth

* 0.4.0

* FIX: allow redirect uris to have any path, enforce host and protocol

* 0.4.1

* FEAT: functions now support runtime options via runWith argument option

* 0.5.0

* ADD: prepublish script

* 0.5.1

* ADD: clean scrips

* 0.5.2
chrisvxd pushed a commit to chrisvxd/oauth2-firebase-auth that referenced this issue May 25, 2023
* FIX: Error: Firebase ID token has no kid claim. firebase/firebase-tools#2764

* FEAT: add cors support for /token endpoint

* FEAT: add cors support, response_type and redirect param to /consent endpoint

* FIX: post /consent does not send response

* FEAT: /authentication add supprot to custom consent url

* FIX: post /consent was missing await

* FEAT: post/ authorize/conset pass redirect_uri, query and fragments as well

* add .npmrc to .gitignore

* 0.3.0

* REVERT: add .npmrc to .gitignore

* FEAT: validateScope -> support multiple comman separated scopes

* 0.3.1

* FEAT: createOrUpdateAccessToken -> Create firebase custom token for custom auth and set scopes as claims for security rules

* 0.3.2

* FEAT: createOrUpdateAccessToken -> pass authId as custom claim to access it when removing access

* 0.3.3

* FIX: always split/join scope by space

* 0.3.4

* FEAT: support passing scope separator string via configuration

* 0.3.5

* RFR: save custom token calim scopes as string as firebase database rules do not support arrays

* 0.3.6

* FEAT: add new claim to custom token to id oauth is used

* 0.3.7

* FEAT: authentication -> add support for redirect param

* FEAT: add support for multiple redirect uris

* CHORE: update package.json to @neurosity/oauth2-firebase-auth

* 0.4.0

* FIX: allow redirect uris to have any path, enforce host and protocol

* 0.4.1

* FEAT: functions now support runtime options via runWith argument option

* 0.5.0

* ADD: prepublish script

* 0.5.1

* ADD: clean scrips

* 0.5.2
chrisvxd pushed a commit to chrisvxd/oauth2-firebase-auth that referenced this issue May 25, 2023
* FIX: Error: Firebase ID token has no kid claim. firebase/firebase-tools#2764

* FEAT: add cors support for /token endpoint

* FEAT: add cors support, response_type and redirect param to /consent endpoint

* FIX: post /consent does not send response

* FEAT: /authentication add supprot to custom consent url

* FIX: post /consent was missing await

* FEAT: post/ authorize/conset pass redirect_uri, query and fragments as well

* add .npmrc to .gitignore

* 0.3.0

* REVERT: add .npmrc to .gitignore

* FEAT: validateScope -> support multiple comman separated scopes

* 0.3.1

* FEAT: createOrUpdateAccessToken -> Create firebase custom token for custom auth and set scopes as claims for security rules

* 0.3.2

* FEAT: createOrUpdateAccessToken -> pass authId as custom claim to access it when removing access

* 0.3.3

* FIX: always split/join scope by space

* 0.3.4

* FEAT: support passing scope separator string via configuration

* 0.3.5

* RFR: save custom token calim scopes as string as firebase database rules do not support arrays

* 0.3.6

* FEAT: add new claim to custom token to id oauth is used

* 0.3.7

* FEAT: authentication -> add support for redirect param

* FEAT: add support for multiple redirect uris

* CHORE: update package.json to @neurosity/oauth2-firebase-auth

* 0.4.0

* FIX: allow redirect uris to have any path, enforce host and protocol

* 0.4.1

* FEAT: functions now support runtime options via runWith argument option

* 0.5.0

* ADD: prepublish script

* 0.5.1

* ADD: clean scrips

* 0.5.2
@wesharper
Copy link

wesharper commented Jul 2, 2023

Even with the env var Im getting this error:

FirebaseAppError: Error while making request: connect ECONNREFUSED ::1:9099. Error code: ECONNREFUSED

I had to change mine to 127.0.0.1:9099 vs localhost:9099. However, I'm now having an issue where the firebase auth emulator cannot find the user corresponding to the identifier in the JWT.

FirebaseAuthError: There is no user record corresponding to the provided identifier.

@Mikephii
Copy link

any update on this for the go v4 sdk? is it safe to use "firebase.google.com/go" instead of v4?

@abdushkur
Copy link

abdushkur commented Sep 9, 2024

I implemented like this:

async function getIdTokenByEmailAndPassword(email, password) {
  const isRunningInEmulator = process.env.FIREBASE_AUTH_EMULATOR_HOST !== undefined;
  let baseUrl = `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=${process.env.GOOGLE_API_KEY}`;
  if(isRunningInEmulator){
    baseUrl = `http://${process.env.FIREBASE_AUTH_EMULATOR_HOST}/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${process.env.GOOGLE_API_KEY}`;
  }
  const data = {
    email: email,
    password: password,
    returnSecureToken: true
  };
  try {
    const response = await axios.post(baseUrl, data, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    return response.data;
  } catch (error) {
    throw Error(error.response ? error.response.data.error.message : error.message);
  }
}

async function getIdTokenByCustomToken(customToken) {
  const isRunningInEmulator = process.env.FIREBASE_AUTH_EMULATOR_HOST !== undefined;
  let baseUrl = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${process.env.GOOGLE_API_KEY}`;
  if(isRunningInEmulator){
    baseUrl = `http://${process.env.FIREBASE_AUTH_EMULATOR_HOST}/identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${process.env.GOOGLE_API_KEY}`;
  }
  const data = {
    token: customToken,
    returnSecureToken: true
  };
  try {
    const response = await axios.post(baseUrl, data, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    return response.data;
  } catch (error) {
    throw Error(error.response ? error.response.data.error.message : error.message);
  }
}

@Jhon-Idrovo
Copy link

Jhon-Idrovo commented Dec 26, 2024

For those still facing the issue

I found that the problem for me was not using "" for the variable

FIREBASE_AUTH_EMULATOR_HOST="localhost:9099" instead of FIREBASE_AUTH_EMULATOR_HOST=localhost:9099

@rublev
Copy link

rublev commented Feb 28, 2025

Unreal that I am still getting the "Firebase ID token has no "kid" claim". Complete joke.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests