LoginSignup
1
0

More than 1 year has passed since last update.

AWS CDKでAPI GatewayのLambdaプロキシ統合とAPIキーを同時に使う

Posted at

やり方

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の中で認証書いてるのかなぁ?
誰かのお役に立てば幸いです。

ではまた!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0