【问题标题】:Authorize google service account using AWS Lambda/API Gateway使用 AWS Lambda/API Gateway 授权 google 服务账户
【发布时间】:2020-04-30 20:30:21
【问题描述】:

我的 express 服务器有一个 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 Cognitostoring credentials in environment variablescustom authorizers in API gateway。所有这些对我来说似乎都是可行的,但我是 AWS 的新手,所以任何关于采取哪个方向的建议都将不胜感激。

【问题讨论】:

    标签: amazon-web-services aws-api-gateway serverless service-accounts


    【解决方案1】:

    现在很晚,但可能会帮助其他人。这是我的工作代码。

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

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 2019-12-28
      • 2013-07-23
      • 1970-01-01
      • 2021-01-08
      • 2020-12-23
      • 2016-10-27
      • 2020-09-21
      • 1970-01-01
      相关资源
      最近更新 更多