Lambda Authorizerでカスタムのエラーメッセージを出力したい時。
Lambda Proxy統合の場合ステータスコードが変更できないのでDenyポリシーを返す403限定ではありますが、context変数にエラーメッセージ等を格納し、ゲートウェイレスポンスのレスポンステンプレートを編集することで可能です。
context変数はこちらのドキュメントにそって定義します。
Amazon API Gateway Lambda オーソライザーからの出力 - Amazon API Gateway
レスポンステンプレートはCloudFormation的にはこんな感じで定義します。
この例でいうと、context.message
とcontext.code
をLambdaの方で定義します。
GatewayResponse:
Type: "AWS::ApiGateway::GatewayResponse"
Properties:
ResponseTemplates:
application/json: >
{"message":"$context.authorizer.message", "code":"$context.authorizer.code"}
ResponseType: DEFAULT_4XX
RestApiId: !Ref ResourceApi