首页 > 解决方案 > 如何在 AWS::Serverless::Api 的 AWS SAM 模板中添加请求验证器?

问题描述

我正在尝试使用 AWS SAM 将请求验证器资源链接到 SAM 模板中的无服务器 API。我已经创建了请求验证器并在其 RestApiId 中引用了 API,但验证器没有在 AWS 控制台中设置为 API 默认验证器选项。

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
    Discription for the template
Globals:
  Function:
    Timeout: 30

Resources:
  MyAPI:
    Type: AWS::Serverless::Api
    Properties:
      Name: MyAPI
      StageName: prod
      Auth:
        DefaultAuthorizer: MyAuthorizer
        Authorizers:
            MyAuthorizer:
              FunctionPayloadType: REQUEST
              FunctionArn: here goes the function Arn
              Identity:
                Context:
                  - identity.sourceIp
                ReauthorizeEvery: 60
      Models:
        RequestModel:
          $schema: 'http://json-schema.org/draft-04/mySchema#'
          type: object
          properties:
            Format:
              type: string
            Name:
              type: string
              minLength: 3
            Id:
              type: string
          required:
            - Format
            - Id

  RequestValidator:
    Type: AWS::ApiGateway::RequestValidator
    Properties:
      Name: RequestValidator
      RestApiId: !Ref MyAPI
      ValidateRequestBody: true

  LambdaFunction:
    Type: AWS::Serverless::Function 
    Properties:
      FunctionName: NameOfTheFunction
      CodeUri: ./src/folder/
      Handler: Project::nameSpace.class::Handler
      Runtime: dotnetcore2.1
      Environment: 
        Variables:
          variableA : value
          variableB : value
          variableC : value
          variableD : value
      Events:
        ApiEndpoint:
          Type: Api
          Properties:
            RestApiId: !Ref MyAPI
            Path: /path
            Method: post
            RequestValidatorId: !Ref RequestValidator
            Auth:
              Authorizer: MyAuthorizer
            RequestModel: 
              Model: RequestModel
              Required: true

验证器被创建,如果我单击 API 上的请求验证器下拉菜单,我可以看到它。但是,请求验证器并不默认为我定义的验证器。它只是将 None 作为选定选项

标签: amazon-web-servicesaws-api-gatewayjson-schema-validatoraws-sam

解决方案


我通过源代码搜索了 api 转换函数,没有办法附加请求验证。SAM 将 AWS::Serverless::Api 转换为内联 body swagger/openapi 定义,但对于 x-amazon-apigateway-request-validator 没有任何内容。我不明白为什么只有在 api 方法中附加模式部分时才能在 lambda 事件中定义模型

"paths": {
  "/post": {
    "post": {
      "requestBody": {
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/user"
            }
          }
        }, 
        "required": true
      }, 

也许在 SAM github 中添加功能请求


推荐阅读