在 AWS CDK 项目中使用 Python 编写代码来实现子域名的 CORS 策略。
首先,需要导入 AWS CDK 中的相关库和模块:
from aws_cdk import (
aws_apigateway as apigateway,
aws_lambda as lambda_,
aws_iam as iam,
core,
)
接着,创建自定义域名对象:
domain_name = apigateway.DomainName(
self, "DomainName",
domain_name=domain_name,
certificate=certificate,
security_policy=apigateway.SecurityPolicy.TLS_1_2
)
定义 API Gateway 的 rest API:
api = apigateway.RestApi(
self, "APIGateway",
rest_api_name="subdomain-cors-api",
domain_name=domain_name,
default_cors_preflight_options={
"allow_origins": apigateway.Cors.ALL_ORIGINS,
"allow_methods": apigateway.Cors.ALL_METHODS,
"allow_headers": ["Content-Type", "X-Amz-Date", "Authorization", "X-Api-Key"]
}
)
创建 Lambda 函数并添加到 API Gateway 中:
handler = lambda_.Function(
self, "Handler",
code=lambda_.Code.asset("lambda"),
handler="handler.handle_request",
runtime=lambda_.Runtime.PYTHON_3_8,
)
integration = apigateway.LambdaIntegration(
handler=handler,
proxy=True,
)
api.root.add_method(
"ANY",
integration,
method_responses=[{
"statusCode": "200",
"responseParameters": {
"method.response.header.Access-Control-Allow-Headers": True,
"method.response.header.Access-Control-Allow-Methods": True,
"method.response.header.Access-Control-Allow-Origin": True,
}
}],
integration_responses=[{
"statusCode": "200",
"responseParameters": {
"method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'",
"method.response.header.Access-Control-Allow-Methods": "'