Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What is going on with this article?
@tomiyan

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

More than 3 years have 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"

参考資料

6
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
tomiyan
最近はAPI Gateway、Lambda、k8sを主にやっています
kurashicom
「北欧、暮らしの道具店」を運営するクラシコムのエンジニアチーム。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
6
Help us understand the problem. What is going on with this article?