API Gateway에서 IAM 인증을 활성화하면 요청에 서명이 필요하다.
로컬 환경에서 TypeScript로 IAM 인증 요청을 보내는 구현을 정리한다.
환경
- 로컬 환경에서 실행
- Node.js(또는 Bun)에서 동작
구현
AWS SDK for JavaScript의 SignatureV4 를 사용해 요청에 서명을 추가한다.
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, },});포인트
fromIni로 AWS 프로파일에서 인증 정보를 읽는다HttpRequest로 요청 객체를 만든다SignatureV4로 요청에 서명한다fetch로 서명된 헤더를 포함해 요청을 보낸다
정리
AWS SDK for JavaScript의 SignatureV4 를 사용하면 IAM 인증이 적용된 API Gateway에 로컬 환경에서 쉽게 요청할 수 있다.
인증 정보는 AWS 프로파일에서 읽어 오므로 코드 안에 크레덴셜을 직접 넣을 필요가 없다.
hsb.horse