【问题标题】:Could not load the default credentials? (Node.js Google Compute Engine)无法加载默认凭据? (Node.js 谷歌计算引擎)
【发布时间】:2021-01-02 02:52:43
【问题描述】:

我正在尝试使用 GCP 的 Nodejs 客户端库创建一个新的虚拟机,我点击了以下链接, https://googleapis.dev/nodejs/compute/latest/VM.html#create

下面是我的代码

const Compute = require('@google-cloud/compute');
const {auth} = require('google-auth-library');
const compute = new Compute();

var cred = "<<<credential json content as string>>>";

auth.scopes = ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/compute'];
auth.jsonContent = JSON.parse(cred);


const config = { 
    machineType: 'n1-standard-1', 
    disks: [ { 
        boot: true, 
        initializeParams: { sourceImage: '<<<image url>>>' } 
    } ], 
    networkInterfaces: [ { network: 'global/networks/default' } ], 
    tags: [ { items: [ 'debian-server', 'http-server' ] } ],
    auth: auth, 
};
async function main() {
    // [START gce_create_vm]
  
    async function createVM() {
      const zone = compute.zone('us-central1-c');
      const vm = zone.vm('vm-name');
      await vm.create(config).then(function(data) {
        const vm = data[0];
        const operation = data[1];
        const apiResponse = data[2];
      });

      console.log(vm);
      console.log('Virtual machine created!');
    }
    createVM().catch(function (err) {
        console.log(err);
   });
    // [END gce_create_vm]
}
  
main();

当我运行它时,我得到的错误是

Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
    at GoogleAuth.getApplicationDefaultAsync (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:155:19)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async GoogleAuth.getClient (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:487:17)
    at async GoogleAuth.authorizeRequest (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:528:24)

我的方案是从字符串变量而不是从 env var 或其他东西中获取服务帐户凭据。
我可以看到它正在尝试采用在我的情况下不存在的默认凭据。
我能够在java中实现这一点,但在这里我无法做到。任何帮助将不胜感激。

【问题讨论】:

  • 请注意,由于将此服务帐户签入您的代码中存在风险,因此强烈建议您不要将其作为字符串放入您的代码中。环境变量是最佳实践。
  • 谢谢@JenPerson。我理解这种担忧。考虑我有 3 个用户,并且我已将凭据存储在保险库或安全位置,并且基于用户,我将从服务器检索凭据并执行操作。我该怎么做以及有哪些选择。 ps:我不想将它们存储在谷歌存储桶中

标签: node.js google-cloud-platform google-api google-compute-engine google-api-nodejs-client


【解决方案1】:

为了使用您自己的用户凭据临时执行您的本地应用程序以进行 API 访问,您可以运行:

gcloud auth application-default login
  • 您必须将install sdk 输入您的计算机,这样您才能运行代码。
  • 然后登录到您关联的 gmail 帐户,您就可以准备好了。
  • 您可以查看以下documentation,以获取更多信息。

另一个选项是设置GOOGLE_APPLICATION_CREDENTIALS 为您的应用程序代码提供身份验证凭据。它应该指向一个定义凭据的文件。

要获取此文件,请按照以下步骤操作:

  1. 导航到 Cloud Console 中的 APIs & Services→Credentials 面板。
  2. 选择创建凭据,然后从下拉菜单中选择API 密钥
  3. API 密钥已创建对话框显示您新创建的密钥。
  4. 您可能希望复制您的密钥并确保其安全。除非您使用的是稍后打算删除的测试密钥。
  5. 将您刚刚下载的 *.json 文件放在您选择的目录中。
  6. 此目录必须是私有的(您不能让任何人访问此目录),但您的 Web 服务器代码可以访问。 您可以编写自己的代码将服务帐号密钥传递给客户端库,或将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为下载的 JSON 文件的路径。

我发现以下code 解释了如何使用 Google Cloud 客户端库对 Google Cloud Platform API 进行身份验证。

/**
 * Demonstrates how to authenticate to Google Cloud Platform APIs using the
 * Google Cloud Client Libraries.
 */

'use strict';

const authCloudImplicit = async () => {
  // [START auth_cloud_implicit]
  // Imports the Google Cloud client library.
  const {Storage} = require('@google-cloud/storage');

  // Instantiates a client. If you don't specify credentials when constructing
  // the client, the client library will look for credentials in the
  // environment.
  const storage = new Storage();
  // Makes an authenticated API request.
  async function listBuckets() {
    try {
      const results = await storage.getBuckets();

      const [buckets] = results;

      console.log('Buckets:');
      buckets.forEach((bucket) => {
        console.log(bucket.name);
      });
    } catch (err) {
      console.error('ERROR:', err);
    }
  }
  listBuckets();
  // [END auth_cloud_implicit]
};

const authCloudExplicit = async ({projectId, keyFilename}) => {
  // [START auth_cloud_explicit]
  // Imports the Google Cloud client library.
  const {Storage} = require('@google-cloud/storage');

  // Instantiates a client. Explicitly use service account credentials by
  // specifying the private key file. All clients in google-cloud-node have this
  // helper, see https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
  // const projectId = 'project-id'
  // const keyFilename = '/path/to/keyfile.json'
  const storage = new Storage({projectId, keyFilename});

  // Makes an authenticated API request.
  async function listBuckets() {
    try {
      const [buckets] = await storage.getBuckets();

      console.log('Buckets:');
      buckets.forEach((bucket) => {
        console.log(bucket.name);
      });
    } catch (err) {
      console.error('ERROR:', err);
    }
  }
  listBuckets();
  // [END auth_cloud_explicit]
};

const cli = require(`yargs`)
  .demand(1)
  .command(
    `auth-cloud-implicit`,
    `Loads credentials implicitly.`,
    {},
    authCloudImplicit
  )
  .command(
    `auth-cloud-explicit`,
    `Loads credentials explicitly.`,
    {
      projectId: {
        alias: 'p',
        default: process.env.GOOGLE_CLOUD_PROJECT,
      },
      keyFilename: {
        alias: 'k',
        default: process.env.GOOGLE_APPLICATION_CREDENTIALS,
      },
    },
    authCloudExplicit
  )
  .example(`node $0 implicit`, `Loads credentials implicitly.`)
  .example(`node $0 explicit`, `Loads credentials explicitly.`)
  .wrap(120)
  .recommendCommands()
  .epilogue(
    `For more information, see https://cloud.google.com/docs/authentication`
  )
  .help()
  .strict();

if (module === require.main) {
  cli.parse(process.argv.slice(2));
}

您可以在此link 中获得有关此的更多信息,也可以查看Getting started with authentication 的其他指南。

编辑 1

要从本地文件加载您的凭据,您可以使用以下内容:

const Compute = require('@google-cloud/compute');
const compute = new Compute({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json'
});

您可以查看此link 以获取更多示例和信息。 另一个link 包含另一个可能有用的示例。

【讨论】:

  • 感谢您的回复,只是想知道,有什么方法可以使用凭据而不将它们存储在存储桶中。
  • 没有必要,只要您按照我在第一个解决方法中提到的那样先进行身份验证,暂时使用您自己的用户凭据进行 API 访问。
  • 嗨@Jose,我已经更新了上面的场景,请看一下
  • @smootherbug 我已经更新了我的原始答案,请检查最后的编辑。
  • GoogleAuth { checkIsGCE:未定义,jsonContent:null,cachedCredential:null,_cachedProjectId:'proj-id',keyFilename:'>',范围:['googleapis.com/auth/compute' ], clientOptions: undefined } 在这个密钥文件中,名称工作正常,但是当我尝试传递范围或 jsonContent 时,它没有使用它们。它只是这样工作吗,还是我错过了什么
猜你喜欢
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 2013-12-05
  • 2014-09-13
相关资源
最近更新 更多