firebase-admin along with firebase-functions and auth (for setting custom claims)
(Whatever happened is happened while running the command firebase serve)
firebase-tools: v7.11.0
I was just initializing a firebase project in my laptop, made the changes only in my firebase.json and index.js file which are autogenerated by firebase init; and while using auth functions it returned an initializeApp related error in the cach block and the claims are not get set.
Step 1: Just run the following commands
mkdir firebase
cd firebase
firebase init
Choose functions and hosting
Select a project from the existing projects
Use JavaScript as language and set the "public" folder for hosting
Step 2: add
{
"source": "/api/**",
"function": "api"
}
inside firebase.json rewrites as the first element of array
Step 3: Replace content of index.js with the below one:
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
const func = () => {
admin.auth().setCustomUserClaims("(req.params.uid", {isActivated: true}).then(() => {
console.log("Done")
})
.catch(e => console.error(e))
}
setTimeout(func, 4000)
exports.api = functions.https.onRequest((request, response) => {
console.log(functions.config())
response.send("Hello from Firebase!");
});
Step 4: run firebase serve inside the firebase folder
Result: You'll get an error like below within 4 seconds
{ Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal metadata.google.internal:80. Error code: ENOTFOUND".
> at FirebaseAppError.FirebaseError [as constructor] (C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\node_modules\firebase-admin\lib\utils\error.js:42:28)
> at FirebaseAppError.PrefixedFirebaseError [as constructor] (C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\node_modules\firebase-admin\lib\utils\error.js:88:28)
> at new FirebaseAppError (C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\node_modules\firebase-admin\lib\utils\error.js:123:28)
> at C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\node_modules\firebase-admin\lib\firebase-app.js:121:23
> at process._tickCallback (internal/process/next_tick.js:68:7)
> errorInfo:
> { code: 'app/invalid-credential',
> message:
> 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following
error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal metadata.google.internal:80. Error code: ENOTFOUND".' },
> codePrefix: 'app' }
Change the code of index.js to the below one:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.api = functions.https.onRequest((req, res) => {
var db = admin.firestore();
db.collection('users').get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
res.send("Hi")
});
Open a web browser and make an http request to the functions to trigger this function and ou'll get below error:
Error getting documents Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
> at GoogleAuth.getApplicationDefaultAsync (C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\node_modules\google-auth-library\build\src\auth\googleauth.js:159:19)
> at process._tickCallback (internal/process/next_tick.js:68:7)
<!-- Provide the steps needed to reproduce the issue with the above test case. -->
I have logged into my firebase account through the CLI, chose a firebase project and I am using firebase-admin with firebase-functions therefore the admin.initializeApp(functions.config().firebase); should've worked out (tried the same function with empty argument also)
Neither the first code is successfully setting claims to a user nor the second code is able to successfully read the database
[debug] [2019-12-29T06:29:53.060Z] ----------------------------------------------------------------------
[debug] [2019-12-29T06:29:53.066Z] Command: C:\Program Files\nodejs\node.exe C:\Users\jishn\AppData\Roaming\npm\node_modules\firebase-tools\lib\bin\firebase.js serve --debug
[debug] [2019-12-29T06:29:53.067Z] CLI Version: 7.11.0
[debug] [2019-12-29T06:29:53.067Z] Platform: win32
[debug] [2019-12-29T06:29:53.068Z] Node Version: v10.16.3
[debug] [2019-12-29T06:29:53.070Z] Time: Sun Dec 29 2019 11:59:53 GMT+0530 (India Standard Time)
[debug] [2019-12-29T06:29:53.070Z] ----------------------------------------------------------------------
[debug] [2019-12-29T06:29:53.070Z]
[debug] [2019-12-29T06:29:53.090Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
[debug] [2019-12-29T06:29:53.115Z] > authorizing via signed-in user
[debug] [2019-12-29T06:29:53.116Z] [iam] checking project status-kgi for permissions ["firebase.projects.get"]
[debug] [2019-12-29T06:29:53.122Z] >>> HTTP REQUEST POST https://cloudresourcemanager.googleapis.com/v1/projects/status-kgi:testIamPermissions
[debug] [2019-12-29T06:29:55.131Z] <<< HTTP RESPONSE 200
[debug] [2019-12-29T06:29:55.204Z] >>> HTTP REQUEST GET https://firebase.googleapis.com/v1beta1/projects/status-kgi
[debug] [2019-12-29T06:29:56.151Z] <<< HTTP RESPONSE 200
[info]
[info] === Serving from 'C:\Users\jishn\WorkSpace\Works\Status\firebase'...
[info]
[debug] [2019-12-29T06:29:56.248Z] >>> HTTP REQUEST GET https://firebase.googleapis.com/v1beta1/projects/status-kgi/webApps/-/config
[debug] [2019-12-29T06:29:57.428Z] <<< HTTP RESPONSE 200
[info] i hosting: Serving hosting files from: public
[info] + hosting: Local server: http://localhost:5000
[warn] ! Your requested "node" version "8" doesn't match your global version "10"
[info] + functions: Emulator started at http://localhost:5001
[info] i functions: Watching "C:\Users\jishn\WorkSpace\Works\Status\firebase\functions" for Cloud Functions...
[debug] [2019-12-29T06:29:58.792Z] [worker-pool] addWorker(~diagnostic~)
[debug] [2019-12-29T06:29:58.835Z] [worker-pool] Adding worker with key ~diagnostic~, total=1
[debug] [2019-12-29T06:29:58.837Z] [worker-pool] submitWork(triggerId=)
[debug] [2019-12-29T06:29:58.966Z] [worker-~diagnostic~-43bc9565-abdd-4eca-b6b4-2b0be30298bb]: Assigning socketPath: \\?\pipe\C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\16940
[debug] [2019-12-29T06:29:58.969Z] [worker-~diagnostic~-43bc9565-abdd-4eca-b6b4-2b0be30298bb]: BUSY
[debug] [2019-12-29T06:30:00.105Z] [runtime-status] [16940] Functions runtime initialized. {"cwd":"C:\\Users\\jishn\\WorkSpace\\Works\\Status\\firebase\\functions","node_version":"10.16.3"}
[debug] [2019-12-29T06:30:00.119Z] [runtime-status] [16940] Disabled runtime features: {"functions_config_helper":true,"network_filtering":true,"timeout":true,"memory_limiting":true,"admin_stubs":true,"pubsub_emulator":true}
[debug] [2019-12-29T06:30:00.308Z] [runtime-status] [16940] Resolved module firebase-admin {"declared":true,"installed":true,"version":"8.9.0","resolution":"C:\\Users\\jishn\\WorkSpace\\Works\\Status\\firebase\\functions\\node_modules\\firebase-admin\\lib\\index.js"}
[debug] [2019-12-29T06:30:00.322Z] [runtime-status] [16940] Resolved module firebase-functions {"declared":true,"installed":true,"version":"3.3.0","resolution":"C:\\Users\\jishn\\WorkSpace\\Works\\Status\\firebase\\functions\\node_modules\\firebase-functions\\lib\\index.js"}
[debug] [2019-12-29T06:30:00.544Z] [runtime-status] [16940] Resolved module firebase-functions {"declared":true,"installed":true,"version":"3.3.0","resolution":"C:\\Users\\jishn\\WorkSpace\\Works\\Status\\firebase\\functions\\node_modules\\firebase-functions\\lib\\index.js"}
[info] + functions[api]: http function initialized (http://localhost:5001/status-kgi/us-central1/api).
[debug] [2019-12-29T06:30:00.562Z] [worker-~diagnostic~-43bc9565-abdd-4eca-b6b4-2b0be30298bb]: IDLE
[debug] [2019-12-29T06:30:09.317Z] [work-queue] {"queueLength":1,"workRunningCount":0}
[debug] [2019-12-29T06:30:09.334Z] [work-queue] {"queueLength":0,"workRunningCount":1}
[debug] [2019-12-29T06:30:09.432Z] Accepted request GET /status-kgi/us-central1/api --> api
[debug] [2019-12-29T06:30:09.441Z] [worker-pool] addWorker(api)
[debug] [2019-12-29T06:30:09.545Z] [worker-pool] Adding worker with key api, total=1
[debug] [2019-12-29T06:30:09.546Z] [worker-pool] submitWork(triggerId=api)
[debug] [2019-12-29T06:30:09.547Z] [worker-api-f1beb878-c6b2-461f-8823-5387d6e32b3d]: Assigning socketPath: \\?\pipe\C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\16256
[debug] [2019-12-29T06:30:09.554Z] [worker-api-f1beb878-c6b2-461f-8823-5387d6e32b3d]: BUSY
[debug] [2019-12-29T06:30:10.602Z] [runtime-status] [16256] Functions runtime initialized. {"cwd":"C:\\Users\\jishn\\WorkSpace\\Works\\Status\\firebase\\functions","node_version":"10.16.3"}
[debug] [2019-12-29T06:30:10.606Z] [runtime-status] [16256] Disabled runtime features: {"functions_config_helper":true,"network_filtering":true,"timeout":true,"memory_limiting":true,"admin_stubs":true,"pubsub_emulator":true}
[debug] [2019-12-29T06:30:10.705Z] [runtime-status] [16256] Resolved module firebase-admin {"declared":true,"installed":true,"version":"8.9.0","resolution":"C:\\Users\\jishn\\WorkSpace\\Works\\Status\\firebase\\functions\\node_modules\\firebase-admin\\lib\\index.js"}
[debug] [2019-12-29T06:30:10.707Z] [runtime-status] [16256] Resolved module firebase-functions {"declared":true,"installed":true,"version":"3.3.0","resolution":"C:\\Users\\jishn\\WorkSpace\\Works\\Status\\firebase\\functions\\node_modules\\firebase-functions\\lib\\index.js"}
[debug] [2019-12-29T06:30:10.709Z] [runtime-status] [16256] Resolved module firebase-functions {"declared":true,"installed":true,"version":"3.3.0","resolution":"C:\\Users\\jishn\\WorkSpace\\Works\\Status\\firebase\\functions\\node_modules\\firebase-functions\\lib\\index.js"}
[debug] [2019-12-29T06:30:10.755Z] [runtime-status] [16256] Trigger "api" has been found, beginning invocation!
[info] i functions: Beginning execution of "api"
[debug] [2019-12-29T06:30:10.811Z] [runtime-status] [16256] triggerDefinition {"httpsTrigger":{},"name":"api","entryPoint":"api"}
[debug] [2019-12-29T06:30:10.812Z] [runtime-status] [16256] Running api in mode HTTPS
[debug] [2019-12-29T06:30:10.813Z] [runtime-status] [16256] Attempting to listen to socketPath: \\?\pipe\C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\16256
[debug] [2019-12-29T06:30:10.818Z] [functions] Runtime ready! Sending request!
[debug] [2019-12-29T06:30:10.915Z] [runtime-status] [16256] Ephemeral server handling GET request
[debug] [2019-12-29T06:30:11.980Z] [runtime-status] [16256] Ephemeral server survived.
[info] i functions: Finished "api" in ~1s
[debug] [2019-12-29T06:30:12.184Z] [worker-api-f1beb878-c6b2-461f-8823-5387d6e32b3d]: IDLE
[debug] [2019-12-29T06:30:12.208Z] [work-queue] {"queueLength":0,"workRunningCount":0}
[info] > Error getting documents Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
[info] > at GoogleAuth.getApplicationDefaultAsync (C:\Users\jishn\WorkSpace\Works\Status\firebase\functions\node_modules\google-auth-library\build\src\auth\googleauth.js:159:19)
[info] > at process._tickCallback (internal/process/next_tick.js:68:7)
ran npm i -g firebase-tools
deleted the enitre firebase folder and tried again
deleted the entire firebase folder again, logged out, logged in and tried again
deleted the entire firebase folder again, tried again and this time I tried accessing firestore instead of auth
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://status-kgi.firebaseio.com"
});
But having to use this kind of admin initialization for cloud functions is not a good idea I think.
Just for your note, I had also posted this question on StackOverflow and one user suggested me post the question in GitHub/firebase and this is a better place for firebase related these kinds of issues.
Link to my StackOverflow question is given below and if someone could solve this issue, please add the same answer to my StackOverflow question also so that I could close that tread as answered;
https://stackoverflow.com/questions/59514309/firebase-admin-on-firebase-functions-is-unable-to-initializeapp-correctly
@AJ-Creations thanks for the detailed error. Instead of admin.initializeApp(functions.config().firebase); try just doing admin.initializeApp();. In most environments (like when running in Cloud Functions) that will automatically discover the correct credentials. Passing functions.config().firebase is an old pattern that we no longer recommend.
@AJ-Creations thanks for the detailed error. Instead of
admin.initializeApp(functions.config().firebase);try just doingadmin.initializeApp();. In most environments (like when running in Cloud Functions) that will automatically discover the correct credentials. Passingfunctions.config().firebaseis an old pattern that we no longer recommend.
I had tried that one also ( Already written in my question )
I have logged into my firebase account through the CLI, chose a firebase project and I am using firebase-admin with firebase-functions therefore the admin.initializeApp(functions.config().firebase); should've worked out (tried the same function with empty argument also)
Still it's not working
I was able to reproduce the same error.
Error getting documents Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for
more information.
at GoogleAuth.getApplicationDefaultAsync (C:\Users\krist\DesktopProjects\FirebaseFunction2functionsnode_modules\google-auth-librarybuild\src\auth\googleauth.js:159:19)
at process._tickCallback (internal/process/next_tick.js:68:7)
Any way to fix this? Thank you!
Ok a few more questions:
1) Do you have the GOOGLE_APPLICATION_CREDENTIALS environment variable set? If so does it point to a service account JSON file for the right project?
2) On your machine is there a file located at $HOME/.config/gcloud/application_default_credentials.json (or the Windows equivalent) and if so does it point to a service account JSON file for the right project?
Note: please do not post your actual service account JSON file on GitHub, that's sensitive secret information. I just want to know if the files above exist and look correct to you.
Ok a few more questions:
- Do you have the
GOOGLE_APPLICATION_CREDENTIALSenvironment variable set? If so does it point to a service account JSON file for the right project?- On your machine is there a file located at
$HOME/.config/gcloud/application_default_credentials.json(or the Windows equivalent) and if so does it point to a service account JSON file for the right project?Note: please do not post your actual service account JSON file on GitHub, that's sensitive secret information. I just want to know if the files above exist and look correct to you.
Since I am having the same problem I will also answer this.
GOOGLE_APPLICATION_CREDENTIALS environment variable set.
Hey @AJ-Creations. We need more information to resolve this issue but there hasn't been an update in 7 days. I'm marking the issue as stale and if there are no new updates in the next 3 days I will close it automatically.
If you have more information that will help us get to the bottom of this, just add a comment!
Looking through some old issues, I believe this was fixed in version 8.5.0 by #2214
This is still present in the latest firebase admin and firebase functions sdk, i can't get authenticated, and get the same error.
Most helpful comment
@AJ-Creations thanks for the detailed error. Instead of
admin.initializeApp(functions.config().firebase);try just doingadmin.initializeApp();. In most environments (like when running in Cloud Functions) that will automatically discover the correct credentials. Passingfunctions.config().firebaseis an old pattern that we no longer recommend.