AWS API Gateway允许您轻松地创建既可公开访问又可私有访问的API。以下是如何实现此功能的步骤:
创建一个VPC端点,以便API Gateway可以与您的VPC通信。这可以通过在VPC中创建一个端点来完成。
使用API Gateway创建一个REST API,并在资源级别上添加API密钥验证。这将使您在API上实现私有访问。
创建一个API Gateway资源,该资源允许无需进行API密钥验证即可从Internet访问。可以通过在资源上禁用API密钥验证来实现此功能。
创建一个集成,该集成将API附加到您的目标(例如AWS Lambda函数或EC2实例)。
配置API Gateway集成以使用VPC端点。
配置API Gateway资源以允许从Internet访问,并使用以下Lambda函数代码来实现此功能:
import json
import boto3
from botocore.exceptions import ClientError
def lambda_handler(event, context):
client = boto3.client('apigateway')
rest_id = 'your_rest_api_id'
resource_id = 'your_resource_id'
# Create policy for public access
statement_public = {
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:::" + rest_id + "/*/*",
"Condition": {
"IpAddress": {
"aws:SourceIp": [event['requestContext']['identity']['sourceIp']]
}
}
}
# Add policy to allow public access
try:
client.update_method(
restApiId=rest_id,
resourceId=resource_id,
httpMethod='ANY',
patchOperations=[
{
'op': 'add',
'path': '/authorizer',
'value': ''
},