Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

How to authenticate firebase-admin with nodejs?

I am using Nodejs with the firebase-admin library, but I have not been successful authenticating to use Firestore.

Show More
Error : Error: 16 UNAUTHENTICATED: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

I Tried :

  1. I generated the key as requested by firebase by following this link: Services AdminSDK or Project Overview > Project Settings > Service Accounts > Generate new private key
  2. I checked the Read and Write permissions.

 

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

 

My Code :

 

import express from 'express';
import admin from 'firebase-admin';

const credentials = './key.json';

admin.initializeApp( { 
    credential : admin.credential.cert( credentials )
 } );

const app = express();
const db = admin.firestore();

app.use( express.json() );
app.use( express.urlencoded( { extended : true } ) );

app.post( '/create', async ( req, res ) => {
    try {
        const id = req.body.email;
        const regJSON = {
            email : req.body.email,
            firstName : req.body.firstName,
            lastName : req.body.lastName,
        }
        const registerResponse = db.collection( ' users ' ).doc( ` ${ id } ` ).set( regJSON );
        res.json( {
            'message' : 'Data Stored with SUCCESS!!!!',
            'data' : registerResponse
        } );
    }
    catch ( e ) {
        res.json( {
            'message' : 'ERROR',
            'data' : e.toString()
        } );
    }
} );
const PORT = process.env.PORT || 8080;
app.listen( PORT, () => console.log( ` The server is running on PORT : ${ PORT } ` ) );

 

Thank You for now!

0 4 685
4 REPLIES 4

Looks like you're using ESM rather than CommonJS. Nice. Except it cannot import JSON files. I know...
So you have to convert your Service Account Key into an object than can be imported. Like this:

import key from './key.mjs';

admin.initializeApp({
credential: admin.credential.cert(key)
});

Where your key file resembles this:

const key = {
    "type": "service_account",
    "project_id": "",
    //etc
  }

export default key

 

Hi

I just tried your solution, but I am getting the same warning!

I think the problem is with the key. I looked at the error message and the page it recommends is client-side.

So, here's an idea. I know Firebase well, but Google Cloud Console better. Time to step into the ultimate zone of controls!

Through the Google Cloud Console, via IAM & Admin; Service Accounts (link), let's create a new Service Account and key (JSON) and download the key. Now reformat the key into an import export, as before, and try again.

If you are unfamiliar with GCC, welcome to a paradise of new controls for permissions and roles! Frankly, I don’t use client-side Firebase, so the security rules for Firestore are not used. Instead, I create Service Accounts with permissions for Firestore Database, such as read/write, or view. Unfortunately, you can’t manage controls per database (unlike Storage Buckets), so you have to be a little more inventive, since the Admin SDK automatically bypasses all Firestore security rules.

Let me know how it goes. I also recommend subscribing for a month to an advanced AI, such as Gemini or GPT. They are coding masters and will help you with specifics like these in faster time. Gemini will already know a lot about Google Cloud and Firebase.

Hi @CloudComputing,

The error suggests that the credentials you're using to authenticate the Admin SDK can't be used for the action you're trying to perform. Some authentication methods, like createCustomToken() and verifyIdToken(), require the SDK to be initialized with a certificate credential instead of a refresh token or Application Default credential. Check out the "Initialize the SDK" documentation for guidance on how to authenticate the Admin SDKs with a certificate credential.

Was this helpful? If so, please accept this answer as “Solution”. If you need additional assistance, reply here within 2 business days and I’ll be happy to help.