danecando / with-firebase-user

A higher order function that decodes a Firebase Auth JWT and decorates the NextJS api request object with a Firebase user

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to get 'kid' in header when testing with firebase emulator?

cureau opened this issue · comments

Firstly, this is an awesome lib, so glad I found it — surprised it's yet undiscovered. Thank you

I ran into an issue running locally with Firebase Auth Emulators where if the Firebase's client-side SDK is using local auth emulators, then there's no kid in the accessToken, which breaks the withFirebaseUser function.

Fyi, this is my current workaround. You may be using the firebase admin SDK on next or not pointing your client SDKs to the local auth emulator, hence why you may not have this issue (I'm posting it for other users or in case you want to handle this case).

It seems this is a deliberate safety measure by Firebase.

      if (publicKey) {
        // decode jwt with public key
        const decodedToken = jwt.verify(accessToken, publicKey, {
          audience: projectId,
          issuer: projectId && `https://securetoken.google.com/${projectId}`,
        });
        console.log(decodedToken, 'decodedToken');

        if (typeof decodedToken === 'object') {
          // create user object we decorate req with from decoded token
          const user: FirebaseUser = {
            user_id: decodedToken.user_id ?? decodedToken.sub,
            name: decodedToken.name,
            email: decodedToken.email,
            email_verified: decodedToken.email_verified,
          };

          decoratedReq.user = user;
        }
      } else if (process.env.NODE_ENV === 'development') {
        const body = accessToken.split('.')[1];
        const decodedString = Buffer.from(body, 'base64').toString('ascii');
        decoratedReq.user = JSON.parse(decodedString);
      } else {
        console.error('No public key or kid found.');
      }

@cureau thanks for reporting this issue and great to hear someone else is getting some use out of this 👍 .

You're right I haven't tried using the firebase emulators at the moment, so glad you caught this. I'll try this out locally soon with the emulator and open a PR to fix it. I think using a different environment variable like FIREBASE_EMULATOR=true or something might be good for this since you might not be running the emulators in dev.

If some people besides myself actually find this useful I'll clean it up a bit more and write some tests for it as well.