node.js - 将 Google Cloud Function 作为其他 Google API 上的服务帐户进行身份验证

标签 node.js authentication google-cloud-functions

我有一个在 Google Cloud Functions 上运行的 HTTP 触发函数,它使用 require('googleapis').sheets('v4') 将数据写入文档电子表格。

对于本地开发,我通过开发者控制台的 Service Accounts 部分添加了一个帐户。我下载了 token 文件(下面的 dev-key.json)并使用它来验证我对 Sheets API 的请求,如下所示:

var API_ACCT = require("./dev-key.json");
let apiClient = new google.auth.JWT(
  API_ACCT.client_email, null, API_ACCT.private_key,
  ['https://www.googleapis.com/auth/spreadsheets']
);

exports.myFunc = function (req, res) {
  var newRows = extract_rows_from_my_client_app_request(req);
  sheets.spreadsheets.values.append({
    auth: apiClient,
    // ...
    resource: { values:newRows }
  }, function (e) {
    if (e) res.status(500).json({err:"Sheets API is unhappy"});
    else res.status(201).json({ok:true})
  });
};

在我与服务帐户的“电子邮件地址”共享我的电子表格后,例如local-devserver@foobar-bazbuzz-123456.iam.gserviceaccount.com — 成功了!

但是,当我将它部署到 Google Cloud Functions 服务时,我想知道是否有更好的方法来处理凭据?我的代码是否可以自动验证自身而无需将 JWT key 文件与部署捆绑在一起?

我注意到在我的函数运行时设置了一个 FUNCTION_IDENTITY=foobar-bazbuzz-123456@appspot.gserviceaccount.com 环境变量,但我不知道如何在 auth 我的 googleapis 调用的值。 code for google.auth.getApplicationDefault 不使用它。

将私有(private) JWT token 与我的 GCF 代码一起上传是否被认为是好的做法?或者我应该以某种方式使用 metadata server 吗?或者是否有一种内置方法可以让 Cloud Functions 向其他 Google API 验证自己的身份?

最佳答案

将凭据与函数部署捆绑在一起是很常见的。只是不要将它们 checkin 您的源代码管理。 Cloud Functions for Firebase samples在需要的地方做这件事。例如,从 Cloud Storage 创建签名 URL 需要管理员凭据,并且 this sample说明了将该凭据保存到文件中以使用函数进行部署。

关于node.js - 将 Google Cloud Function 作为其他 Google API 上的服务帐户进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771037/

相关文章:

firebase - Firestore 移动到 Firebase 函数中的时间戳

javascript - 将 MySQL 行从 .exec(err,rows) 返回到 Sails JS 中的函数(我不想发送行作为响应)

authentication - native 应用程序中第一方身份验证的最佳实践

c# - Flickr API 中不可用的操作的 Flickr 自动化(如添加联系人)

ruby-on-rails - Ruby on Rails 身份验证可在登录前记住上一页

ios - 如何通过 firebase 函数将数据传递给 Paypal?

javascript - 如何在 Node.js 中传输和保存 spawnSync 进程的输出?

node.js - 在容器中运行 webserver 之前将文件从主机复制到 docker 容器

Node.js - tcp 服务器关闭事件处理程序不起作用

node.js - 尝试将谷歌云功能与 node.js 一起使用时,admin.firestore 不是一个功能