使用AWS API网关和API密钥保护API,并验证请求是否带有有效的API密钥。
以下是一个使用Python和Boto3 SDK创建API密钥,设置API密钥和API Gateway之间的授权,以及验证API请求是否包含有效API密钥的示例代码:
创建API密钥:
import boto3
client = boto3.client('apigateway')
api_key_name = 'my-api-key'
api_key_response = client.create_api_key(
name=api_key_name,
enabled=True
)
api_key_id = api_key_response['id']
api_key_value = api_key_response['value']
设置API密钥和API Gateway之间的授权:
api_id = 'my-api-id'
response = client.create_usage_plan_key(
usagePlanId=usage_plan_id,
keyId=api_key_id,
keyType='API_KEY'
)
response = client.create_authorizer(
restApiId=api_id,
name='my-authorizer',
type='TOKEN',
identitySource='method.request.header.Authorization',
authorizerUri='arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:my-function-arn',
authorizerCredentials='arn:aws:iam::123456789012:role/my-role',
authorizerResultTtlInSeconds=300
)
验证API请求是否包含有效API密钥:
import requests
url = 'https://my-api.execute-api.us-east-1.amazonaws.com/prod/my-resource'
headers = {'x-api-key': api_key_value}
response = requests.get(url, headers=headers)
if response.status_code == 200:
# valid API key
else:
# invalid API key