When IAM authentication is enabled on API Gateway, requests must be signed.
This is a TypeScript implementation for sending IAM-authenticated requests from a local environment.
Environment
- Runs from a local environment
- Works on Node.js (or Bun)
Implementation
Use SignatureV4 from the AWS SDK for JavaScript to add a signature to the request.
import { fromIni } from "@aws-sdk/credential-providers";import { SignatureV4 } from "@aws-sdk/signature-v4";import { Sha256 } from "@aws-crypto/sha256-js";import { HttpRequest } from "@aws-sdk/protocol-http";
const credentials = fromIni({ profile: "profile-name" });
const serviceName = "execute-api";
const options = { url: "https://{id}.execute-api.ap-northeast-1.amazonaws.com/", headers: {} as Record<string, string>,};
const url = new URL(options.url);const host = url.hostname;const path = url.pathname;
const req = new HttpRequest({ headers: { Host: host, }, hostname: host, method: "GET", path: path,});
const signer = new SignatureV4({ credentials, region: "ap-northeast-1", service: serviceName, sha256: Sha256,});
const signed = await signer.sign(req);
const response = await fetch(options.url, { headers: { ...signed.headers, Host: host, },});Key Points
- Load credentials from an AWS profile with
fromIni - Build the request object with
HttpRequest - Sign the request with
SignatureV4 - Send the request with
fetchand the signed headers
Summary
Using SignatureV4 from the AWS SDK for JavaScript makes it straightforward to call an IAM-protected API Gateway from a local environment.
Because credentials are loaded from an AWS profile, there is no need to hardcode them in source code.
hsb.horse