LoginSignup
0
0

More than 3 years have passed since last update.

【Node.js】LambdaでIAMからcredentialsを取得しAPIGateway実行

Last updated at Posted at 2019-12-21

試したいこと

image.png
上図のように、APIGatewayを実行するIAMポリシーがアタッチされているLambdaのIAMロールを使ってAPIGatewayの認証を行うことが今回行いたいことです。サービス間のAPI連携なんかでは、実装方針の一つになるかと思います。
APIGatewayを実行するIAMポリシーのアタッチ、Lambda関数やAPIGatewayの作成手順は割愛しています。

処理フロー

  1. LambdaがIAMのSTSよりCredentialsを取得する
  2. 取得したCredentialsを付与してAPIGatewayにRequest
  3. APIGatewayでは受け取ったCredentialsの検証を行い、認証認可を行う

Lambdaの実装

今回、LambdaはNode.js v10で実装しています。
まず、libフォルダを作成し、その配下にAPI実行処理コードを作成、モジュール化します。
以下のような実装です。

execute.js
var AWS = require('aws-sdk');
//create a object which executes APIGateway.
const apigClientFactory = require('aws-api-gateway-client').default;
//get credentials of AWS sercvices
const apiExe = AWS.config.credentials.get(function (err) {
    if (!err) {
        //get required parameters from credentials and set required configurations
        const apigClient = apigClientFactory.newClient({
            accessKey: AWS.config.credentials.accessKeyId,
            secretKey: AWS.config.credentials.secretAccessKey,
            sessionToken: AWS.config.credentials.sessionToken,
            region: 'xx-xxxx-x',
            invokeUrl: 'https://XXXXXXXXXXXXXXXXXXXXXXX'
        });
        const params = {
        };
        //set HTTP configurations
        const pathTemplate = '/xxxx';
        const method = 'GET';
        const additionalParams = {
            queryParams: {
            }
        };
        const body = {};
        apigClient.invokeApi(params, pathTemplate, method, additionalParams, body)
            .then(function (result) {
                console.log(result.data);
            })
            .catch(function (result) {
                console.log(result);
            });
    } else {
        console.log(err);
    }
});
module.exports = apiExe;

aws-sdkを使って、credentialsを取得します。
ちなみに、APIGatewayの実行にはaws-api-gateway-clientというライブラリを使用しています。
このようにして作成したAPIGateway認証&実行モジュールを下記のようなLambdaで実行します。

index.js
var apiExe = require("./lib/execute.js")

exports.handler = function(event, context) {
    apiExe;
};

これで処理は完了です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0