やり方
Stackだけ抜粋しますが、これでOK!
import { Stack, App, StackProps } from 'aws-cdk-lib';
import { Runtime, Architecture } from 'aws-cdk-lib/aws-lambda';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { LambdaRestApi } from 'aws-cdk-lib/aws-apigateway';
export class ExampleApiStack extends Stack {
constructor(scope: App, id: string, props?: StackProps) {
super(scope, id, props);
const lambda = new NodejsFunction(this, 'Lambda', {
runtime: Runtime.NODEJS_18_X,
architecture: Architecture.ARM_64,
handler: 'handler',
entry: 'lambda/index.ts',
functionName: `example-api`,
});
// ↓ここから大事!!!
const api = new LambdaRestApi(this, `example-api-endpoint`, {
handler: lambda,
// APIキーをすべてのメソッドに対して必須に設定
defaultMethodOptions: { apiKeyRequired: true },
});
// APIキーを作成(中身は自動生成されるのでWebコンソールから確認)
const apiKey = api.addApiKey('ApiKey', { apiKeyName: `example-api-key` });
// 使用量プランを作ってAPIキー・API・ステージを紐付け
const plan = api.addUsagePlan('UsagePlan', { name: `example-api-usageplan` });
plan.addApiKey(apiKey);
plan.addApiStage({ stage: api.deploymentStage });
}
}
「new LambdaRestApi()
のオプションにdefaultMethodOptions: { apiKeyRequired: true }
を渡す」って情報が、探しても全然見つからなくてハマりました。分かってみれば簡単ですね。
余談
例えばこんな記事とかあるんですが、
https://blog.exploringserverless.com/aws-cdk-101-api-gateway-construct-throttle-quota-usageplans-api-keys
const eventGateway = new apigw.LambdaRestApi(this, 'EventEndpoint', {
handler: eventEntry,
proxy: false
});
proxy: false
してLambdaプロキシ統合を外して、
const eventHandler: apigw.LambdaIntegration = new apigw.LambdaIntegration(eventEntry);
const event = eventGateway.root.addResource('event');
const eventMethod: apigw.Method = event.addMethod('POST', eventHandler, {
apiKeyRequired: false
});
自分でaddMethod('POST')
とかしてるんですけど、
こんなことしなくても、最初の例でシンプルに行けますからね!
けっこう需要あると思うんだけど情報が少ない。みんな割り切ってLambdaの中で認証書いてるのかなぁ?
誰かのお役に立てば幸いです。
ではまた!