首页 > 解决方案 > Google Cloud Functions - 如何正确设置默认凭据?

问题描述

我正在使用 Google Cloud Functions 收听 Pub/Sub 中的主题并将数据发送到 Firestore 中的集合。问题是:每当我测试函数(使用 GCP 中提供的测试选项卡)并检查该函数的日志时,它总是抛出这个错误:

Error: Could not load the default credentials.
Browse to https://cloud.google.com/docs/authentication/getting-started for more information.

顺便说一句,该链接没有帮助,因为他们说应用程序默认凭据是自动找到的,但这里不是这种情况。

这就是我使用 Firestore 的方式,在index.js

const admin = require('firebase-admin')
admin.initializeApp()
var db = admin.firestore()
// ...
db.collection('...').add(doc)

在我的package.json中,这些是依赖项(我也在使用 BigQuery,这会引发相同的错误):

{
  "name": "[function name]",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/pubsub": "^0.18.0",
    "@google-cloud/bigquery": "^4.3.0",
    "firebase-admin": "^8.6.1"
  }
}

我已经尝试过:

但似乎没有任何效果:(我如何配置这个默认凭据,这样我就不必再次配置它?比如,整个项目的永久设置,这样我的所有功能都可以访问 Firestore、BigQuery、IoT Core等没有问题。

标签: google-cloud-platformgoogle-cloud-firestoregoogle-cloud-functionsfirebase-admin

解决方案


这是我正在使用的代码:

const firebase = require('firebase');
const functions = require('firebase-functions');
const admin = require('firebase-admin');

const serviceAccount = require("./key.json");



const config = {
    credential: admin.credential.cert(serviceAccount),
    apiKey: "",
    authDomain: "project.firebaseapp.com",
    databaseURL: "https://project.firebaseio.com",
    projectId: "project",
    storageBucket: "project.appspot.com",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
 };

 firebase.initializeApp(config);
 const db = admin.firestore();

推荐阅读