使用AWS API网关的API密钥可以提供对API端点的访问控制,并通过使用API key保护API端点免受恶意攻击。以下是使用AWS API网关API密钥保护API端点的一些示例代码。
# Set up the API Key Required method
resource "aws_api_gateway_method_settings" "example" {
rest_api_id = "${aws_api_gateway_rest_api.example.id}"
stage_name = "${aws_api_gateway_stage.example.name}"
method_path = "/*/*/create"
settings = {
api_key_required = true
}
}
# Deploy the REST API
resource "aws_api_gateway_deployment" "example" {
rest_api_id = "${aws_api_gateway_rest_api.example.id}"
stage_name = "${aws_api_gateway_stage.example.name}"
}
# Define an API Key
resource "aws_api_gateway_api_key" "example" {
name = "exampleApiKey"
}
# Add resource/method to API Gateway
resource "aws_api_gateway_resource" "example" {
rest_api_id = "${aws_api_gateway_rest_api.example.id}"
parent_id = "${aws_api_gateway_rest_api.example.root_resource_id}"
path_part = "exampleResource"
}
resource "aws_api_gateway_method" "exampleMethod" {
rest_api_id = "${aws_api_gateway_rest_api.example.id}"
resource_id = "${aws_api_gateway_resource.example.id}"
http_method = "ANY"
authorization = "NONE"
}
# Associate the API Key with the Resource/Method
resource "aws_api_gateway_usage_plan" "example" {
name = "exampleUsagePlan"
product_code = "exampleProductCode"
api_stages {
api_id = "${aws_api_gateway_rest_api.example.id}"
stage = "${aws_api_gateway_stage.example.name}"
}
# Define the API Key Usage
quota {
limit = 10000
offset = 1
period = "MONTH"
}
throttle {
burst_limit = 5
rate