Electron Firebase: FIREBASE WARNING: Provided authentication credentials are invalid - node.js

I've created electron app that uses firebase auth and database.
App uses signInWithCustomToken with token received from remote server.
On my work machine (macOS) it works as expected. But when i've cloned my repo to home machine (windows) i've receive
FIREBASE WARNING: Provided authentication credentials are invalid.
This usually indicates your FirebaseApp instance was not initialized correctly.
Make sure your apiKey and databaseURL match the values provided
for your app at https://console.firebase.google.com/
As i found here in same questions error with firebase-admin. But i'm using client library. Also i've misunderstood how it depends on machine where it runs?
I'm using npm package firebase 4.1.5 packed with webpack into client script
Initialising:
const firebaseConf = {
apiKey: '<api_key>',
authDomain: '<domain>.firebaseapp.com',
databaseURL: 'https://<database>.firebaseio.com',
projectId: '<project_id>',
storageBucket: '<storage>.appspot.com',
messagingSenderId: '<sender_id>',
};
Vue.prototype.$firebase = firebase.initializeApp(firebaseConf);
So on work machine all database operations work fine. But on home machine it shows that warning few times after signInWithCustomToken called and does nothing else
The code is exactly the same. It was cloned from bitbucket
I've spent a whole day trying to figure out the reason but failed.
Sorry for my English
Thank you in advance

Related

Firebase - Error: 16 UNAUTHENTICATED: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid au

Hello I'm using firebase functions and I have created a Node.js project with firebase init, then I selected the options functions, firebase and storage. The project works with the firebase-admin NPM package.
When I deploy the project with firebase deploy everything goes well, but when I run the function on the cloud, it says the following message:
I have tested the entire project with the emulators and it works well.
Project Structure:
What is causing this error? Thanks!
I solved it. The problem was that I had this in the initializeApp:
const serviceAccount = require("../project-name-f3ad6ae0572f.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: BUCKET_NAME,
});
This is incorrect because I was missing the firebase configuration that is given on the Firebase Console -> Project Settings -> Your Apps.
Then, the result has to be like this:
const firebaseConfig = {
apiKey: "xxx-your-api-key-xxx",
authDomain: "project-name.firebaseapp.com",
projectId: "project-name",
storageBucket: "project-name.appspot.com",
messagingSenderId: "xxxxxxxxxxxxxxxx",
appId: "x:xxxxxxxxxxxxxxx:web:xxxxxxxxxxxxxxx",
measurementId: "G-XXXXXXXXX",
};
admin.initializeApp(firebaseConfig);
verify your pc time, i had same problem and resolving when update pc time.
import * as admin from 'firebase-admin';
const serviceAccount = require('./firebase.json');
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
export const firebaseDB = admin.firestore();
I might be late to this question but I faced a similar issue yesterday (16 October 2022). What I figured is that, when you set your computer's time manually, firebase doesn't work.
So your firebase timestamp rules must match with your current host time.
The code for the function framework is actually public in the GoogleCloudPlatform/functions-framework-nodejs repository (although not advertised anywhere).
In particular you can see there the cases where killInstance is used, which is the one triggering exit code 16:
const killInstance = process.exit.bind(process, 16);
These cases are (at the time of writing):
· uncaughtException
· unhandledRejection
I had the same issue today, if it's only happening in your local environment, there's a 99% chance that your computer's time is wrong.

Deploying firebase cloud function fails when I initialise firebase with a service account key

so very recently I started using google's firebase cloud functions, and loved it immediately! I very quickly restructured a project I was going to work on, and included firebase in it, so I could use the cool features of firestore, in combination with cloud functions.
Up until today, everything went on smoothly; pretty much, until I decided to play with google's FCM (Firebase Cloud Messaging) to send notifications via node js. Before this, I had created some really dense functions and already deployed to my console which were working seamlessly.
The tricky part is, at the time I created and deployed these functions, I initialised my firebase app in node js with admin.initalizeApp().
With this, everything worked fine(both locally & deployed) until I tried to use admin.messaging().sendToDevice... which resulted in a very nasty error, that basically told me I couldnt send notifications if I wasnt authenticated..
The error
(Error: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions. Raw server response: "<HTML>
> <HEAD>
> <TITLE>Unauthorized</TITLE>
> </HEAD>
> <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
> <H1>Unauthorized</H1>
> <H2>Error 401</H2>
> </BODY>
> </HTML>
> ". Status code: 401.)
Following the error, I used a few tips from some other users on stack overflow who had faced this error, and most of them suggested that I download a service key from my console, and initialise my firebase app with admin.initializeApp({credential:admin.credential.cert(serviceAccount)})
This solution worked beautifully, as it allowed me to test my notification without seeing the above error ever again.
However, when all my tests were done, and I was ready to deploy, the new function I had just created to work on notification, as well as all my previously deployed functions could not get deployed. All of a sudden, the old working functions in my console had a red exclamation mark beside them, and I had to get rid of them. Even after I cleared out all of my console and tried to redeploy all my functions, it failed, and failed and failed with no errors(context: I wasted the whole day!!! lool!) Every tip on the internet failed for me, until I reverted back to my old way of initialising my firebase app admin.initializeApp(), then booom! all my functions uploaded successfully, and then again, the authentication error appeared again when I tried to retest my notification function.....
I guess my question is: is there anything I don't know about deploying functions to the firebase console with my app initialised with a service account key I downloaded from my console?
Is there something else I need to do to get my functions to deploy properly every time I init my firebase admin app with a service account key?? Because initialising the app with just .initalizeApp() works fine for all other purposes both locally and when deployed, except when using FCM. Can anyone please help with what is happening here??
I think it can be solved by initializing two apps and using them as objects described here. One with credentials that work for other functions and one for messaging.
If you need it only for one function you can do it even inside it. I have tested it like this:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
exports.first_app = functions.https.onRequest(async (req, res) => {
res.json(admin.app().name);
})
exports.other_app = functions.https.onRequest(async (req, res) => {
var otherApp = admin.initializeApp({
credential: **<< different credential here >>**
}, "2nd_app");
res.json(otherApp.name);
})
as already mentioned, you should initialize a second app just for the new function you are creating. You should put the initialization code inside the new function like this
export const saveMap = functions.https.onRequest(async (req, response) => {
const serviceAccount = require("./../serviceAccountKey.json");
admin.initializeApp({
projectId: "serviceAccount.project_id",
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://your_project_id_here.firebaseio.com", //update this
storageBucket: "your_bucket_name_here.appspot.com" //update this
}, "2nd_app")
I had the same issue and once I put the second initialization code into the new function, it worked. Note that in this code the serviceAccountKey.json is in the same folder as src and lib.

Realtime DB events don't work when subscribed to from Admin SDK

Operating System: Ubuntu 16.04
Firebase SDK version: 4.8.0
Library version 5.5.1
Node version: 7.8.0
Firebase Product: database
Hey! Yesterday my server with Admin SDK stopped working. After a little investigation it turns out that events don't fire anymore. For example, the following code neither fails or succeedes (the process is running forever). It is run on a local dev server:
const admin = require('firebase-admin')
const config = require('./config')
const signature = require('./signature.json')
admin.initializeApp({
credential: admin.credential.cert(signature),
databaseURL: config.databaseURL
})
admin.database()
admin.database().ref('/config').once('value')
.then(snapshot => console.log(snapshot.val()))
.catch(error => console.log(error))
module.exports = {}
Database events are working when I subscribe to them as a client. Also database is accesible from web console. I've tried generating a new private key (credentials), but it doesn't help. What am I missing? Is there a way to take a closer look at what's going on? Maybe enabling debug mode somehow?
After enabling loggin I was able to figure out what's wrong.
// Enable logging
admin.database.enableLogging(true)
The problem was that the time on my machine was out of sync. After synchronising it the database is working again.

Firebase Admin INVALID_APP_OPTIONS error at initializeApp()

I'm trying to connect Instagram OAuth to Firebase through Node.js back-end. I have successfully retrieved Instagram account data including access_token which I want to exchange with firebase-admin's createCustomToken on my Node.js backend. My objective here is to generate custom token so my Angular app can do signInWithCustomToken(token) into my Firebase app. There is no problem on retrieving data from Instagram as I can print my JSON object on console.
The problem is occurred when I want to exchange my access_token to Firebase Custom Token.
I have followed this guide from Firebase Admin page for Node.js and I'm facing an error message below
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, "Invalid Firebase app options passed as the first argument to initializeApp() for the " +
Error: Invalid Firebase app options passed as the first argument to initializeApp() for the app named "[DEFAULT]". The "credential" property must be an object which implements the Credential interface.
Here is my code on related issue.
// authService.js
var fbAdmin = require('firebase-admin');
var serviceAccount = require('./key/key.json');
function createFirebaseToken(instagramID) {
// I copy & pasted this var from other class
var config = {
apiKey: "MY_FIREBASE_APIKEY",
authDomain: "MY_APP.firebaseapp.com",
databaseURL: "https://MY_APP.firebaseio.com",
storageBucket: "MY_APP.appspot.com",
};
console.log(fbAdmin.credential.cert(serviceAccount)); // serviceAccount successfully printed on console
// Error appears when executing this function
fbAdmin.initializeApp({
serviceAccount: fbAdmin.credential.cert(serviceAccount),
databaseURL: config.databaseURL
});
const uid = `instagram:${instagramID}`;
// Create the custom token.
console.log(uid);
return fbAdmin.auth().createCustomToken(uid);
}
It appears that my Node app cannot initialize a connection to firebase-admin but I have no idea the solution as I am a beginner on these technologies. Please advice.
This issue can be resolved by updating firebase-tools, firebase-functions and firebase-admin packages to the latest version.
npm install -g firebase-tools#latest
npm install firebase-functions#latest
npm install firebase-admin#latest
Refer this GitHub page for more details.
Just stumbled upon on Firebase Admin Release Notes at version 5.0.0 on May 2017 stated that serviceAccount has been removed. So instead of forcing to use serviceAccount, I use credential instead.
fbAdmin.initializeApp({
credential: fbAdmin.credential.cert({
projectId: '<APP_ID>',
clientEmail: "foo#<APP_ID>.iam.gserviceaccount.com",
privateKey: "-----BEGIN PRIVATE KEY-----\n<MY_PRIVATE_KEY>\n-----END PRIVATE KEY-----\n"
}),
databaseURL: config.databaseURL
});
Updated Answer
After continuing to work with this, it seems to be able to call admin.initializeApp() without any params, you need to make sure your `/functions nodeJs setup is up to date.
In /functions directory, run this command:
npm i --save firebase-functions#latest
Thanks to:
https://stackoverflow.com/a/49437619/2162226
.. I am still getting familiar with all the nodeJS/npm details - not sure why, but seems I had to run it a few times for everything to get into place. That and the sudo npm install -g firebase-tools updated as well .
According to official docs, we need to be using at least version Firebase 4.12.0 in order to get the latest cloud functions support: https://firebase.google.com/docs/functions/callable
First Answer
I ran into the same error message in trying to set up Cloud Functions for Firebase.
Passing in the argument for admin.initializeApp solved it for my project:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
After a good amount of search, gratefully found this thread with a post where it has that line of code: https://github.com/firebase/firebase-functions/issues/99 .. because so far haven't seen it anywhere in the docs about that parameter
According to the release docs for Jan. 11, 2018:
https://firebase.google.com/support/release-notes/admin/node
The admin.initializeApp() method can now be invoked without any arguments. This initializes an app using Google Application Default Credentials, and other AppOptions loaded from the FIREBASE_CONFIG environment variable.
Kindly use the following snippet, which is mentioned in the Firebase Admin SDK for Node.js. Download the JSON file from the Service Account in the Project Settings and change the path in serviceAccount. Also add your databaseUrl, which is of the form http://app_name/.firebaseio.com
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "yourDatabaseUrl"
});
For those having this issue with "firebase-admin": "^11.0.0", you have to construct the certification passed into initializeApp() using cert imported from firebase-admin/app.
Example:
import { initializeApp, cert } from "firebase-admin/app";
const admin = initializeApp({
credential: cert({
projectId: process.env.MY_PROJECT_ID,
clientEmail: process.env.MY_PRIVATE_KEY,
privateKey: process.env.MY_CLIENT_EMAIL,
}),
});
Check what version of firebase-admin module you are using.
As per the release note of version 5.9.1
The admin.initializeApp() method can now be invoked without a credential option. The SDK uses Google Application Default Credentials when initialized this way.
release notes

Firebase admin sdk (node.js) database request freezing

In recent days, i have encountered a few problems with my old firebase sdk's in both android and server node js 'firebase' sdk. Sending notifications and retrieving data.
After i updated android dependencies with newest version, notification problem was solved.
But in server side:
Installed firebase admin sdk.
Followed instructions:
https://firebase.google.com/docs/admin/setup
and also checked role of firebase-adminsdk service account.
Problem with the following example:
var admin = require("firebase-admin");
var serviceAccount = require("filepath.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://dbname.firebaseio.com"
});
var db = admin.database();
var ref = db.ref("myval");
ref.once("value",function(snapshot){
console.log(snapshot.val());
});
Example does not return any value or error, just waiting. Sure there is 'myval' child under main database tree.
What wrong may cause the problem?
Solved the problem with help of firebase team.
Enabling the logging before database definition with:
admin.database.enableLogging(true);
var db = admin.database();
helps for debugging. After that I got the error:
Failed to get token: Error: Error fetching access token: invalid_grant (Invalid JWT: Token must be a short-lived token and in a reasonable timeframe)
And according to this:
Authentication on google: OAuth2 keeps returning 'invalid_grant'
my machine timezone was not syncronized appropriately with a ntp server, which is required for new admin authentication in my case.
Then (in ubuntu 14.04) setting the timezone (timezones are here: '$ timedatectl list-timezones') :
$ sudo timedatectl set-timezone desired_timezone
solved the problem!
Thanks for helps.

Resources