使用 AWS Lambda/API Gateway 授权 Google 服务账户



我的快递服务器有一个 credentials.json,其中包含 google 服务帐户的凭据。这些凭据用于从谷歌获取 jwt,我的服务器使用该 jwt 来更新服务帐户拥有的谷歌表格。

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无服务器/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作为文件存储在项目根目录中。会尝试找到一些更好的地方来保存。

最新更新