typescript 如何确保我的API网关拒绝格式不正确的JSON?

rqqzpn5f  于 2023-02-10  发布在  TypeScript
关注(0)|答案(1)|浏览(113)
    • 问题:**

API Gateway目前正在接受发送给它的所有JSON,并返回200响应。这不是首选用例,我希望创建一个关于哪些字段是必需的意见。也许,在调用的Lambda中使用Typescript Interface来返回500响应。

    • 步骤构想:**

1.数据发送到API网关

  1. JSON由被调用的Lambda接收
  2. Lambda使用类型脚本Interface
    1.发现JSON的格式不正确
  3. API网关发送正确的响应代码,通知发送者JSON中的必填字段尚未收到或不正确(例如,数字不是字符串)。

***注意:***正在生成CDK中的所有资源。

hzbexzde

hzbexzde1#

有很多方法可以做到这一点。例如,如果您使用SAM,请参见下面的代码片段(如果您选择这条路线,则可以使用CDK执行相同的操作)。
在这里,您可以将passthroughBehavior指定为never,以阻止任何无效输入。
此外,您可以指定x-amazon-apigateway-request-validators来验证所有请求头和请求体。
请查看有关如何执行基本请求验证here的文档

MyServerlessApi:
    Type: AWS::Serverless::Api
    Properties:
      # Use DefinitionBody for swagger file so that we can use CloudFormation intrinsic functions within the swagger file
      DefinitionBody:
        "Fn::Transform":
          Name: "AWS::Include"
          Parameters:
            Location: "../../swagger/api.yaml"
      StageName: v1
      EndpointConfiguration: REGIONAL
      TracingEnabled: true # Enable AWS X-Ray to help debug API requests
      MethodSettings:
        - ResourcePath: "/*"
          HttpMethod: "*"
          # Disable data trace in production to avoid logging customer sensitive information from requests and responses
          DataTraceEnabled: true
          LoggingLevel: INFO
          MetricsEnabled: true
          ThrottlingRateLimit: 300
          ThrottlingBurstLimit: 350
      AccessLogSetting:
        DestinationArn: !Sub "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:slsapi1grp"
        Format: '$context.identity.sourceIp $context.authorizer.claims.sub [$context.requestTime] "$context.httpMethod $context.resourcePath $context.protocol" $context.status $context.requestId $context.awsEndpointRequestId $context.xrayTraceId $context.responseLatency $context.integrationLatency "$context.error.message"'
      OpenApiVersion: "3.0.0"
      Cors:
        AllowOrigin: "'*'"
        AllowHeaders: "'authorization, content-type'"

API swagger模式的片段

openapi: 3.0.0

info:
  title:
    Fn::Sub: validate-request
  description: Validation Snippet
  contact:
    email: email@local
  version: 1.0.0

# Enable request validator. 
# See doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-validation-sample-api-swagger.html
x-amazon-apigateway-request-validators:
  "All":
    validateRequestBody: true
    validateRequestParameters: true
  "ValidateHeaderOnly":
    validateRequestBody: false
    validateRequestParameters: true
  "ValidateBodyOnly":
    validateRequestBody: true
    validateRequestParameters: false
x-amazon-apigateway-request-validator: "All" # Validate Header and Body

x-amazon-apigateway-gateway-responses:
  # Provide more detailed error message for bad request body errors. 
  # See doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-gateway-responses.html
  BAD_REQUEST_BODY:
    responseTemplates:
      application/json: '{"errorCode": "BadRequestBody", "message": "$context.error.validationErrorString"}'
    responseParameters:
      gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
  DEFAULT_4XX:
    responseParameters:
      gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
  DEFAULT_5XX:
    responseParameters:
      gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
paths:
  /api:
    post:
      operationId: Create
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateInput"
        required: true
      responses:
        "201":
          description: "Create"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Details"
        "400":
          description: "Bad Request Exception"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BadRequestException"
        "401":
          description: "Unauthorized Exception"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/UnauthorizedException"
        "409":
          description: "Conflict Exception"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ConflictException"
        "429":
          description: "Too Many Requests Exception"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TooManyRequestsException"
        "500":
          description: "Internal Server Error"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/InternalServerErrorException"
      x-amazon-apigateway-integration:
        uri:
          Fn::Sub: arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyServerlessApi.Arn}:live/invocations
        httpMethod: POST
        type: aws_proxy
        passthroughBehavior: never # do not send incorrectly formatted input
      security:
        - tokenAuthorizer: []

相关问题