【问题标题】:google cloud storage node client - credentials not working as expected谷歌云存储节点客户端 - 凭据未按预期工作
【发布时间】:2020-04-08 19:18:23
【问题描述】:

我正在做一个项目,我需要访问 gcloud 存储桶中的一些对象

它适用于 GOOGLE_APPLICATION_CREDENTIALS 环境变量,但当我尝试使用 Storage 构造函数的 keyfilename 选项时却不行。这是一个显示正在发生的事情的最小示例:

const {Storage, File} = require('@google-cloud/storage');
const path = require("path");

// Fake bucket and file names
const bucketname = "my-bucket";
const filename = "test-file.txt";
// Points to a valid key file for a service account with read & write access to the bucket
const keyPath = path.resolve("./key.json");

const storage = new Storage({keyFile: keyPath}); // note that I'm providing a keyFile here
const bucket = storage.bucket(bucketname);
const file = new File(bucket, filename);

async function main() {
  console.log("try without GOOGLE_APPLICATION_CREDENTIALS");
  try {
    await file.download({ destination: "./test.txt" });
    console.log("ok");
    return;
  } catch (e) {
    console.log(e.message);
  }

  console.log("try with GOOGLE_APPLICATION_CREDENTIALS");
  try {
    process.env["GOOGLE_APPLICATION_CREDENTIALS"] = keyPath;
    await file.download({ destination: "./test.txt" });
    console.log("ok");
    return;
  } catch (e) {
    console.log("failed with GOOGLE_APPLICATION_CREDENTIALS");
    console.log(e.message);
  }
}
main();

我希望这个输出是:

try without GOOGLE_APPLICATION_CREDENTIALS
ok

但我得到了

try without GOOGLE_APPLICATION_CREDENTIALS
Anonymous caller does not have storage.objects.get access to my-bucket/test-file.txt.
try with GOOGLE_APPLICATION_CREDENTIALS
ok

这是怎么回事?

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-storage


    【解决方案1】:

    好吧,这很愚蠢,但它可能对某人有所帮助:

    存储构造函数选项对象同时具有KeyFilekeyFilename 选项,具有完全相同的description。 (准确地说,StorageOptions 继承了 GoogleAuthOptions 的那些)

    documentation 只讨论了keyFilename 选项,但我的编辑还向我展示了KeyFile 作为自动完成选项,我使用它并没有考虑太多。

    keyFilename 是你要使用的那个,而不是keyFile(这个是干什么用的?不知道)

    简而言之:

    new Storage({keyFilename: "/path/to/key.json"}); // this works
    new Storage({keyFile: "/path/to/key.json"}); // this doesn't
    

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 2016-03-21
      • 1970-01-01
      • 2017-11-23
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      相关资源
      最近更新 更多