AWS ApiGateway Singing HTTP Requests

JS
S
JavaScript

Complete example of signing a HTTP GET Request located on AWS Api Gateway.

1const axios = require('axios');
2const aws4 = require('aws4');
3const URL = require('url');
4
5// ...
6
7const getDocs = async() => {
8  // Sign HTTP Requests (API Gateway protected via AWS IAM) *by adding token headers
9  let url = URL.parse(apiEndpoint);
10  const opts = {
11    host: url.hostname,
12    path: url.pathname
13  };
14
15  aws4.sign(opts);
16  const axiosRequest = axios.create({
17    baseURL: apiEndpoint,
18    timeout: 5000,
19    headers: {
20      'Host': opts.headers['Host'],
21      'X-Amz-Date': opts.headers['X-Amz-Date'],
22      'Authorization': opts.headers['Authorization'],
23      'X-Amz-Security-Token': opts.headers['X-Amz-Security-Token']
24    }
25  });
26  const data = await axiosRequest.get()
27    .then((res) => {
28      return res.data;
29    })
30    .catch((error) => {
31      console.log('error from axios', error);
32      return [];
33    })
34  return data;
35}

Created on 2/2/2019