LoginSignup
4
2

More than 3 years have passed since last update.

CDK で API Gateway Mock 統合と Lambda Authorizer を作る

Last updated at Posted at 2020-10-01

CDK(TypeScript) で API Gateway(REST API) の Mock 統合と、Lambda Authorizer を作ってみました。

ソースコード全体はこちらです。
https://github.com/kazfuku/apigateway-java-lambda-authorizer/blob/master/lib/apigateway-java-lambda-authorizer-stack.ts

Mock 統合

Mock 統合はこの部分です。

const mockIntegration = new apigateway.MockIntegration({
  requestTemplates: {
    'application/json': '{"statusCode": 200}'
  },
  integrationResponses: [
    {
      statusCode: '200',
      responseTemplates: {
        'application/json': '{ "message": "mock", "now": "$context.authorizer.now" }'
      }
    }
  ]
});
const method = api.root.addMethod('GET', mockIntegration, {
  methodResponses: [
    {
      statusCode: '200'
    }
  ],
  authorizer: lambdaAuthorizer
});

Mock 統合の仕組み上、リクエストテンプレートとレスポンステンプレートが要ります。
リクエストテンプレートでステータスコードを定義して、レスポンステンプレートでそのステータスコードに対応するレスポンス本文を設定します。

$context.authorizer.now の部分は、Lambda Authorizer が返している現在日時 を指しています。

Lambda Authorizer

Lambda Authorizer はこの部分です。

const authorizerFunction = new lambda.Function(this, 'AuthorizerFunction', {
  runtime: lambda.Runtime.JAVA_8,
  handler: 'com.kazfuku.aws.MapLambdaAuthorizer::handleRequest',
  code: lambda.Code.fromAsset('lambda/authorizer/target/apigateway-java-lambda-authorizer-1.0.jar')
});

const lambdaAuthorizer = new apigateway.RequestAuthorizer(this, 'Authorizer', {
  handler: authorizerFunction,
  identitySources: [IdentitySource.header('Authorization')]
});

Lambda 関数と、API Gateway の Lambda Authorizer (REQUEST タイプ) を定義してます。

最後に、Method に設定するのを忘れずに。

const method = api.root.addMethod('GET', mockIntegration, {
  methodResponses: [
    {
      statusCode: '200'
    }
  ],
  authorizer: lambdaAuthorizer // <----
});

参考

関連記事

この記事は、Java Lambda で API Gateway の Lambda Authorizer を実装する と関連しています。
Java Lambda に興味がある方は、ぜひこちらもご覧ください。

4
2
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
4
2