firebase-admin-node icon indicating copy to clipboard operation
firebase-admin-node copied to clipboard

secretOrPrivateKey must be an asymmetric key when using RS256

Open jdutheil opened this issue 2 years ago • 37 comments

  • Operating System version: Ubuntu 22.10
  • Firebase SDK version: 11.3.0
  • Firebase Product: auth
  • Node.js version: 16.13.2
  • NPM version: 8.19.2

[REQUIRED] Step 3: Describe the problem

I am using Firebase-Admin on a NestJs API, build with NX ; my API is using Admin SDK to create and manage users. For that, I am using the method auth.createUser({email, password}), but Firebase throws an error, ONLY FOR THE FIRST CALL :

secretOrPrivateKey must be an asymmetric key when using RS256

I know my private key is readed right, and most of all, only the first call to createUser returns error ; other calls are working great.. So I ended up putting a call with fake datas right after the initialization of Firebase, to be able to use it in other parts of my app, but it doesn't seem so terrible..! I can't find any other people having the same issue, really weird.

Any idea ?

jdutheil avatar Jan 20 '23 20:01 jdutheil

I was stuck in this problem, and the solution for me was generate de key using the key size as 2048 with algorithm:RS256

luizfilho avatar Jan 22 '23 02:01 luizfilho

I have the same error on simple nodejs code, but it happens for all the calls for me not only the first one. Any solution ? @luizfilho can you please explain where do you generate the key ? i'm doing it from firebase console and it's not giving the option to configure the key.

karim-goubba avatar Jan 23 '23 15:01 karim-goubba

Wait, do you want generate a jsonwebtoken ? Just to check if we are in same page.

luizfilho avatar Jan 23 '23 17:01 luizfilho

I have the same problem, entered the private-key and other information as env. when I try to send message the error occurs. Log: error: Unable to store a new push token secretOrPrivateKey must be an asymmetric key when using RS256 ` import admin from 'firebase-admin'

const { FIREBASE_PROJECT_ID = '', FIREBASE_PRIVATE_KEY = '', FIREBASE_CLIENT_EMAIL = '', } = process.env

class Firebase { public init() { return admin.initializeApp({ credential: admin.credential.cert({ projectId: FIREBASE_PROJECT_ID, clientEmail: FIREBASE_CLIENT_EMAIL, privateKey: FIREBASE_PRIVATE_KEY, }), }) } }

export default Firebase `

diegosantosouza avatar Jan 23 '23 20:01 diegosantosouza

I solved it as follows

import admin from 'firebase-admin'

const {
  FIREBASE_PROJECT_ID = '',
  FIREBASE_PRIVATE_KEY = '',
  FIREBASE_CLIENT_EMAIL = '',
} = process.env

class Firebase {
  public init() {
    return admin.initializeApp({
      credential: admin.credential.cert({
        projectId: FIREBASE_PROJECT_ID,
        clientEmail: FIREBASE_CLIENT_EMAIL,
        privateKey: FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
      }),
    })
  }
}

export default Firebase

my env : FIREBASE_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\n<YOUR_PRIVATE_KEY>\n-----END PRIVATE KEY-----\n

the private key I used exactly as in the example, without quotes.

diegosantosouza avatar Jan 24 '23 19:01 diegosantosouza

Perfect! In my case I put the key in a file, and I read the file to use it, to avoid the problem of \n. Anyway, thanks for share.

luizfilho avatar Jan 24 '23 20:01 luizfilho

@diegosantosouza you just pasted the service account json file in the .env File ?

Yagelazuo avatar Jan 25 '23 08:01 Yagelazuo

@diegosantosouza you just pasted the service account json file in the .env File ?

firebase does not need all the information contained in the json file, only [projectId, clientEmail, privateKey]. you can use it as an environment variable to put your project into production without exposing the json file in your repository.

diegosantosouza avatar Jan 25 '23 13:01 diegosantosouza

Still the same error for me. Here's my code: ` const admin = require("firebase-admin"); require('dotenv').config();

admin.initializeApp({ credential: admin.credential.cert({ projectId: process.env.FIREBASE_PROJECT_ID, clientEmail: process.env.FIREBASE_CLIENT_EMAIL, privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\n/g, "\n"), }), });

admin.auth().getUser("kFC1nrE51YSIDdwY9gYWvyZxKtX2"); ` And in my env file: image Still getting the same error : secretOrPrivateKey must be an asymmetric key when using RS256

karim-goubba avatar Jan 25 '23 13:01 karim-goubba

Since the original issue was encountered in NestJs API, built with NX, @jdutheil: does replacing the /n per https://github.com/firebase/firebase-admin-node/issues/2051#issuecomment-1402448454 (privateKey: FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),)work for you?

If not, could you provide us with a minimal repro or a complete code sample to reproduce the issue in NestJs API? Thanks.

lahirumaramba avatar Jan 25 '23 19:01 lahirumaramba

It is an ubuntu problem probably

Yagelazuo avatar Jan 25 '23 20:01 Yagelazuo

I have the same problem and none of the suggestions above worked for me

focafull avatar Jan 27 '23 15:01 focafull

@jdutheil Hey, I have the same problem and I am using Ubuntu too, What I discovered is that if I run the same server on a different system (I ran it on mac) it works, This leads me to believe it has something to do with the ubuntu operating system

Yagelazuo avatar Jan 28 '23 10:01 Yagelazuo

@jdutheil Found a solution for you, upgrade your node version to 18 !, I was shocked it worked

Yagelazuo avatar Jan 28 '23 13:01 Yagelazuo

It also worked in NodeJS 16.19.0 😄 Not worked in 16.15.0 .

nesso-pfl avatar Jan 30 '23 08:01 nesso-pfl

@jdutheil Found a solution for you, upgrade your node version to 18 !, I was shocked it worked

Yea, I worked in the Docker environment, migrate from node 16 to node 18 and don't use quotes in .env for the private key.

im6h avatar Jan 31 '23 11:01 im6h

It also worked in NodeJS 16.19.0 smile Not worked in 16.15.0 .

Thanks. I used NodeJS v16.14 and not work. Upgrading to v18 fixed.

acro5piano avatar Feb 13 '23 08:02 acro5piano

I don't use Firebase but I'm facing this issue currently. Resolved to ditching Passport entirely and writing my own authentication guards myself. Sigh.

alvissraghnall avatar Feb 22 '23 18:02 alvissraghnall

I just started getting this issue, but I'm running windows and Node v18.15.0 when calling getAuth().getUser(uid). Any updates on this? I know it might not be a Firebase issue but I'm not sure where to troubleshoot next.

ngregrichardson avatar Mar 27 '23 21:03 ngregrichardson

I know its silly, but when I tried to use netilfy, I got the error because my environment variables were wrapped with commas "...env_value...." I got rid of the commas ...env_value... for all my environment variables and it worked

elron avatar Apr 25 '23 16:04 elron

I also faced this issue on linux, changed node v from 18.16 to 16.20 and voila.

mhmd-pixel avatar Jul 09 '23 10:07 mhmd-pixel

I have same issue, i am using sveltekit, i am initializing the admin sdk like this in the server side:

import { initializeApp, credential, apps } from "firebase-admin";
import * as path from "path";
import * as fs from "fs";
import { deleteApp } from "firebase-admin/app";

// Get the path to the service account key JSON file
const serviceAccountPath = path.join(
  process.cwd(),
  "firebase",
  "serviceAccountKey.json",
);

// Read the service account key JSON file synchronously
const serviceAccount = JSON.parse(fs.readFileSync(serviceAccountPath, "utf-8"));
const config = {
  credential: credential.cert(serviceAccount),
};

let adminSDK = null;
if (!apps.length) {
  adminSDK = initializeApp(config, "admin");
} else {
  await deleteApp(adminSDK);
  adminSDK = initializeApp(config, "admin");
}

export default adminSDK;

and when i use it in hook.server.js:

/** @type {import('@sveltejs/kit').Handle} */
import adminSDK from "../firebase/firebaseAdminSdk.js";

export async function handle({ event, resolve }) {
  const token = event.cookies.get("_token_");
  const uuid = event.cookies.get("UUID");

  if (token) {
    try {
   const decodedToken =    await adminSDK.auth().verifyIdToken(token);
    const user =   await adminSDK.auth().getUser(uuid);
      event.locals.authenticated = true;
      return await resolve(event);
    } catch (error) {
      event.locals.authenticated = false;
      console.log(error);
    }
  }
  return await resolve(event);
}

when i console.log(decodedToken) everything goes as expected, but it throws out error Error: secretOrPrivateKey must be an asymmetric key when u sing RS256 , when trying to execute const user = await adminSDK.auth().getUser(uuid); this line, any idea what went wrong and how to fix this issue?

NULL401 avatar Aug 05 '23 08:08 NULL401

Having the same issue in Deno tried all the solutions about , any of you had any luck ?

AbeerAhmad avatar Aug 09 '23 11:08 AbeerAhmad

Having the same issue in Deno tried all the solutions about , any of you had any luck ?

Hey Abeer. I also produced the issue. @AbeerAhmad

docharrod85 avatar Aug 09 '23 20:08 docharrod85

I got the same issue Error: secretOrPrivateKey must be an asymmetric key when using RS256 when trying to use firebase-admin. My firebase private key is an environment variable and used in the initializeApp function from firebase-admin. Was able to fix the error by:

  • Wrap the firebase private key environment variable inside single quotes + double quotes like so:

FIREBASE_PRIVATE_KEY='"-----BEGIN PRIVATE KEY-----\n<the key goes here>\n-----END PRIVATE KEY-----\n"'

  • Use JSON.parse() when reading the env variable and initializing the app:
app = initializeApp({
    credential: cert({
      privateKey: JSON.parse(process.env.FIREBASE_PRIVATE_KEY as string),
      clientEmail: process.env.FB_CLIENT_EMAIL,
      projectId: process.env.FB_PROJECT_ID,
    }),
  });

jaysencpp avatar Aug 17 '23 14:08 jaysencpp

I got the same issue while generating jsonWebToken. I solved it as follow

const crypto = require('crypto') const cert = fs.readFileSync('./key.pem', 'utf8') const privateKey = crypto.createPrivateKey({key : cert, passphrase:'pass'}) ...

The generated privateKey will be asymmetric.

anil-darjee-robomq avatar Sep 25 '23 09:09 anil-darjee-robomq

I can confirm updating node to 18 fixed the problem. I was running v16.14.2 and once I updated to v18.18.0 everything worked as expected.

MawRojas avatar Oct 06 '23 18:10 MawRojas

maybe I'm too late for the party, in my case I had a extra comma , after the key that somehow messed up my .env file

before `FIREBASE_SA_PRIVATE_KEY="-----BEGIN PR...0k\n-----END PRIVATE KEY-----\n",

after `FIREBASE_SA_PRIVATE_KEY="-----BEGIN PR...0k\n-----END PRIVATE KEY-----\n"

x1c0 avatar Nov 12 '23 20:11 x1c0

@x1c0 you saved my life

souzaluiz avatar Nov 13 '23 19:11 souzaluiz

@anil-darjee-robomq solution worked for me.

akanz avatar Nov 21 '23 07:11 akanz