Node.js
AWS
cognito
APIGateway

API GatewayをCognito(Unauth)でNode.jsからリクエストしてみた

More than 1 year has passed since last update.

API Gateway、Cognito、IAMの設定はクラスメソッドさんの『Amazon API Gateway の API を Cognito で認証して呼び出す』を参考にしてください


検証バージョン


  • Node.js 0.10.41

  • npm


    • aws-sdk 2.4.4

    • aws4 1.41




ソースコード

AWSのregion、CognitoのIdentityPoolId、API Gatewayのhostname、pathは環境に応じて変更してください

var https = require('https')

, aws4 = require('aws4')
, AWS = require('aws-sdk')
, region = 'ap-northeast-1'
;

var cognitoOptions = {
IdentityPoolId: 'YOUR_COGNITO_IDENTITY_POOL_ID'
};
var httpOptions = {
service: 'execute-api',
region: region,
hostname: 'YOUR_API_ID.execute-api.ap-northeast-1.amazonaws.com',
path: '/prod/resorucePath',
method: 'GET'
};

getCredentials(cognitoOptions, function (error, credentials) {
request(httpOptions, credentials, function (error, body) {
console.log('body: ', body);
});
});

function getCredentials(options, done) {
AWS.config.region = region;
var cognitoidentity = new AWS.CognitoIdentity();
cognitoidentity.getId(options, function (err, objectHavingIdentityId) {
if (err) return done(err);
cognitoidentity.getCredentialsForIdentity(objectHavingIdentityId, function (err, data) {
if (err) return done(err);
var credentials = {
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretKey,
sessionToken: data.Credentials.SessionToken
};
done(null, credentials);
});
});
}

function request(options, credentials, done) {
var signedOptions = aws4.sign(options, credentials);
var req = https.request(signedOptions, function (res) {
var body = '';
console.log('statusCode: ', res.statusCode);
console.log('headers: ', res.headers);
res.setEncoding('utf8');
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function (res) {
done(null, body);
});
});
req.on('error', function (error) {
done(error);
});
req.end();
}


実行結果

statusCode:  200

headers: { 'content-type': 'application/json',
'content-length': '6',
connection: 'keep-alive',
date: 'Sat, 02 Jul 2016 00:42:07 GMT',
'access-control-allow-origin': '*',
'x-amzn-requestid': 'cd98a1d5-3fed-11e6-b0fe-e73602f4978c',
'x-cache': 'Miss from cloudfront',
via: '1.1 7f150809b0d3f0320b40d49f5756b015.cloudfront.net (CloudFront)',
'x-amz-cf-id': 'CEebYad9DSFzmLrsPKwxLyCaGhgSXr4z4VniqNr9oJzVcXo9DuFzrQ==' }
body: "hoge"


参考資料