对于本地开发,大多数google云客户端库都配置为使用 GOOGLE_APPLICATION_CREDENTIALS
环境变量来定位使用中的服务账户的凭证,然后对该库进行认证。当部署到GCP时,它们同样不需要在代码中进行任何手动认证,而是使用它们的环境在幕后进行认证。这意味着大多数客户端库,比如BigQuery、云存储等,只是在Cloud Functions中工作,而不需要任何代码进行认证。然而, googleapis Nodejs客户端库 不用 GOOGLE_APPLICATION_CREDENTIALS
并且似乎需要在代码中进行手动认证。下面是一个最小的例子,说明我是如何在本地做这件事的。我如何在谷歌云函数中运行这段代码,而不需要将服务账户凭证上传到云函数中?
const { google } = require("googleapis");
const key = require("service_account_credentials.json");
const client = new google.auth.JWT(key.client_email, null, key.private_key, [
"https://www.googleapis.com/auth/spreadsheets",
]);
client.authorize(function (err, tokens) {
const gsapi = google.sheets({ version: "v4", auth: client });
const opt = {
spreadsheetId: "spreadsheetId",
range: "Sheet1!A:T",
};
gsapi.spreadsheets.values.get(opt).then(res => console.log(res));
});
我设法找到了一个解决方案,在 readme.md
的googleapis nodejs github repo。为了解决我的问题,我使用。
async function main() {
const auth = new google.auth.GoogleAuth({
scopes: ["https://www.googleapis.com/auth/spreadsheets"],
});
const authClient = await auth.getClient();
const project = await auth.getProjectId();
const gsapi = google.sheets({ version: "v4", auth: authClient });
const opt = {
spreadsheetId: "spreadsheetID",
range: "Sheet1!A:T",
};
gsapi.spreadsheets.values.get(opt).then(res => console.log(res.data.values));
}