简体   繁体   English

错误:无法加载默认凭据(Firebase function 到 firestore)

[英]Error: Could not load the default credentials (Firebase function to firestore)

I am attempting to write an onCall function for Firebase Cloud Functions that performs advanced querying tasks on a firestore database (ie checking a text query up against AutoML natural lang to get a category, etc) but I keep running into a problem trying to query the database from the function:我正在尝试为 Firebase Cloud Functions 编写一个 onCall function,它在 firestore 数据库上执行高级查询任务(即根据 AutoML 自然语言检查文本查询以获得类别等),但我一直在尝试查询时遇到问题来自 function 的数据库:

Error getting documents ::  Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
    at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

Function: Function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.query = functions.https.onCall((data, context) => {
    const text = data.text;
    var results = [];
    const promise = db.collection('providers').get()
    promise.then((snapshot) => {
        console.log('marker');
        snapshot.forEach((doc) => {
            results.push({id: doc.id, data: doc.data()});
        });
        console.log('yessir');
        return {results: results};
    }).catch((err) => {
        console.log('Error getting documents :: ', err)
        console.log('nosir');
        return {results: "no results"};
    });
});

Longer output:更长的 output:

Function execution started
Function execution took 8ms, finished with status code: 200
Error getting documents :: (etc, same error)
nosir

Example 2 (no change in running):示例2(运行没有变化):

Function execution started
Function execution took 1200 ms, finished with status code: 200
marker
yessir

I can't figure out where this problem is coming from or how to resolve it.我不知道这个问题是从哪里来的,也不知道如何解决。 Any help?有什么帮助吗?

Regards.问候。

What I first did to solve it was add my firebase admin sdk key to my project.首先要做的就是将我的 firebase admin sdk 密钥添加到我的项目中。

I downloaded it at我在下载

https://console.firebase.google.com/u/0/project/**YOUR_PROJECT_ID**/settings/serviceaccounts/adminsdk https://console.firebase.google.com/u/0/project/**YOUR_PROJECT_ID**/settings/serviceaccounts/adminsdk

管理员 SDK 密钥下载页面

then at admin.initializeApp();然后在admin.initializeApp(); I changed to:我改为:

admin.initializeApp({
    credential: admin.credential.cert(require('../keys/admin.json'))
});

My folder structure is我的文件夹结构是

├── key
│   ├── admin.json
├── src
│   ├── index.ts

HOWEVER , a better practice and safer approach, as some mentioned already: You could use environment variables to store your credentials, this way you won't commit it to a repository such as Github, keep it safer from safety breaches and won´t make it hardcoded.但是,正如一些人已经提到的那样,一种更好的做法和更安全的方法:您可以使用环境变量来存储您的凭据,这样您就不会将其提交到诸如 Github 之类的存储库中,使其更安全地避免安全漏洞并且不会使它硬编码。

Depending on your project and where you'll deploy it there's a different way to do it.根据您的项目以及您将在何处部署它,有不同的方法可以做到这一点。

There are many tutorials around on how to create and access env variables ( like this one ), but you could use a name it like the example below:有很多关于如何创建和访问 env 变量的教程( 比如这个),但是你可以像下面的例子一样使用它的名字:

GOOGLE_APPLICATION_CREDENTIALS="/home/admin.json"

I had the same error "Could not load the default credentials".我有同样的错误“无法加载默认凭据”。

The error occured after updating my project dependencies with npm update .使用npm update更新我的项目依赖项后发生错误。 More precisely firebase-admin and firebase-functions .更准确地说是 firebase-adminfirebase-functions

Before update:更新前:

"dependencies": {
    "@google-cloud/firestore": "^1.3.0",
    "firebase-admin": "~7.0.0",
    "firebase-functions": "^2.2.0"
}

After update:更新后:

"dependencies": {
    "@google-cloud/firestore": "^1.3.0",
    "firebase-admin": "^8.6.0",
    "firebase-functions": "^3.3.0"
}

I added the serviceAccountKey.json to my project and changed the imports with the code provided at the service account setting of my firebase project.我将serviceAccountKey.json添加到我的项目中,并使用在我的 firebase 项目的服务帐户设置中提供的代码更改了导入。

From:从:

var admin = require('firebase-admin')

admin.initializeApp()

To:至:

var admin = require('firebase-admin');    
var serviceAccount = require('path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://my-project.firebaseio.com'
});

See @Fernando Rocha 's answer below to access the account setting of your firebase project.请参阅下面的@Fernando Rocha的答案以访问您的 firebase 项目的帐户设置。

@aldobaie's answer helped me figure out what was going on for my use case. @aldobaie 的回答帮助我弄清楚我的用例发生了什么。 For those who are not looking to add async/await to all their calls, remember that the firestore calls return promises, so prepending them with return has the same effect.对于那些不想在所有调用中添加 async/await 的人,请记住,firestore 调用 return 承诺,因此在它们前面加上return具有相同的效果。

In my case:就我而言:

function doSomething(...) {
    return admin.firestore().collection(...).doc(...).get()
        .then((doc) => {...})
        .catch(err => {...})
}

module.exports = functions.firestore.document('collection/{docId}').onWrite((change, context) => {
    return doSomething()
})

I think the accepted answer goes against Firebase's recommend configuration.我认为接受的答案与 Firebase 的推荐配置背道而驰。 The function environment has access to admin credentials already, and passing your key in the code is not recommended. function 环境已经可以访问管理员凭据,不建议在代码中传递您的密钥。

I do it like this:我这样做:

const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

I ran into the same problem myself.我自己也遇到了同样的问题。 Sometimes the function works and many times it would through the Error: Could not load the default credentials error.有时 function 可以工作,而且很多时候会出现Error: Could not load the default credentials错误。 The problem I believe have been solved by watching for the Callbacks.我相信通过观察回调已经解决了这个问题。 You have to keep the function running until the callbacks have been called using the await and async prefixes.您必须保持 function 运行,直到使用awaitasync前缀调用回调。

Firebase Cloud Functions don't allow the access to the processor through callbacks once it's been terminated! Firebase 云函数一旦终止就不允许通过回调访问处理器! That's why we get the Error: Could not load the default credentials error.这就是为什么我们得到Error: Could not load the default credentials错误。

So, whenever you have a .then() function prefix it with await and prefix the function it's inside it with async and prefix any call to the function with await .所以,只要你有一个.then() function前缀await它和前缀 function 它在它里面有async和前缀任何对await的调用。

async function registerUser(..) {
    ...
    await admin.firestore().collection(..)...
    ...
}

I hope this helps you out!我希望这可以帮助你!

Another option is to set the service account key in an environmental variable instead of setting it with a call to firebaseAdmin.initializeApp({ credential }) .另一种选择是在环境变量中设置服务帐户密钥,而不是通过调用firebaseAdmin.initializeApp({ credential })来设置它。

Linux Linux

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows PowerShell Windows PowerShell

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

Postscript: An even better option might be to use the local emulator suite .后记:更好的选择可能是使用本地模拟器套件

Alright, so I had this error as well and spent a frustrated few days going over multiple sites, articles, videos, etc to try and figure out the cause of this problem so I could get an adequate answer for both myself and everyone else who is struggling.好的,所以我也遇到了这个错误,并且花了几天的时间浏览多个网站、文章、视频等,试图找出这个问题的原因,这样我就可以为自己和其他所有人都得到一个充分的答案挣扎。

There are answers to this question in this thread already.这个问题已经有这个问题的答案了。 However, I tried following most of them to no avail.但是,我尝试关注其中的大多数都无济于事。 Some have security issues and others are just too vague to follow.有些存在安全问题,有些则太模糊而无法遵循。 I decided to post a thorough answer which also addresses the security issues you would have if you followed some of the other answers.我决定发布一个详尽的答案,该答案还解决了如果您遵循其他一些答案会遇到的安全问题。

Alright now that I've gotten that out of the way lets get started!好吧,现在我已经解决了这个问题,让我们开始吧!

First of all your going to need to go to this link - Getting started with authentication首先,您需要 go 到此链接 - 身份验证入门

You should see this in the center of your screen -您应该在屏幕中央看到这个 - 身份验证入门 Next, click on the button I've marked in green.接下来,单击我标记为绿色的按钮。 This will bring you to the create service account key page.这将带您进入创建服务帐户密钥页面。

You should see a similar screen to the below image -您应该会看到与下图类似的屏幕 - 在此处输入图像描述

  • For the Service Account option, select new service account.对于服务帐户选项,select 新服务帐户。

  • Create a name for your service account.为您的服务帐户创建一个名称。 This is not important, name it whatever you like.这个不重要,随便取个名字就行。

  • For the role option select Project -> Owner对于角色选项 select项目 -> 所有者

  • Finally, select JSON option for key type and then hit create.最后,为密钥类型选择 select JSON 选项,然后点击创建。

This should create and download a.json file.这应该创建并下载一个.json 文件。 Place this file somewhere smart and safe.将此文件放在智能且安全的地方。 I created a folder called 'credentials' in the root of my project and placed it in there.我在项目的根目录中创建了一个名为“credentials”的文件夹并将其放置在其中。

Also I renamed the file to something more readable.此外,我将文件重命名为更具可读性的文件。 While this isn't necessary, following good file/folder naming and structuring practices is important and I would advise you to rename it to something more readable.虽然这不是必需的,但遵循良好的文件/文件夹命名和结构实践很重要,我建议您将其重命名为更具可读性的名称。

(Its important to note that this file is personal and should not be included in any github repositories/firebase production/etc. This file is for you and you alone!) (请务必注意,此文件是个人文件,不应包含在任何 github 存储库/firebase 生产/等中。此文件仅供您和您一个人使用!)

Next open a command prompt window and type in the following command -接下来打开命令提示符 window 并输入以下命令 -

set GOOGLE_APPLICATION_CREDENTIALS=C:\Users\Username\Path\To\File\filename.json设置 GOOGLE_APPLICATION_CREDENTIALS=C:\Users\Username\Path\To\File\filename.json

This will create an environment variable that is linked securely to your credentials which firebase will recognize and use when you make calls to authenticate yourself.这将创建一个环境变量,该变量安全地链接到您的凭据,firebase 在您进行身份验证时将识别并使用该凭据。

(Note - This is the command for windows. If your using mac/linux go to the 'Getting started with Authentication' page mentioned earlier to get the appropriate command for your operating system) (注意 - 这是 windows 的命令。如果您使用 mac/linux go 到前面提到的“验证入门”页面,以获得适用于您的操作系统的适当命令)

There you go, the issue should now be fixed. go,问题现在应该得到解决。 If anyone has any further questions or problems feel free to comment below and i'll do my very best to help you.如果有人有任何进一步的问题或问题,请随时在下面发表评论,我会尽我所能为您提供帮助。 I know how frustrating it can be to be stuck with an error like this.我知道陷入这样的错误是多么令人沮丧。

I hope this helps someone at the very least.我希望这至少可以帮助某人。 Happy Programming.快乐编程。 C.Gadd C.Gadd

I do not want to use @Fernando solution even though there is nothing wrong.即使没有任何问题,我也不想使用@Fernando 解决方案。

I have prd and non-prd environment.我有prd和非prd环境。 I use firebase use command to push the changes to the correct environment.我使用 firebase 使用命令将更改推送到正确的环境。 When I deploy, firebase uses the default service account.当我部署时,firebase 使用默认服务帐户。 Also I do not want to have the keys in the project folder or in my git repo.此外,我不想在项目文件夹或我的 git 存储库中拥有密钥。

The way I solved might not work for others, but want to share here.我解决的方法可能对其他人不起作用,但想在这里分享。

The issue came to me when I updated the permission of the firebase project to give a viewer with editor permission.当我更新 firebase 项目的权限以授予具有编辑权限的查看器时,我遇到了这个问题。 I made that person the owner and rolled back to editor.我让那个人成为所有者并回滚到编辑器。 It went away.它走了。 It is not justifying as a fix, but worked for me and I do not have to download the key.它不能作为修复的理由,但对我有用,我不必下载密钥。

I had same problem in firebase Error: "Could not get default credentials."我在 firebase 中遇到了同样的问题错误:“无法获得默认凭据。”

Then go to firebase console and go to project setting, where you can find Service Accounts option.然后 go 到firebase 控制台和 go 到项目设置,您可以在其中找到服务帐户选项。 Click there and you will see the Generate new private key under your project setting.单击此处,您将在项目设置下看到生成新私钥 Copy code for your project language and add it to your project file.复制项目语言的代码并将其添加到项目文件中。

 var admin = require("firebase-admin"); var serviceAccount = require("path/to/serviceAccountKey.json"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://your-database-url-that-is-given-under-admin-sdk-snippets" });

After Generating the key you will have option to download.生成密钥后,您将可以选择下载。 and put it in the project folder.并将其放在项目文件夹中。 Also set path var serviceAccount = require("path/to/serviceAccountKey.json");还设置路径var serviceAccount = require("path/to/serviceAccountKey.json"); That's it your are ready.那就是你准备好了。

This error can also occur when the cloud function is not terminated properly.当云 function 未正确终止时,也会出现此错误。

Whenever you write a cloud function make sure you return promise after the cloud function processing is over, so that cloud function knows that your process is complete. Whenever you write a cloud function make sure you return promise after the cloud function processing is over, so that cloud function knows that your process is complete.

If you don't return promise then there might be chances where your cloud function might terminate before the processing is complete.如果您不返回 promise,那么您的云 function 可能会在处理完成之前终止。

You can refer this to know how to terminate the cloud function.您可以参考此了解如何终止云 function。 Terminate cloud functions 终止云功能

I had the same issue.我遇到过同样的问题。

  • Go on your settings page on Firebase => Service and Account. Go 在您的设置页面上 Firebase => 服务和帐户。

  • Firebase Setting 1. Parameters 2. Account 3. Download the file and rename it [admin.json] Firebase 设置 1. 参数 2. 账号 3. 下载文件并重命名 [admin.json]

  • Copy the code and paste it复制代码并粘贴

  • Requires 'admin.json' and paste, and run Firebase deploy.需要“admin.json”并粘贴,然后运行 Firebase 部署。

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

also works.也有效。

This is a known bug in Firebase.这是 Firebase 中的一个已知错误。 see the progress here: https://github.com/firebase/firebase-tools/issues/1940在此处查看进度: https://github.com/firebase/firebase-tools/issues/1940

However, meantime there are few options to resolve this:但是,与此同时,解决此问题的选择很少:

1 Explicitly passed via code 1 通过代码显式传递

var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://your-app.firebaseio.com"
});

Not recommended this hard-coding.不推荐这种硬编码。 This json file will not be accessible on server.此 json 文件将无法在服务器上访问。

2 Passed via GOOGLE_APPLICATION_CREDENTIALS 2 通过 GOOGLE_APPLICATION_CREDENTIALS

I'd recommend this way, set environmental variable:我推荐这种方式,设置环境变量:

GOOGLE_APPLICATION_CREDENTIALS=path/to/serviceAccountKey.json

For windows: (considering json is at your root path of project.对于 windows:(考虑到 json 位于项目的根路径中。

using powershell:使用 powershell:

$env:GOOGLE_APPLICATION_CREDENTIALS='serviceAccountKey.json'

using NPM script: (notice no space before &&)使用 NPM 脚本:(注意 && 前没有空格)

"serve": "set GOOGLE_APPLICATION_CREDENTIALS=serviceAccountKey.json&& npm run start",

(for some reason cross-env didn't work) (由于某种原因, cross-env不起作用)

3 Available at a well-known filesystem path due to gcloud 3 由于 gcloud,在众所周知的文件系统路径中可用
by installing gcloud sdk and running gcloud auth application-default login通过安装 gcloud sdk 并运行gcloud auth application-default login

4 Available from the Compute Engine metadata API when running on GCP 4 在 GCP 上运行时可从 Compute Engine 元数据 API 获得

Download your firebase service account into your project and reference it like this:将您的 firebase 服务帐户下载到您的项目中,并像这样引用它:

<code>
  var admin = require("firebase-admin");
  var serviceAccount = require("path/to/serviceAccountKey.json");

  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "<database-url>"
  });
</code>

For those who come here from a serp trying to figure out why their google cloud function fails with:对于那些从 serp 来到这里试图弄清楚为什么他们的谷歌云 function 失败的人:

Error: Could not load the default credentials.错误:无法加载默认凭据。 Browse to https://cloud.google.com/docs/authentication/getting-started for more information.浏览到https://cloud.google.com/docs/authentication/getting-started了解更多信息。 at GoogleAuth.getApplicationDefaultAsync在 GoogleAuth.getApplicationDefaultAsync

but none of the above helped, you can try to update all(?) of your @google/whatever dependencies: npm i -E @google/firestore@latest .但以上都没有帮助,您可以尝试更新所有(?)您的@google/whatever依赖项: npm i -E @google/firestore@latest Then rebuild, deploy, try again.然后重建,部署,再试一次。 It happened to me a few times recently and this worked.最近在我身上发生了几次,这很有效。

I just had the same problem.我只是有同样的问题。 To solve it, just update your node packages by npm update inside your project-dir/functions/ directory.要解决它,只需通过npm update您的项目目录/功能/目录中的节点包。 Finally, deploy again.最后,再次部署。

None of above.以上都没有。 You may just:你可能只是:

firebase login - It will open browser login firebase 登录 - 它将打开浏览器登录

As soon as you do login, returnto console and run:登录后,返回控制台并运行:

firebase init - It will run as successfull. firebase init - 它将成功运行。

On MacOS I had to do the following:在 MacOS 上,我必须执行以下操作:

export GOOGLE_APPLICATION_CREDENTIALS=/Users/myname/serviceAccountKey.json

I was getting credential error because the locally running functions emulator could not securely talk to firebase auth running in production.我收到凭据错误,因为本地运行的功能模拟器无法安全地与生产中运行的 firebase auth 通信。

Google Cloud Reference谷歌云参考

For those who still get the same problem event after downloading account key and using it inside your code, make sure it is inside your functions folder.对于那些在下载帐户密钥并在您的代码中使用它后仍然遇到相同问题事件的人,请确保它在您的函数文件夹中。

One thing it's a bit difficult to find in the docs is the firebase-admin SDK only uses the emulators when environment variables tell it to.在文档中很难找到的一件事是 firebase-admin SDK 仅在环境变量告诉它时才使用模拟器。 If you use the service account JSON key as described in some answers here, firebase-admin will talk to prod (on Google Cloud) rather than the emulated version, even if everything else you're doing is on the emulators.如果您使用服务帐户 JSON 密钥,如此处某些答案中所述,即使您正在执行的其他所有操作都在模拟器上,firebase-admin 也会与 prod(在 Google Cloud 上)而不是模拟版本对话。

Since most likely you would rather use the emulators for local testing, here's how I set my environment variables in Mac ~/.zshrc:由于您很可能更愿意使用模拟器进行本地测试,因此我在 Mac ~/.zshrc 中设置环境变量的方法如下:

export GCLOUD_PROJECT="your-project-id"
export FIRESTORE_EMULATOR_HOST=localhost:8080
export FIREBASE_AUTH_EMULATOR_HOST=localhost:9099
export FIREBASE_DATABASE_EMULATOR_HOST=localhost:9000

The GCLOUD_PROJECT id could be your project id, but apparently any id will work as long as it is a well-formed Firebase project id, so these same environment variables can be used to test all your projects on the Firebase emulators. GCLOUD_PROJECT id 可以是您的项目 id,但显然任何 id 都可以工作,只要它是格式正确的 Firebase 项目 id,因此这些相同的环境变量可用于在 Firebase 模拟器上测试您的所有项目。 Try setting these environment variables first for emulator use before you try any of the other solutions.在尝试任何其他解决方案之前,请先尝试设置这些环境变量以供模拟器使用。

Another oddity is firebase emulators:start needs these environment variables set, but firebase emulators:exec sets them automagically.另一个奇怪的是 firebase emulators:start 需要设置这些环境变量,但 firebase emulators:exec 会自动设置它们。 When you are in a CI scenario:exec is the better choice, but when actively running tests as you write code having the emulators stay up and running with:start is a faster loop and you'll need the environment variables for it to work properly.当您处于 CI 场景中时:exec 是更好的选择,但是当您在编写代码时主动运行测试时,让模拟器保持正常运行:start 是一个更快的循环,您需要环境变量才能使其正常工作. By having these in environment variables, your code won't need to change at all when deployed to the Cloud.通过在环境变量中包含这些,您的代码在部署到云时根本不需要更改。

I just had this issue and fixed it with我刚遇到这个问题并用

firebase login

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Firebase 函数访问 Firestore 错误:无法加载默认凭据 - Firebase Functions Accessing Firestore error: Could not load the default credentials Ruby的Firestore-无法加载默认凭据 - Firestore from Ruby - Could not load the default credentials Firebase 云函数:获取应用程序默认凭据时出现意外错误。 无法加载默认凭据 - Firebase cloud functions: Unexpected error while acquiring application default credentials. Could not load the default credentials Firebase 函数:无法加载默认凭据 - Firebase Functions: Could not load default credentials 错误:无法加载默认凭据 — 凭据很好,function 死了 - Error: could not load the default credentials — creds are fine, function dies 错误:无法加载默认凭据。 上下文:firebase 登录:ci 和 firebase 身份验证:导出 - Error: Could not load the default credentials. context: firebase login:ci AND firebase auth:export TwiML 应用程序和 Firebase 抛出未处理的承诺拒绝:错误:无法加载默认凭据 - TwiML app and Firebase throwing Unhandled promise rejection: Error: Could not load the default credentials admin.auth().verifyIdToken(idToken) 错误:在 8.0.0 之后无法使用 firebase-admin 加载默认凭据 - admin.auth().verifyIdToken(idToken) Error: Could not load the default credentials whith firebase-admin after to 8.0.0 尝试通过 Next.js API 路由上的 admin.firestore.v1.FirestoreAdminClient 导出备份。 错误:无法加载默认凭据 - Trying to export backup via admin.firestore.v1.FirestoreAdminClient on a Next.js API route. Error: Could not load the default credentials 错误:无法加载默认凭据。 - 云功能 - Error: Could not load the default credentials. - Cloud Functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM