【问题标题】:Google Cloud Functions - How to correctly setup the default credentials?Google Cloud Functions - 如何正确设置默认凭据?
【发布时间】:2020-03-11 21:13:05
【问题描述】:

我正在使用 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.

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

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

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

我已经试过了:

  • 创建一个新的服务帐号并在功能设置中使用它;
  • 在 Cloud Shell 中使用命令 gcloud auth application-default login
  • 通过 Cloud Shell 将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为 json 文件(我什至不知道这是否有意义);

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

【问题讨论】:

  • 您的目标是哪个节点运行时?顺便说一句,在 Cloud Shell 中设置环境变量不会影响 Cloud Functions 的行为方式。
  • Node.js 8. 是的,这就是我在一段时间后注意到的......我想知道,如果该变量应该是 json 文件的路径,那么该文件应该位于哪里?在我的 GCP 虚拟机中?我不知道,在我找到的页面上也没有这方面的信息。
  • 不过,使它起作用的一件事,(我现在才发现)是在短时间内多次激活该功能,但我不知道它是否总是会那样工作.换句话说,我不确定它是否能正常工作,因为我之前做了一些临时设置,比如gcloud auth application-default login,还是真的会一直这样。
  • 在本地测试时,您应该在本地测试环境(即运行代码的 shell/终端)上设置环境变量。在云中运行时无需额外设置,因为 GCP 运行时会自动为您的代码提供默认凭据。

标签: google-cloud-platform google-cloud-firestore google-cloud-functions firebase-admin


【解决方案1】:

这是我正在使用的代码:

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();

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 2019-02-17
    • 2017-07-13
    • 2017-05-04
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多