我有一个在Google Cloud Functions上运行的HTTP触发函数,它使用 require('googleapis').sheets('v4')
将数据写入文档电子表格 .
对于本地开发,我通过其开发人员控制台的Service Accounts部分添加了一个帐户 . 我下载了令牌文件(下面的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})
});
};
用我的服务帐户"email address"分享我的电子表格后,例如 local-devserver@foobar-bazbuzz-123456.iam.gserviceaccount.com
- 它有效!
但是,当我将其部署到Google Cloud Functions服务时,我想知道是否有更好的方法来处理凭据?我的代码可以自动验证自身,而无需将JWT密钥文件与部署捆绑在一起吗?
我注意到我的函数运行时设置了一个 FUNCTION_IDENTITY=foobar-bazbuzz-123456@appspot.gserviceaccount.com
环境变量,但我不知道如何在我的googleapis调用的 auth
值中使用它 . code for google.auth.getApplicationDefault不使用它 .
将私有JWT令牌与我的GCF代码一起上传是否可行?或者我应该以某种方式使用metadata server?或者 Cloud 端功能是否已经可以通过内置方式对其他Google API进行身份验证?
1 回答
它's common to bundle credentials with a function deployment. Just don' t检查它们到你的源代码管理 . Cloud Functions for Firebase samples在需要的地方这样做 . 例如,从 Cloud 存储创建签名URL需要管理员凭据,this sample说明将该凭据保存到要与这些功能一起部署的文件中 .