由于缺少 "private_key",服务器端的 firebase 管理员身份验证失败

firebase admin authentication fails on server side due to missing "private_key"

我在 google firebase 上托管一个 node.js 函数,我想在 服务器端 创建和更新用户帐户。我的服务帐户 json 文件如下所示:

{
    "apiKey"           : ""
    "authDomain"       : ""
    "databaseURL"      : ""
    "projectId"        : ""
    "storageBucket"    : ""
    "messagingSenderId": ""
}

出于某些原因,我删除了这些字段。当我加载凭证并通过以下方式创建 admin 实例时:

import * as admin     from 'firebase-admin'    ;
import * as functions from 'firebase-functions';

const accountKeyPath = path.join(__dirname, '../credentials/serviceAccountKey.json')
const accountKey     = require(accountKeyPath);

const firebaseAdmin = admin.initializeApp( accountKey );

firebaseAdmin足以crud一个数据库。但是它不能创建新用户,除非我声明它:

const firebaseAdmin = admin.initializeApp({
      credential: admin.credential.cert(accountKey)
    , databaseURL: "..."
});

大概是这样。当我 运行 出现此错误时:

            throw new 

error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
            ^

Error: Certificate object must contain a string "private_key" property.

这对我来说是莫名其妙的,因为我不知道如何使用 private_key 获得服务帐户 json。我是否应该在每次 运行 服务器时都创建一个?

您的 JSON 对于 firebase-admin SDK 完全不正确。请参阅有关如何检索服务帐户 JSON 文件的文档:https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app

它应该具有以下格式:

{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/example@iam.gserviceaccount.com"
}

编辑:

我注意到您正在导入 firebase-functions,在这种情况下您根本不需要服务帐户 JSON。只需致电:

admin.initializeApp(functions.config().firebase);

https://firebase.google.com/docs/admin/setup#initialize_the_sdk