Skip to content

drg-adaptive/api-gateway-request-signer

Repository files navigation

API Gateway Request Signer

Build Status Maintainability npm version FOSSA Status

Sign requests to IAM authorized API Gateway APIs

Usage

First, create an instance of the client

import ApiGatewaySigner from "api-gateway-request-signer";

const apiSigner = new ApiGatewaySigner({
  endpoint: "https://API_GATEWAY_ID.execute-api.REGION.amazonaws.com/STAGE",
  region: "us-east-1"
});

Now, when you want to make a call to the api, create a signed request

const request = apiSigner.signRequest({
  method: HttpMethods.GET,
  path: `/path/to/some/resource`
});

Finally you're ready to actually make the request.

const result = await axios.get(request.url, { headers: request.headers });

Making Requests with Exponential Backoff

The ApiGatewaySigner has a convenience method called makeRequestWithRetries. Simply provide it with the same parameters as signRequest and a callback and it will take care of automatically retrying requests.

const data = await apiSigner.makeRequestWithRetries(
  {
    method: HttpMethods.GET,
    path: `/path/to/some/resource`
  },
  request => axios.get(request.url, { headers: request.headers }),
  3 // Number of times to retry the request
);

The method calls your callback with the signed request. If the callback throws an exception, then it is called again after a short delay.

The last parameter is optional, and it determines the number of times to retry the request. By default it's set to 5.

Credentials

To sign your request the library requires a set of credentials. You can provide these credentials as part of the initial config, or in environment variables.

Configuration

You can specify the credentials to sign requests with by passing them into the constructor using the accessKey, secretKey, and sessionToken config parameters.

const apiSigner = new ApiGatewaySigner({
  endpoint: "https://API_GATEWAY_ID.execute-api.REGION.amazonaws.com/STAGE",
  region: "us-east-1",

  accessKey: "SOME_KEY",
  secretKey: "SECRET",
  sessionToken: "SESSION_TOKEN"
});

Environment Variables

If values aren't provided in the constructor, the values of the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN environment variables will be used. These values will be populated by default in a lambda runtime environment.

See Lambda Environment Variables for more information.

License

FOSSA Status