在 Google 云函数中验证 googleapis 库
Authenticate googleapis library in Google Cloud Function
对于本地开发,大多数 google 云客户端库都配置为使用 GOOGLE_APPLICATION_CREDENTIALS
环境变量来查找正在使用的服务帐户的凭据,然后对该库进行身份验证。当部署到 GCP 时,它们同样不需要在代码中进行任何手动身份验证,而是使用它们的环境在幕后进行身份验证。这意味着大多数客户端库,例如 BigQuery、Cloud Storage 等,只在 Cloud Functions 中工作,不需要任何代码进行身份验证。但是,googleapis Nodejs client library 不使用 GOOGLE_APPLICATION_CREDENTIALS
并且似乎需要在代码中进行手动身份验证。下面是我如何在本地执行此操作的最小示例。我如何在 Google 云功能中 运行 这段代码而不需要将服务帐户凭据上传到云功能?
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));
});
我设法在 googleapis nodejs github 存储库的 readme.md
中找到了解决方案。为了解决我的问题,我使用了:
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));
}
对于本地开发,大多数 google 云客户端库都配置为使用 GOOGLE_APPLICATION_CREDENTIALS
环境变量来查找正在使用的服务帐户的凭据,然后对该库进行身份验证。当部署到 GCP 时,它们同样不需要在代码中进行任何手动身份验证,而是使用它们的环境在幕后进行身份验证。这意味着大多数客户端库,例如 BigQuery、Cloud Storage 等,只在 Cloud Functions 中工作,不需要任何代码进行身份验证。但是,googleapis Nodejs client library 不使用 GOOGLE_APPLICATION_CREDENTIALS
并且似乎需要在代码中进行手动身份验证。下面是我如何在本地执行此操作的最小示例。我如何在 Google 云功能中 运行 这段代码而不需要将服务帐户凭据上传到云功能?
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));
});
我设法在 googleapis nodejs github 存储库的 readme.md
中找到了解决方案。为了解决我的问题,我使用了:
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));
}