

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 在 API Gateway 中選擇 API 金鑰來源
<a name="api-gateway-api-key-source"></a>

當您將 API 與用量計劃建立關聯並在 API 方法上啟用 API 金鑰時，每個對 API 傳入的請求必須包含 [API 金鑰](api-gateway-basic-concept.md#apigateway-definition-api-key)。API Gateway 會讀取金鑰，並將其與在用量計劃中的金鑰進行比對。如果有相符項目，則 API Gateway 會根據計劃的請求限制和配額來調節請求量。否則，它會擲出 `InvalidKeyParameter` 例外狀況。因此，發起人收到 `403 Forbidden` 回應。

API Gateway API 可接收來自以下兩種來源之一的 API 金鑰：

**`HEADER`**  
您將 API 金鑰發布至客戶，並要求他們傳遞 API 金鑰，做為每個傳入請求的 `X-API-Key` 標頭。

**`AUTHORIZER`**  
您可以讓 Lambda 授權方傳回 API 金鑰，當做授權回應的一部分。如需授權回應的詳細資訊，請參閱[來自 API Gateway Lambda 授權方的輸出](api-gateway-lambda-authorizer-output.md)。

**注意**  
如需考量最佳實務，請參閱 [API 金鑰和用量計劃的最佳實務](api-gateway-api-usage-plans.md#apigateway-usage-plans-best-practices)。

下列程序說明如何選擇 API 的 API 金鑰來源。

------
#### [ AWS 管理主控台 ]

**選擇 API 的 API 金鑰來源**

1. 登入 API Gateway 主控台。

1. 選擇現有的 API 或建立新的 API。

1. 在主導覽窗格中，選擇 **API 設定**。

1. 在 **API 詳細資訊**區段中，選擇**編輯**。

1.  在 **API 金鑰來源**下，從下拉式清單選取 `Header` 或 `Authorizer`。

1. 選擇**儲存變更**。

------
#### [ AWS CLI ]

以下 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令會更新 API，以將 API 金鑰來源設定為 `AUTHORIZER`：

```
aws apigateway update-rest-api --rest-api-id 1234123412 --patch-operations op=replace,path=/apiKeySource,value=AUTHORIZER
```

若要讓用戶端提交 API 金鑰，請在上述命令中將 `value` 設為 `HEADER`。

------
#### [ REST API ]

若要使用 API Gateway REST API 選擇 API 的 API 金鑰來源，請呼叫 [https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateRestApi.html](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateRestApi.html)，如下所示：

```
PATCH /restapis/fugvjdxtri/ HTTP/1.1
Content-Type: application/json
Host: apigateway.us-east-1.amazonaws.com
X-Amz-Date: 20160603T205348Z
Authorization: AWS4-HMAC-SHA256 Credential={access_key_ID}/20160603/us-east-1/apigateway/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature={sig4_hash}

{
  "patchOperations" : [
    {
        "op" : "replace",
        "path" : "/apiKeySource",
        "value" : "HEADER"
    }
  ]
}
```

若要讓授權方傳回 API 金鑰，請在之前的 `value` 輸入中將 `AUTHORIZER` 設為 `patchOperations`。

------