awinogrodzki / next-firebase-auth-edge

Next.js Firebase Authentication for Edge and Node.js runtimes. Compatible with latest Next.js features.
https://next-firebase-auth-edge-docs.vercel.app/
MIT License
534 stars 46 forks source link

createAuthMiddlewareResponse returns error Too big integer #17

Closed vladgardus closed 1 year ago

vladgardus commented 1 year ago

I'm using the createAuthMiddlewareResponse middleware together with the AuthProvider provided in the example and when calling the endpoint "/api/login" I get error : error - node_modules\next-firebase-auth-edge\lib\auth\jwt\crypto-signer.js (21:0) @ ServiceAccountSigner.sign error - Too big integer

I am running this locally, I'm not using the emulator, and it seems that the issue is on this line: https://github.com/ensite-in/next-firebase-auth-edge/blob/b5349422ea81c421812972d127ca48f0b5a6979e/src/auth/jwt/crypto-signer.ts#L35

The way I configured my service account is this: serviceAccount: { projectId: process.env.FIREBASE_ADMIN_PROJECT_ID, privateKey: process.env.FIREBASE_ADMIN_PRIVATE_KEY, clientEmail: process.env.FIREBASE_ADMIN_CLIENT_EMAIL, }

And the values configured in the env variables is I went in firebase -> Project settings -> Service accounts -> Firebase Admin SDK -> Generate a new private key. Out of that JSON I mapped: FIREBASE_ADMIN_PROJECT_ID -> project_id FIREBASE_ADMIN_PRIVATE_KEY -> tried both private_key_id and private_key with and without the commented "-----BEGIN PRIVATE KEY-----" FIREBASE_ADMIN_CLIENT_EMAIL -> client_email

What might be the issue?

awinogrodzki commented 1 year ago

Hey @vladgardus! Thanks for reporting the issue.

There are two steps to make this work:

  1. Copy the whole private key (including "-----BEGIN PRIVATE KEY-----\n", "\n-----END PRIVATE KEY-----\n" as well as new line characters into a variable. Here's an example using .env file:

    FIREBASE_ADMIN_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\nMIIEvQI_REST_OF_THE_KEY_HERE_SgKXeiGI/+Y=\n-----END PRIVATE KEY-----\n
  2. The second step is to use the variable in Node.js, but there's one small caveat that you're probably missing. Here's the config from next13-typescript-example:

export const serverConfig = {
  firebaseApiKey: process.env.FIREBASE_API_KEY!,
  serviceAccount: {
    projectId: process.env.FIREBASE_PROJECT_ID!,
    clientEmail: process.env.FIREBASE_ADMIN_CLIENT_EMAIL!,
    privateKey: process.env.FIREBASE_ADMIN_PRIVATE_KEY!.replace(/\\n/g, '\n')
  }
};

Notice the .replace method at the end of the string. We need to convert escaped \n characters into new-line characters before validating the private key.

Could you try that out and let me know if that worked?

vladgardus commented 1 year ago

It works fine now! Thank you very much for your help.