amazon-web-services - 使用 AWS Lambda/API Gateway 授权 google 服务账户
问题描述
我的快递服务器有一个 credentials.json,其中包含一个 google 服务帐户的凭据。这些凭据用于从 google 获取 jwt,并且我的服务器使用该 jwt 来更新服务帐户拥有的 google 表格。
var jwt_client = null;
// load credentials form a local file
fs.readFile('./private/credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content));
});
// get JWT
function authorize(credentials) {
const {client_email, private_key} = credentials;
jwt_client = new google.auth.JWT(client_email, null, private_key, SCOPES);
}
var sheets = google.sheets({version: 'v4', auth: jwt_client });
// at this point i can call google api and make authorized requests
问题是我正在尝试从 node/express 迁移到 npm serverless/aws。我使用相同的代码,但得到 403 - 禁止。
errors:
[ { message: 'The request is missing a valid API key.',
domain: 'global',
reason: 'forbidden' } ] }
研究向我指出了许多事情,包括:AWS Cognito、在环境变量中存储凭证、API 网关中的自定义授权者。所有这些对我来说似乎都是可行的,但我是 AWS 的新手,所以任何关于采取哪个方向的建议都将不胜感激。
解决方案
已经晚了,但可能会帮助别人。这是我的工作代码。
const {google} = require('googleapis');
const KEY = require('./keys');
const _ = require('lodash');
const sheets = google.sheets('v4');
const jwtClient = new google.auth.JWT(
KEY.client_email,
null,
KEY.private_key,
[
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/spreadsheets'
],
null
);
async function getGoogleSheetData() {
await jwtClient.authorize();
const request = {
// The ID of the spreadsheet to retrieve data from.
spreadsheetId: 'put your id here',
// The A1 notation of the values to retrieve.
range: 'put your range here', // TODO: Update placeholder value.
auth: jwtClient,
};
return await sheets.spreadsheets.values.get(request)
}
然后在 lambda 处理程序中调用它。我不喜欢的一件事是将 key.json 作为文件存储在项目根目录中。将尝试找到一些更好的地方来保存。
推荐阅读
- java - 使用 X-Checksum-Sha1 标头和 Apache 的 HTTP 客户端在 Java 中上传到工件时的 409 响应
- r - R中的pivot_wider删除我需要的变量
- ios - 如何快速重新加载部分中的最后一个单元格
- apache-flink - Flink 是否会自动检查 AggregateFunction 的状态以及如何使用 AggregatingStateDescriptor?
- qt - TextInput 文档未指定 onTextChanged 信号
- scala - Scala 中的 Nullablle 支持
- python - 如何将文本/颜色格式应用于多索引 Python 图表?
- amazon-web-services - 在 ECS 中附加卷 EFS
- postgresql - PostgreSQL 自定义聚合:比数组连接更有效的选项
- sql - 仅在窗口分区中查找具有非重复值的行