Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8839

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

$
0
0

試したいこと

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

処理フロー

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

Lambdaの実装

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

execute.js
varAWS=require('aws-sdk');//create a object which executes APIGateway.constapigClientFactory=require('aws-api-gateway-client').default;//get credentials of AWS sercvicesconstapiExe=AWS.config.credentials.get(function(err){if(!err){//get required parameters from credentials and set required configurationsconstapigClient=apigClientFactory.newClient({accessKey:AWS.config.credentials.accessKeyId,secretKey:AWS.config.credentials.secretAccessKey,sessionToken:AWS.config.credentials.sessionToken,region:'xx-xxxx-x',invokeUrl:'https://XXXXXXXXXXXXXXXXXXXXXXX'});constparams={};//set HTTP configurationsconstpathTemplate='/xxxx';constmethod='GET';constadditionalParams={queryParams:{}};constbody={};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 Functionで実行します。

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

これで処理は完了です。


Viewing all articles
Browse latest Browse all 8839

Trending Articles