首页 > 解决方案 > firebase-functions 上的 firebase-admin 无法正确初始化 App

问题描述

我试图使用 firebase 云功能和 firebase-admin 组合来为我的用户添加 auth 声明创建路由。我正在使用 firebase serve 对其进行测试,并尝试了以下代码:

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)


// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.api = functions.https.onRequest((request, response) => {
console.log(functions.config())
 response.send("Hello from Firebase!");
});

这实际上并没有奏效,并给了我以下错误:

{ 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' }

一篇博客文章说,如果我想在 firebase-admin 中使用除 firestore 和实时数据库以外的任何东西,我必须做一些额外的配置,所以我尝试使用以下代码测试 firestore 是否正常工作:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

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")
});

它再次给了我另一个与管理员凭据本身相关的错误:

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)

functions.config()返回{}

无论发生什么都发生在命令 firebase serve 上。 下面的代码适用于 serviceAccount.json 文件:

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://status-kgi.firebaseio.com"
});

但是我认为必须对云功能使用这种管理员初始化并不是一个好主意。

标签: google-cloud-firestorefirebase-authenticationgoogle-cloud-functionsfirebase-adminfirebase-cli

解决方案


来自 Github 问题解决:

查看一些旧问题,我相信这已在版本 8.5.0 中由 #2214 修复

解决方法如下:

const admin = require('firebase-admin');
admin.initializeApp(); // no neeed for functions.config().firebase

推荐阅读