통합검색

AWS

AWS PHP sdk로 API Gateway 에 api 키 생성, 사용량계획 연결, 키 삭제


 

API Gateway에 요율 및 제한량을 api 유저별로 개별 설정해 주기 위해 api 키 생성후 사용량 계획 연결이 필요한데,
php sdk를 통해 api 키 생성 및 미리 만들어 놓은 사용량계획을 연결해 주는 방법.


[!]IAM 에서 access key 와 secret key 생성[/!]
아래 링크를 접속하여 IAM 에서 API에 사용할 access key 와 secret key를 미리 생성해둔다.
https://console.aws.amazon.com/iam/home?region=ap-northeast-2#/security_credentials


[!]키 생성 및 사용계획 연결[/!]
아래와 같이 구현 가능한데, region, 사용량계획id 등을 적절히 수정해준다.
use Aws\Credentials\Credentials;
use Aws\Signature\SignatureV4;
use Aws\ApiGateway\ApiGatewayClient;

// signature 생성
$accessKey = 'access key';
$secretKey = 'srcret key';

// AWS 자격 증명 및 API Gateway 클라이언트 설정
$credentials = new Credentials($accessKey, $secretKey);
$apiGatewayClient = new ApiGatewayClient([
    'region' => 'ap-northeast-2',
    'version' => 'latest',
    'credentials' => $credentials,
    'signature' => new SignatureV4('apigateway', 'ap-northeast-2') // region 설정
]);

// API 키 생성
$result = $apiGatewayClient->createApiKey([
    'name' => 'userskey123', // 중복되지 않는 고유한 이름으로 수정
    'enabled' => true, // 활성화 여부
    'description' => 'hello', // 메모
    'value' => 'codehere'.rand(), // 코드를 수동 생성하려면 입력.
]);
$apiKeyId = $result['id']; // 성공 결과 값에서 생성된 key의 id를 가져옴

// 사용량계획 연결
$result = $apiGatewayClient->createUsagePlanKey([
    'keyId' => $apiKeyId, // 위에서 생성한 키 id
    'usagePlanId' => 'plan id hear', // 미리 만들어 놓은 사용량 계획 ID
    'keyType' => 'API_KEY'
]);


[!]키 삭제[/!]
키 생성시 DB에 별도 저장한 키 id로 삭제를 수행한다.
use Aws\Credentials\Credentials;
use Aws\Signature\SignatureV4;
use Aws\ApiGateway\ApiGatewayClient;

// signature 생성
$accessKey = 'access key';
$secretKey = 'srcret key';

// AWS 자격 증명 및 API Gateway 클라이언트 설정
$credentials = new Credentials($accessKey, $secretKey);
$apiGatewayClient = new ApiGatewayClient([
    'region' => 'ap-northeast-2',
    'version' => 'latest',
    'credentials' => $credentials,
    'signature' => new SignatureV4('apigateway', 'ap-northeast-2') // region 설정
]);

// 삭제할 API 키의 ID
$apiKeyIdToDelete = 'DB에 별도 보관한 키 ID 입력';

// API 키 삭제
$apiGatewayClient->deleteApiKey([
    'apiKey' => $apiKeyIdToDelete,
]);