代码之家  ›  专栏  ›  技术社区  ›  xiaolingxiao

由于缺少“私钥”,服务器端firebase管理员身份验证失败

  •  1
  • xiaolingxiao  · 技术社区  · 8 年前

    我正在主持一个 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.
    

    这对我来说是无法解释的,因为我不知道如何获得服务帐户 json 具有 private_key .我是不是每次运行服务器都要创建一个?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Cisco    8 年前

    您的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

    推荐文章