logo hsb.horse
← 블로그 목록으로 돌아가기

블로그

IAM 인증이 켜진 API Gateway에 TypeScript로 요청하기

AWS SDK for JavaScript의 SigV4를 사용해 로컬 환경의 TypeScript 코드에서 IAM 인증이 적용된 API Gateway로 요청을 보내는 구현 방법.

게시일:

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,
},
});

포인트

  1. fromIni 로 AWS 프로파일에서 인증 정보를 읽는다
  2. HttpRequest 로 요청 객체를 만든다
  3. SignatureV4 로 요청에 서명한다
  4. fetch 로 서명된 헤더를 포함해 요청을 보낸다

정리

AWS SDK for JavaScript의 SignatureV4 를 사용하면 IAM 인증이 적용된 API Gateway에 로컬 환경에서 쉽게 요청할 수 있다.

인증 정보는 AWS 프로파일에서 읽어 오므로 코드 안에 크레덴셜을 직접 넣을 필요가 없다.