Javascript 无法加载默认凭据?(Node.js 谷歌计算引擎教程)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42043611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:51:25  来源:igfitidea点击:

Could not load the default credentials? (Node.js Google Compute Engine tutorial)

javascriptnode.jsgoogle-cloud-platformgoogle-compute-engine

提问by Coder1000

SITUATION:

情况:

I follow this tutorial: https://cloud.google.com/nodejs/tutorials/bookshelf-on-compute-engine

我遵循本教程:https: //cloud.google.com/nodejs/tutorials/bookshelf-on-compute-engine

Everything works fine until I do npm startand go to:

一切正常,直到我这样做npm start并转到:

http://localhost:8080

http://本地主机:8080

I am met with the following text on the blank page:

我在空白页上看到以下文字:

Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.

Which makes no sense since I am using OAuth. I followed the link and read the page, but I have no GOOGLE-APPLICATION-CREDENTIALSfield anywhere, and nothing about it in the tutorial.

这是没有意义的,因为我使用的是 OAuth。我点击了链接并阅读了该页面,但我在任何GOOGLE-APPLICATION-CREDENTIALS地方都没有任何字段,教程中也没有任何相关内容。



QUESTION:

题:

Could you please reproduce the steps and tell me if you get the same result ?

您能否重现这些步骤并告诉我您是否得到相同的结果?

(takes 5 minutes)

(需要 5 分钟)

If not, what could I have done wrong ?

如果没有,我可能做错了什么?

回答by newbreedofgeek

Yes, I had the same error. It's annoying cause Google Cloud Platform docs for their "getting started" bookshelf tutorial does not mention this anywhere. Which means that any new developer who tries this tutorial will see this error.

是的,我有同样的错误。这很烦人,因为谷歌云平台文档的“入门”书架教程没有在任何地方提到这一点。这意味着任何尝试本教程的新开发人员都会看到此错误。

Read this: https://developers.google.com/identity/protocols/application-default-credentials

阅读:https: //developers.google.com/identity/protocols/application-default-credentials

I fixed this issue by running: gcloud auth application-default login

我通过运行解决了这个问题: gcloud auth application-default login

In order to run thisgcloud auth application-default loginVisit: https://cloud.google.com/sdk/install1) You have to install sdk into your computer 2) That will enable you to run the code 3) Log in to your associated gmail account then you are good to go!

为了运行此gcloud auth application-default login访问:https: //cloud.google.com/sdk/install1) 您必须将 sdk 安装到您的计算机 2) 这将使您能够运行代码 3) 然后登录到您关联的 Gmail 帐户你已准备好出发!

This will make you login, and after that you code locally will use that authentication.

这将使您登录,然后您在本地编码将使用该身份验证。

回答by Caner

There are 2 solutions for this problem. One option, as mentioned by others, is to use gcloud auth application-default login

这个问题有2个解决方案。正如其他人所提到的,一种选择是使用gcloud auth application-default login

Second option is to set the environment variable GOOGLE_APPLICATION_CREDENTIALS. It should point to a file that defines the credentials. To get this file you need to follow these steps:

第二个选项是设置环境变量GOOGLE_APPLICATION_CREDENTIALS。它应该指向定义凭据的文件。要获取此文件,您需要执行以下步骤:

Go to the API Console Credentials page.

From the project drop-down, select your project.

On the Credentials page, select the Create credentials drop-down, then select Service account key.

From the Service account drop-down, select an existing service account or create a new one.

For Key type, select the JSON key option, then select Create. The file automatically downloads to your computer.

Put the *.json file you just downloaded in a directory of your choosing.

This directory must be private (you can't let anyone get access to this), but accessible to your web server code.

Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file downloaded.

转到 API 控制台凭据页面。

从项目下拉列表中,选择您的项目。

在凭据页面上,选择创建凭据下拉列表,然后选择服务帐户密钥。

从服务帐户下拉列表中,选择一个现有的服务帐户或创建一个新的服务帐户。

对于密钥类型,选择 JSON 密钥选项,然后选择创建。该文件会自动下载到您的计算机。

将您刚刚下载的 *.json 文件放在您选择的目录中。

此目录必须是私有的(您不能让任何人访问此目录),但您的 Web 服务器代码可以访问该目录。

将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为下载的 JSON 文件的路径。

See https://developers.google.com/identity/protocols/application-default-credentialsfor details

有关详细信息,请参阅https://developers.google.com/identity/protocols/application-default-credentials

回答by jdobry

If you're running the app locally, then the gcloud beta auth application-default logincommand should suffice for acquiring local credentials (I updated the tutorialto say so).

如果您在本地运行该应用程序,那么该gcloud beta auth application-default login命令应该足以获取本地凭据(我更新了教程以说明这一点)。

When running the app on Google Compute Engine, if the Compute Engine instance was created with the proper scopes (cloud-platformshould be sufficient) then the app will authenticate with Google Cloud Platform APIs automatically without any extra work on your part.

在 Google Compute Engine 上运行应用程序时,如果 Compute Engine 实例是使用适当的范围创建的(cloud-platform应该足够了),那么应用程序将自动使用 Google Cloud Platform API 进行身份验证,而无需您进行任何额外的工作。

回答by Blasanka

I got this error because of initially I did like below:

我收到此错误是因为最初我喜欢以下内容:

var admin = require("firebase-admin");
admin.initializeApp(); // I didnt add anything because firebaserc file include appName

It worked when I deployed the functions but not in serve. So this is how I solved it:

当我部署这些功能时它有效,但在serve. 所以这就是我解决它的方法:

  • Go to the firebase Project settings(click on setting icon from side nav).
  • Click on the Service accounts.
  • Copy the admin sdk configuration snippetfrom selecting your pro. lang.
  • 转到 firebase项目设置(单击侧面导航中的设置图标)。
  • 单击服务帐户
  • 从选择您的专业版中复制admin sdk 配置片段。朗。

Ex (node.js):

前(node.js):

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

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

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://your-domain.firebaseio.com"
});
  • Now we need to add serviceAccountKey.jsonfile.
  • Click on the Manage service account permissionsin top right corner.
  • Now, you will see services accounts for your project, in the table find the row with column name nameand value firebase-adminsdk, in that row click on Actiondots and select Create key.
  • From the pop up dialog select Key typeas jsonand press createbutton.
  • You will prompt to download the file, download it to your functionsdirectory in project(You can customize this as you want and if you pushing to github, make sure to ignore that file).
  • Now, if you save it into the same directory where you are initializeApp(), access that file like: ./socialape-15456-68dfdc857c55.json(In my case, both files are located: functions/index.jsand functions/services.sonin functionsdirectory and in index.jsfile, I initialed my firebase adminsdk).
  • 现在我们需要添加serviceAccountKey.json文件。
  • 单击右上角的管理服务帐户权限
  • 现在,您将看到您的项目的服务帐户,在表中找到具有列名称名称和值firebase-adminsdk 的行,在该行中单击操作点并选择创建密钥
  • 从弹出对话框中选择密钥类型json并按创建按钮。
  • 您将提示下载文件,将其下载到项目中的函数目录(您可以根据需要自定义它,如果您推送到 github,请确保忽略该文件)。
  • 现在,如果您将它保存到您所在的同一目录中initializeApp(),请访问该文件,例如:(./socialape-15456-68dfdc857c55.json在我的情况下,两个文件都位于:functions/index.js并且functions/services.sonfunctions目录和index.js文件中,我初始化了我的firebase adminsdk)。

Ex(node.js):

前(节点.js):

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

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

var serviceAccount = require("./myapp-15456-68dfdc857c55.json");

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

It's a best and good idea to create .envfile and include your file there and access it as others mentioned. I leave that part to you.

创建.env文件并将您的文件包含在其中并像其他人提到的那样访问它是一个最好的主意。我把那部分留给你。

Hope this help someone on the planet. Regards!

希望这能帮助地球上的某个人。问候!

回答by Bira

  1. Create a service account key using and download the json file. https://console.cloud.google.com/apis/credentials/serviceaccountkey

  2. Add this to your ENV file

    GOOGLE_APPLICATION_CREDENTIALS = "<PATH_TO_SERVICE_ACCOUNT_JSON_FILE>"

  1. 使用并下载 json 文件创建服务帐户密钥。https://console.cloud.google.com/apis/credentials/serviceaccountkey

  2. 将此添加到您的 ENV 文件中

    GOOGLE_APPLICATION_CREDENTIALS = "<PATH_TO_SERVICE_ACCOUNT_JSON_FILE>"

E.g:

例如:

GOOGLE_APPLICATION_CREDENTIALS=/Users/hello/Documents/ssh/my-10ebbbc8b3df.json

回答by HMaziad

Go here: https://firebase.google.com/docs/admin/setup#initialize_the_sdkand follow the instructions to create a private key. Then after you have downloaded your private key open command prompt in the project directory and do the following command:

转到此处:https: //firebase.google.com/docs/admin/setup#initialize_the_sdk并按照说明创建私钥。然后在您下载了您的私钥后,在项目目录中打开命令提示符并执行以下命令:

 set GOOGLE_APPLICATION_CREDENTIALS=C:\YOUR-PATH\YOUR-KEY.json

回答by MAITRAIYA MALI

use this to solve your issue. this actually works:- just put credential parameter and give reference to your key to it.

使用它来解决您的问题。这实际上有效:-只需放置凭据参数并引用您的密钥即可。

const serviceAccount = require('../key.json');
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

回答by arg0100

I also had this error problem, here I had not created the object of

我也有这个错误问题,这里我没有创建对象

keyFilename (stores the credentials of the api)

keyFilename(存储 api 的凭据)

in the sessionClient object for nodejs app.

在 nodejs 应用程序的 sessionClient 对象中。

const sessionClient = new dialogflow.SessionsClient({
                keyFilename: "./keyCredentials.json"  
       });
        
           const sessionPath = sessionClient.sessionPath(projectId, sessionId);

To download 'keyCredentials.json' goto:

要下载“keyCredentials.json”,请转到:

https://console.cloud.google.com/apis/credentials/serviceaccountkey

https://console.cloud.google.com/apis/credentials/serviceaccountkey

Also add the path of this file to the system variables

还要将此文件的路径添加到系统变量中

  1. In windows open powershell
  2. type GOOGLE_APPLICATION_CREDENTIALS = [PATH_TO_SERVICE_ACCOUNT_JSON_FILE]
  1. 在 Windows 中打开 powershell
  2. 输入 GOOGLE_APPLICATION_CREDENTIALS = [PATH_TO_SERVICE_ACCOUNT_JSON_FILE]

回答by Wayne Smallman

Although this question has been answered multiple times, I found myself in a situation not explained here.

虽然这个问题已经被多次回答,但我发现自己处于一种没有在这里解释的情况。

After I created the variable: $GOOGLE_APPLICATION_CREDENTIALS, I was getting the same error as Coder1000.

在创建变量 $GOOGLE_APPLICATION_CREDENTIALS 后,我遇到了与 Coder1000 相同的错误。

However, I was running both: nodemonand: npm run devin two separate sessions in Terminal, neither of which were aware of the variable.

但是,我在终端中的两个单独会话中同时运行:nodemon和:npm run dev,这两个会话都不知道该变量。

Once I: shut the tabs down; added new tabs; and ran the commands again, the application was able to access the variable.

一旦我:关闭标签;添加了新标签;并再次运行命令,应用程序能够访问该变量。

回答by slideshowp2

I provide another way which is set the credentials manually. For local development and running on GCP, like Cloud Function, Compute Engine.

我提供了另一种手动设置凭据的方法。用于本地开发并在 GCP 上运行,例如 Cloud Function、Compute Engine。

You can use a service account and grant this service account proper permission. e.g. Cloud Trace Admin

您可以使用服务帐户并授予此服务帐户适当的权限。例如云跟踪管理员

Set private_key, client_emailand projectIdoptions for any GCP client library. These options you can get from the service account json file.

为任何 GCP 客户端库设置private_keyclient_emailprojectId选项。您可以从服务帐户 json 文件中获取这些选项。

For example, I am using Cloud Trace Node.js client library in my cloud functions.

例如,我在云函数中使用 Cloud Trace Node.js 客户端库。

Before I set the credentialsand projectId, I got this error:

在我设置credentialsand之前projectId,我收到了这个错误:

Error: Unexpected error while acquiring application default credentials: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentialsfor more information. at GoogleAuth. (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:248:31) at step (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:47:23) at Object.next (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:28:53) at fulfilled (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:19:58) at at process._tickDomainCallback (internal/process/next_tick.js:229:7)

错误:获取应用程序默认凭据时出现意外错误:无法加载默认凭据。浏览到https://developers.google.com/accounts/docs/application-default-credentials了解更多信息。在 GoogleAuth。(/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:248:31) 在步骤 (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js: 47:23) 在 Object.next (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:28:53) 在完成 (/srv/node_modules/google-auth-library/build/ src/auth/googleauth.js:19:58) 在 process._tickDomainCallback (internal/process/next_tick.js:229:7)

You can pass the credentialsand projectIdas environment variables. After setting credentialsand projectId, the error is gone.

您可以将credentialsprojectId作为环境变量传递。设置credentials和 后projectId,错误消失。

const tracer = require('@google-cloud/trace-agent').start({
    samplingRate: 0,
    bufferSize: 1,
    credentials: {
      client_email: process.env.CLIENT_EMAIL,
      private_key: process.env.TRACE_AGENT_ADMIN,
    },
    projectId: process.env.X_GOOGLE_GCLOUD_PROJECT || process.env.PROJECT_ID,
  });

X_GOOGLE_GCLOUD_PROJECTis a built-in environment variable for cloud function runtime

X_GOOGLE_GCLOUD_PROJECT是云函数运行时的内置环境变量