【Node.js】Lambda에서 IAM으로부터 credentials를 취득해 APIGateway 실행

시도하고 싶은 것




위 그림과 같이 APIGateway를 실행하는 IAM 정책이 첨부된 Lambda의 IAM 역할을 사용하여 APIGateway를 인증하는 것이 이번에 수행하고 싶습니다. 서비스 간의 API 제휴 등에서는 구현 방침의 하나가 될까 생각합니다.
APIGateway를 실행하는 IAM 정책 연결, Lambda 함수 및 APIGateway를 만드는 절차는 생략되었습니다.

처리 흐름


  • Lambda는 IAM의 STS에서 Credentials를 얻습니다.
  • 취득한 Credentials를 부여하고 APIGateway에 Request
  • 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를 사용하여 신원을 얻습니다.
    덧붙여서, APIGateway의 실행에는 aws-api-gateway-client 라는 라이브러리를 사용하고 있습니다.
    이렇게 작성한 APIGateway 인증 및 실행 모듈을 아래와 같은 Lambda에서 실행합니다.

    index.js
    var apiExe = require("./lib/execute.js")
    
    exports.handler = function(event, context) {
        apiExe;
    };
    

    이것으로 처리가 완료됩니다.
  • 좋은 웹페이지 즐겨찾기