在 API Gateway 中設定基本請求驗證 - Amazon API Gateway

在 API Gateway 中設定基本請求驗證

本節說明如何使用主控台 AWS CLI 和 OpenAPI 定義,設定 API Gateway 的請求驗證。

使用 API Gateway 主控台設定請求驗證

您可以使用 API Gateway 主控台來驗證請求,方法是為 API 請求選取三個驗證程式之一:

  • 驗證內文

  • 驗證查詢字串參數和標頭

  • 驗證內文、查詢字串參數和標頭

當您在 API 方法上套用其中一個驗證程式時,API Gateway 主控台會將驗證程式新增至 API 的 RequestValidators 對應。

若要遵循本教學課程,您將使用 AWS CloudFormation 範本建立不完整的 API Gateway API。此 API 具有 /validator 資源,其中含有 GETPOST 方法。這兩種方法會與 http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP 端點整合。您將設定兩種請求驗證:

  • GET 方法中,您將設定 URL 查詢字串參數的請求驗證。

  • POST 方法中,您將設定請求內文的請求驗證。

這將只允許某些 API 呼叫傳遞至 API。

下載並解壓縮應用程式建立範本 AWS CloudFormation。您將使用此範本建立不完整的 API。您將完成 API Gateway 主控台中的其餘步驟。

若要建立 AWS CloudFormation 堆疊
  1. 開啟位於 https://console.aws.amazon.com/cloudformation 的 AWS CloudFormation 主控台。

  2. 選擇 Create stack (建立堆疊),然後選擇 With new resources (standard) (使用新資源 (標準))

  3. 對於 Specify template (指定範本),選擇 Upload a template file (上傳範本檔案)

  4. 選取您下載的範本。

  5. 選擇 Next (下一步)。

  6. 針對 Stack name (堆疊名稱),輸入 request-validation-tutorial-console,然後選擇 Next (下一步)

  7. 針對 Configure stack options (設定堆疊選項),選擇 Next (下一步)

  8. 針對 Capabilities (功能),請確認 AWS CloudFormation 可以在您的帳戶中建立 IAM 資源。

  9. 選擇提交

AWS CloudFormation 佈建在範本中指定的資源。完成資源佈建可能需要幾分鐘的時間。當 AWS CloudFormation 堆疊狀態為 CREATE_COMPLETE 時,您就可以繼續進行下一個步驟了。

選取新建立的 API
  1. 選取新建立的 request-validation-tutorial-console 堆疊。

  2. 選擇 Resources (資源)

  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 } } }

如需關於模型的詳細資訊,請參閱REST API 的資料模型

設定 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。如果找不到相符的內容類型,則不會執行請求驗證。若要使用相同的模型,而不論內容類型為何,請輸入 $default

    對於模型,選取 PetStoreModel

  6. 選擇儲存

測試 POST 方法的請求驗證
  1. 選擇測試標籤。您可能需要選擇向右箭頭按鈕才能顯示此索引標籤。

  2. 對於請求內文,將下列內容貼入程式碼編輯器中:

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

    選擇 Test (測試)

  3. 方法測試會傳回 200 OK 和成功訊息。

  4. 對於請求內文,將下列內容貼入程式碼編輯器中:

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

    選擇測試

  5. 方法測試會傳回 400 錯誤,並顯示下列錯誤訊息:

    { "message": "Invalid request body" }

    測試日誌底部會傳回請求內文無效的原因。在此案例中,寵物的價格超出了模型中指定的最高價格。

刪除 AWS CloudFormation 堆疊
  1. 開啟位於 https://console.aws.amazon.com/cloudformation 的 AWS CloudFormation 主控台。

  2. 選取您的 AWS CloudFormation 堆疊。

  3. 選擇刪除,然後確認您的選擇。

後續步驟

使用 AWS CLI 設定基本請求驗證

您可以使用 AWS CLI 建立驗證程式來設定請求驗證。若要遵循本教學課程,您將使用 AWS CloudFormation 範本建立不完整的 API Gateway API。

注意

這不是與主控台教學課程相同的 AWS CloudFormation 範本。

使用預先公開的 /validator 資源,您將建立 GETPOST 方法。這兩種方法會與 http://petstore-demo-endpoint.execute-api.com/petstore/pets HTTP 端點整合。您將設定下列兩個請求驗證:

  • GET 方法上,您將建立 params-only 驗證程式來驗證 URL 查詢字串參數。

  • POST 方法上,您將建立 body-only 驗證程式來驗證請求內文。

這將只允許某些 API 呼叫傳遞至 API。

若要建立 AWS CloudFormation 堆疊

下載並解壓縮應用程式建立範本 AWS CloudFormation

若要完成下列教學課程,您需要 AWS Command Line Interface (AWS CLI) 第 2 版

對於長命令,逸出字元 (\) 用於將命令分割為多行。

注意

在 Windows 中,作業系統的內建終端機不支援您常用的某些 Bash CLI 命令 (例如 zip)。若要取得 Ubuntu 和 Bash 的 Windows 整合版本,請安裝適用於 Linux 的 Windows 子系統。本指南中的 CLI 命令範例使用 Linux 格式。如果您使用的是 Windows CLI,必須重新格式化包含內嵌 JSON 文件的命令。

  1. 使用下列命令建立 AWS CloudFormation 堆疊。

    aws cloudformation create-stack --stack-name request-validation-tutorial-cli --template-body file://request-validation-tutorial-cli.zip --capabilities CAPABILITY_NAMED_IAM
  2. AWS CloudFormation 佈建在範本中指定的資源。完成資源佈建可能需要幾分鐘的時間。使用下列命令來查看 AWS CloudFormation 堆疊的狀態。

    aws cloudformation describe-stacks --stack-name request-validation-tutorial-cli
  3. 當 AWS 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. 需有驗證程式才能搭配 AWS 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. 使用下列命令,為 GET /validation 方法設定具有所指定 HTTP 端點的 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'

    使用下列命令,為 POST /validation 方法設定具有所指定 HTTP 端點的 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 錯誤,因為狗的價格超過了模型定義的最高價格。

刪除 AWS CloudFormation 堆疊
  • 使用下列命令刪除您的 AWS 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 資料模型) 和參數。

    RequestBodyModel 資料模型要求輸入 JSON 物件包含 nametypeprice 屬性。name 屬性可以是任意字串、type 必須是其中一個指定的列舉欄位 (["dog", "cat", "fish"]),而 price 的範圍必須是 25 到 500。id 不是必要參數。

  • param-only,其僅會驗證參數。

若要在 API 的所有方法上開啟請求驗證程式,請在 OpenAPI 定義的 API 層級指定 x-amazon-apigateway-request-validator 屬性 屬性。在範例 OpenAPI 定義中,除非特別覆寫,否則會在所有 API 方法上使用 all 驗證程式。使用模型驗證主體時,如果找不到相符的內容類型,則不會執行請求驗證。若要使用相同的模型,而不論內容類型為何,請指定 $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 } } }