首页 > 解决方案 > 使用 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 的新手,所以任何关于采取哪个方向的建议都将不胜感激。

标签: amazon-web-servicesaws-api-gatewayserverlessservice-accounts

解决方案


已经晚了,但可能会帮助别人。这是我的工作代码。

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


推荐阅读