AWS SAM-通过SAM模板在API网关方法中强制执行请求验证

时间:2020-02-07 08:19:41

标签: amazon-web-services aws-lambda aws-api-gateway serverless aws-serverless

我正在使用具有API网关作为事件源的具有lambda函数的SAM应用程序进行工作。 API端点是一种POST方法,在请求正文中需要一组参数。 API网关通过使用AWS Console指定请求模型为我们提供了验证请求主体的功能。

请参阅下面的AWS控制台选项的屏幕截图:

enter image description here

enter image description here

我需要通过SAM模板设置类似的选项,并且可以将模型链接到请求正文,但是无法设置请求验证器选项,并且无法找到任何文档或示例。

下面是我的SAM模板

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Description: SAM Template

Parameters: 
  Stage: 
    Type: String
    Default: dev

Resources:
  MyApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      Name: My AWS Serverless API
      StageName: !Ref Stage
      Models: 
        ExchangeRate: 
          $schema: "http://json-schema.org/draft-04/schema#"
          properties: 
            base: 
              type: string
            target: 
              type: string
          required: 
            - base
            - target
          title: User
          type: object

  ExchangeRateFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/exchange-rate/
      Handler: index.handler
      Runtime: nodejs12.x
      Description: Function to Get Currency Exchange Rate
      MemorySize: 128
      Timeout: 3
      Policies:
        - AWSLambdaBasicExecutionRole
      Events:
        HelloWorld:
          Type: Api
          Properties:
            RestApiId: !Ref MyApiGateway
            Path: /exchange
            Method: POST
            RequestModel:
              Model: ExchangeRate
              Required: true

Outputs:
  ExchangeRateFunction:
    Description: "Exchange Rate Lambda Function ARN"
    Value: !GetAtt ExchangeRateFunction.Arn
  MyApiGateway:
    Description: "My Seed API EndPoint"
    Value: !Sub "https://${MyApiGateway}.execute-api.${AWS::Region}.amazonaws.com/${Stage}"

参考文件

请让我知道如何使用SAM模板将“请求验证器”设置为“验证正文”选项。会感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,很明显,SAM缺少了此功能,正如您从上一个问题中可以看到的那样:

How to add a request validator in a AWS SAM template for AWS::Serverless::Api?

此外,一些问题已在GitHub中公开,最后一个是:

https://github.com/awslabs/serverless-application-model/issues/1403

我破解了一个在SAM规范中包含两个附加属性的解决方案来解决此问题,但我不希望它真正成为PR。如果您想使用我的分支仓库从developer分支进行部署,我可以提供进一步的说明。