google-cloud-platform - 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"
}
}
我已经尝试过:
- 创建一个新的服务帐户并在功能设置中使用它;
- 使用
gcloud auth application-default login
Cloud Shell 中的命令; - 通过 Cloud Shell将环境变量设置
GOOGLE_APPLICATION_CREDENTIALS
为 json 文件(我什至不知道这是否有意义);
但似乎没有任何效果:(我如何配置这个默认凭据,这样我就不必再次配置它?比如,整个项目的永久设置,这样我的所有功能都可以访问 Firestore、BigQuery、IoT Core等没有问题。
解决方案
这是我正在使用的代码:
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();
推荐阅读
- python-3.7 - 递归删除超过 2 年的文件(具有特定扩展名,如 .zip、.log 等)
- c++ - 是否依赖 GCC/LLVM 的 `-fexceptions` 技术上未定义的行为?
- python - 是否有充分的理由在单元测试事务中捕获异常?
- netsuite - RCRD_DSNT_EXIST 在使用 aftersubmit 函数创建用户事件脚本时
- javascript - 在 noUiSlider 两个句柄中,是否总是从左端到最小值,从右端到最大值?
- javascript - 看不到 JSON 响应
- ruby-on-rails - 预编译资产的生产版本和开发版本之间的区别?
- ios - DYLD,未加载库 - 仅在试飞中发生
- java - 如何将音频剪辑转换为数组以执行 FFT?
- selenium - 使用 contains(node()) AND contains(@attribute) 通过 xpath 查找元素