在 API Gateway 中设置基本请求验证 - Amazon API Gateway
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

在 API Gateway 中设置基本请求验证

本节介绍如何使用控制台、Amazon CLI 和 OpenAPI 定义为 API Gateway 设置请求验证。

使用 API Gateway 控制台设置请求验证

您可以使用 API Gateway 控制台从 API 请求的三个验证程序中选择一个来验证请求:

  • 验证正文

  • 验证查询字符串参数和标头

  • 验证正文、查询字符串参数和标头

当您对 API 方法应用以上一种验证程序时,API Gateway 控制台会向 API 的 RequestValidators 映射添加该验证程序。

要按本教程操作,您将使用 Amazon CloudFormation 模板来创建不完整的 API Gateway API。此 API 拥有的 /validator 资源具有 GETPOST 方法。两种方法都与 http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP 端点集成。您将配置两种请求验证:

  • GET 方法中,您将为 URL 查询字符串参数配置请求验证。

  • POST 方法中,您将为请求正文配置请求验证。

这将只允许特定的 API 调用传递给 API。

下载并解压缩适用于 Amazon CloudFormation 的应用程序创建模板。您将使用此模板创建不完整的 API。您将在 API Gateway 控制台中完成其余步骤。

创建 Amazon CloudFormation 堆栈
  1. 打开 Amazon CloudFormation 控制台,地址:https://console.aws.amazon.com/cloudformation

  2. 选择创建堆栈,然后选择使用新资源(标准)

  3. 对于指定模板,选择上传模板文件

  4. 选择您下载的模板。

  5. 选择下一步

  6. 对于堆栈名称,输入 request-validation-tutorial-console,然后选择下一步

  7. 对于配置堆栈选项,请选择下一步

  8. 对于功能,请确认 Amazon CloudFormation 可以在您的账户中创建 IAM 资源。

  9. 选择提交

Amazon CloudFormation 预置在模板中指定的资源。完成资源预置可能需要几分钟时间。当 Amazon CloudFormation 堆栈的状态为 CREATE_COMPLETE 时,您就可以继续下一步了。

选择您新创建的 API
  1. 选择新创建的 request-validation-tutorial-console 堆栈。

  2. 选择资源

  3. 物理 ID 下,选择您的 API。此链接将引导您进入 API Gateway 控制台。

在修改 GETPOST 方法之前,必须创建模型。

创建模型
  1. 需要一个模型来对传入请求的正文使用请求验证。要创建模型,请在主导航窗格中选择模型

  2. 选择创建模型

  3. 对于名称,请输入 PetStoreModel

  4. 对于内容类型,输入 application/json。如果未找到匹配的内容类型,则不执行请求验证。要使用同一模型而不考虑内容类型,请输入 $default

  5. 对于描述,输入 My PetStore Model 作为模型描述。

  6. 对于模型架构,将以下模型粘贴到代码编辑器中,然后选择创建

    { "type" : "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" }, "price" : { "type" : "number", "minimum" : 25.0, "maximum" : 500.0 } } }

有关模型的更多信息,请参阅了解数据模型

GET 方法配置请求验证
  1. 在主导航窗格中,选择资源,然后选择 GET 方法。

  2. 方法请求选项卡上的方法请求设置下,选择编辑

  3. 对于请求验证程序,选择验证查询字符串参数和标头

  4. URL 查询字符串参数下,执行以下操作:

    1. 选择添加查询字符串

    2. 名称中,输入 petType

    3. 打开必需

    4. 缓存保持为关闭状态。

  5. 选择保存

  6. 集成请求选项卡的集成请求设置下,选择编辑

  7. URL 查询字符串参数下,执行以下操作:

    1. 选择添加查询字符串

    2. 名称中,输入 petType

    3. 对于映射自,输入 method.request.querystring.petType。这会将 petType 映射到宠物的类型。

      有关数据映射的更多信息,请参阅数据映射教程

    4. 缓存保持为关闭状态。

  8. 选择保存

GET 方法测试请求验证
  1. 选择测试选项卡。您可能需要选择右箭头按钮,以显示该选项卡。

  2. 对于查询字符串,输入 petType=dog,然后选择测试

  3. 方法测试将返回 200 OK 并提供狗的列表。

    有关如何转换此输出数据的信息,请参阅数据映射教程

  4. 删除 petType=dog 并选择测试

  5. 方法测试将返回 400 错误并显示以下错误消息:

    { "message": "Missing required request parameters: [petType]" }
POST 方法配置请求验证
  1. 在主导航窗格中,选择资源,然后选择 POST 方法。

  2. 方法请求选项卡上的方法请求设置下,选择编辑

  3. 对于请求验证程序,选择验证正文

  4. 请求正文下,选择添加模型

  5. 对于内容类型,输入 application/json,然后对于模型,选择 PetStoreModel

  6. 选择保存

POST 方法测试请求验证
  1. 选择测试选项卡。您可能需要选择右箭头按钮,以显示该选项卡。

  2. 对于请求正文,将以下内容粘贴到代码编辑器中:

    { "id": 2, "name": "Bella", "type": "dog", "price": 400 }

    选择测试

  3. 方法测试将返回 200 OK 和成功消息。

  4. 对于请求正文,将以下内容粘贴到代码编辑器中:

    { "id": 2, "name": "Bella", "type": "dog", "price": 4000 }

    选择测试

  5. 方法测试将返回 400 错误并显示以下错误消息:

    { "message": "Invalid request body" }

    在测试日志的底部,将返回请求正文无效的原因。在这种情况下,宠物的价格超出了模型中规定的最高价格。

删除 Amazon CloudFormation 堆栈
  1. 打开 Amazon CloudFormation 控制台,地址:https://console.aws.amazon.com/cloudformation

  2. 选择您的 Amazon CloudFormation 堆栈。

  3. 选择删除,然后确认您的选择。

后续步骤

使用 Amazon CLI 设置基本请求验证

您可以使用 Amazon CLI 创建验证程序来设置请求验证。要按本教程操作,您将使用 Amazon CloudFormation 模板来创建不完整的 API Gateway API。

注意

这与控制台教程的 Amazon CloudFormation 模板不同。

使用预先公开的 /validator 资源,您将创建 GETPOST 方法。两种方法都将与 http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP 端点集成。您将配置以下两个请求验证:

  • GET 方法上,您将创建一个 params-only 验证程序来验证 URL 查询字符串参数。

  • POST 方法上,您将创建一个 body-only 验证程序来验证请求正文。

这将只允许特定的 API 调用传递给 API。

创建 Amazon CloudFormation 堆栈

下载并解压缩适用于 Amazon CloudFormation 的应用程序创建模板

要完成以下教程,您需要 Amazon Command Line Interface(Amazon CLI)版本 2

对于长命令,使用转义字符 (\) 将命令拆分为多行。

注意

在 Windows 中,操作系统的内置终端不支持您经常使用的某些 Bash CLI 命令(例如 zip)。安装 Windows Subsystem for Linux,获取 Ubuntu 和 Bash 与 Windows 集成的版本。本指南中的示例 CLI 命令使用 Linux 格式。如果您使用的是 Windows CLI,则必须重新格式化包含内联 JSON 文档的命令。

  1. 输入以下命令创建 Amazon CloudFormation 堆栈。

    aws cloudformation create-stack --stack-name request-validation-tutorial-cli --template-body file://request-validation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM
  2. Amazon CloudFormation 预置在模板中指定的资源。完成资源预置可能需要几分钟时间。使用以下命令查看 Amazon CloudFormation 的状态。

    aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli
  3. 当 Amazon CloudFormation 堆栈的状态为 StackStatus: "CREATE_COMPLETE" 时,使用以下命令检索将来步骤的相关输出值。

    aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli --query "Stacks[*].Outputs[*].{OutputKey: OutputKey, OutputValue: OutputValue, Description: Description}"

    输出值包括:

    • ApiId,这是 API 的 ID。对于本教程,API ID 为 abc123

    • ResourceId,这是在其中公开 GETPOST 方法的验证程序资源的 ID。对于本教程,资源 ID 为 efg456

创建请求验证程序并导入模型
  1. 需要验证程序才能通过 Amazon CLI 使用请求验证。使用以下命令创建仅验证请求参数的验证程序。

    aws apigateway create-request-validator --rest-api-id abc123 \ --no-validate-request-body \ --validate-request-parameters \ --name params-only

    记下 params-only 验证程序的 ID。

  2. 使用以下命令创建仅验证请求正文的验证程序。

    aws apigateway create-request-validator --rest-api-id abc123 \ --validate-request-body \ --no-validate-request-parameters \ --name body-only

    记下 body-only 验证程序的 ID。

  3. 需要一个模型来对传入请求的正文使用请求验证。使用以下命令导入模型。

    aws apigateway create-model --rest-api-id abc123 --name PetStoreModel --description 'My PetStore Model' --content-type 'application/json' --schema '{"type": "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : {"type" : "integer"},"type" : {"type" : "string", "enum" : [ "dog", "cat", "fish" ]},"name" : { "type" : "string"},"price" : {"type" : "number","minimum" : 25.0, "maximum" : 500.0}}}}'

    如果未找到匹配的内容类型,则不执行请求验证。要使用同一模型而不考虑内容类型,请指定 $default 作为键。

创建 GETPOST 方法
  1. 使用以下命令对 /validate 资源添加 GET HTTP 方法。此命令创建 GET 方法,添加 params-only 验证程序,并根据需要设置查询字符串 petType

    aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --authorization-type "NONE" \ --request-validator-id aaa111 \ --request-parameters "method.request.querystring.petType=true"

    使用以下命令对 /validate 资源添加 POST HTTP 方法。此命令创建 POST 方法,添加 body-only 验证程序,并将模型附加到仅限正文的验证程序。

    aws apigateway put-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --authorization-type "NONE" \ --request-validator-id bbb222 \ --request-models 'application/json'=PetStoreModel
  2. 使用以下命令设置 GET /validate 方法的 200 OK 响应。

    aws apigateway put-method-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --status-code 200

    使用以下命令设置 POST /validate 方法的 200 OK 响应。

    aws apigateway put-method-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200
  3. 使用以下命令通过指定的 HTTP 端点为 GET /validation 方法设置 Integration

    aws apigateway put-integration --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --type HTTP \ --integration-http-method GET \ --request-parameters '{"integration.request.querystring.type" : "method.request.querystring.petType"}' \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets'

    使用以下命令通过指定的 HTTP 端点为 POST /validation 方法设置 Integration

    aws apigateway put-integration --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --type HTTP \ --integration-http-method GET \ --uri 'http://petstore-demo-endpoint.execute-api.com/petstore/pets'
  4. 使用以下命令设置 GET /validation 方法的集成响应。

    aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456\ --http-method GET \ --status-code 200 \ --selection-pattern ""

    使用以下命令设置 POST /validation 方法的集成响应。

    aws apigateway put-integration-response --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --status-code 200 \ --selection-pattern ""
测试 API
  1. 要测试将对查询字符串执行请求验证的 GET 方法,请使用以下命令:

    aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET \ --path-with-query-string '/validate?petType=dog'

    结果将返回 200 OK 和狗的列表。

  2. 使用以下命令在不包含查询字符串 petType 的情况下进行测试

    aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method GET

    结果将返回 400 错误。

  3. 要测试将对请求正文执行请求验证的 POST 方法,请使用以下命令:

    aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --body '{"id": 1, "name": "bella", "type": "dog", "price" : 400 }'

    结果将返回 200 OK 和一条成功消息。

  4. 使用以下命令通过无效的正文进行测试。

    aws apigateway test-invoke-method --rest-api-id abc123 \ --resource-id efg456 \ --http-method POST \ --body '{"id": 1, "name": "bella", "type": "dog", "price" : 1000 }'

    结果将返回 400 错误,因为狗的价格超过了模型定义的最高价格。

删除 Amazon CloudFormation 堆栈
  • 使用以下命令删除您的 Amazon CloudFormation 资源。

    aws cloudformation delete-stack --stack-name request-validation-tutorial-cli

使用 OpenAPI 定义设置基本请求验证

您可以在 API 级别声明请求验证程序,方法是在 x-amazon-apigateway-request-validators 对象 映射中指定一组 x-amazon-apigateway-request-validators.requestValidator 对象 对象,以选择将对请求的哪个部分进行验证。在示例 OpenAPI 定义中,有两个验证程序:

  • all 验证程序,它验证正文(使用 RequestBodyModel 数据模型)和参数。

  • param-only,它只验证参数。

要在 API 的所有方法上开启请求验证程序,请在 API 级别指定 OpenAPI 定义的 x-amazon-apigateway-request-validator 属性 属性。在示例 OpenAPI 定义中,all 验证器用于所有 API 方法,除非被覆盖。使用模型验证正文时,如果找不到匹配的内容类型,则不执行请求验证。要使用同一模型而不考虑内容类型,请指定 $default 作为键。

要针对单独的方法开启请求验证程序,请在方法级别指定 x-amazon-apigateway-request-validator 属性。在示例 OpenAPI 定义中,param-only 验证程序会覆盖 GET 方法上的 all 验证程序。

要将 OpenAPI 示例导入 API Gateway,请参阅以下有关将区域 API 导入到 API Gateway 中将边缘优化的 API 导入 API Gateway的说明。

OpenAPI 3.0
{ "openapi" : "3.0.1", "info" : { "title" : "ReqValidators Sample", "version" : "1.0.0" }, "servers" : [ { "url" : "/{basePath}", "variables" : { "basePath" : { "default" : "/v1" } } } ], "paths" : { "/validation" : { "get" : { "parameters" : [ { "name" : "q1", "in" : "query", "required" : true, "schema" : { "type" : "string" } } ], "responses" : { "200" : { "description" : "200 response", "headers" : { "test-method-response-header" : { "schema" : { "type" : "string" } } }, "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/ArrayOfError" } } } } }, "x-amazon-apigateway-request-validator" : "params-only", "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.querystring.type" : "method.request.querystring.q1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } }, "post" : { "parameters" : [ { "name" : "h1", "in" : "header", "required" : true, "schema" : { "type" : "string" } } ], "requestBody" : { "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/RequestBodyModel" } } }, "required" : true }, "responses" : { "200" : { "description" : "200 response", "headers" : { "test-method-response-header" : { "schema" : { "type" : "string" } } }, "content" : { "application/json" : { "schema" : { "$ref" : "#/components/schemas/ArrayOfError" } } } } }, "x-amazon-apigateway-request-validator" : "all", "x-amazon-apigateway-integration" : { "httpMethod" : "POST", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.custom_h1" : "method.request.header.h1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } }, "components" : { "schemas" : { "RequestBodyModel" : { "required" : [ "name", "price", "type" ], "type" : "object", "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" }, "price" : { "maximum" : 500.0, "minimum" : 25.0, "type" : "number" } } }, "ArrayOfError" : { "type" : "array", "items" : { "$ref" : "#/components/schemas/Error" } }, "Error" : { "type" : "object" } } }, "x-amazon-apigateway-request-validators" : { "all" : { "validateRequestParameters" : true, "validateRequestBody" : true }, "params-only" : { "validateRequestParameters" : true, "validateRequestBody" : false } } }
OpenAPI 2.0
{ "swagger" : "2.0", "info" : { "version" : "1.0.0", "title" : "ReqValidators Sample" }, "basePath" : "/v1", "schemes" : [ "https" ], "paths" : { "/validation" : { "get" : { "produces" : [ "application/json", "application/xml" ], "parameters" : [ { "name" : "q1", "in" : "query", "required" : true, "type" : "string" } ], "responses" : { "200" : { "description" : "200 response", "schema" : { "$ref" : "#/definitions/ArrayOfError" }, "headers" : { "test-method-response-header" : { "type" : "string" } } } }, "x-amazon-apigateway-request-validator" : "params-only", "x-amazon-apigateway-integration" : { "httpMethod" : "GET", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.querystring.type" : "method.request.querystring.q1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } }, "post" : { "consumes" : [ "application/json" ], "produces" : [ "application/json", "application/xml" ], "parameters" : [ { "name" : "h1", "in" : "header", "required" : true, "type" : "string" }, { "in" : "body", "name" : "RequestBodyModel", "required" : true, "schema" : { "$ref" : "#/definitions/RequestBodyModel" } } ], "responses" : { "200" : { "description" : "200 response", "schema" : { "$ref" : "#/definitions/ArrayOfError" }, "headers" : { "test-method-response-header" : { "type" : "string" } } } }, "x-amazon-apigateway-request-validator" : "all", "x-amazon-apigateway-integration" : { "httpMethod" : "POST", "uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets", "responses" : { "default" : { "statusCode" : "400", "responseParameters" : { "method.response.header.test-method-response-header" : "'static value'" }, "responseTemplates" : { "application/xml" : "xml 400 response template", "application/json" : "json 400 response template" } }, "2\\d{2}" : { "statusCode" : "200" } }, "requestParameters" : { "integration.request.header.custom_h1" : "method.request.header.h1" }, "passthroughBehavior" : "when_no_match", "type" : "http" } } } }, "definitions" : { "RequestBodyModel" : { "type" : "object", "required" : [ "name", "price", "type" ], "properties" : { "id" : { "type" : "integer" }, "type" : { "type" : "string", "enum" : [ "dog", "cat", "fish" ] }, "name" : { "type" : "string" }, "price" : { "type" : "number", "minimum" : 25.0, "maximum" : 500.0 } } }, "ArrayOfError" : { "type" : "array", "items" : { "$ref" : "#/definitions/Error" } }, "Error" : { "type" : "object" } }, "x-amazon-apigateway-request-validators" : { "all" : { "validateRequestParameters" : true, "validateRequestBody" : true }, "params-only" : { "validateRequestParameters" : true, "validateRequestBody" : false } } }