コンテンツにスキップ

IAM認証ありAPI GatewayにTypeScriptでリクエストする

  • ひとまずローカル環境から
  • Node.js(or Bun)で動作する
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
}
})