如何使用aws-cdk-python设置API密钥



我需要为代理资源向API网关添加一个API密钥
现在,我的代码添加了对代理和选项资源的要求。如何仅指定代理的要求?

我设法通过控制台完成了这项工作,但这并不容易管理。

class Stack(core.Stack):
def __init__(self, scope: core.Construct, id: str, props: Dict, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
self.version = Path('VERSION').read_text().strip()
self.namespace = props['namespace']
role = iam.Role()
role.add_to_policy()
bucket = s3.Bucket()
bucket.grant_read_write(role)
code = lambda_.Code.from_ecr_image()
function = lambda_.Function()
api = apigw.RestApi(
self, "BackendApi",
rest_api_name='api',
deploy_options=apigw.StageOptions(
tracing_enabled=True,
data_trace_enabled=True,
stage_name="some_stage"
),
binary_media_types=['multipart/form-data']
)
# Create Api key and add it to the api. Names must be unique independent of stage
api_key = api.add_api_key("ApiKey", api_key_name="ApiKey", value="1234567890abcdefghij")
# Create Usage Plan and add it to the API
plan = api.add_usage_plan("usagePlan", api_key=api_key)
plan.add_api_stage(stage=api.deployment_stage)
api_integration = apigw.LambdaIntegration(function)
proxy_resource = api.root.add_proxy(
any_method=True,
default_integration=api_integration,
default_method_options=apigw.MethodOptions(
api_key_required=True
)
)
self.add_cors_options(proxy_resource)
def add_cors_options(self, resource):
"""
Utility method to add CORS to a Apigateway resource
Args:
resource (aws_cdk.aws_apigateway.IResource)
"""
resource.add_method('OPTIONS', apigw.MockIntegration(
integration_responses=[{
'statusCode': '200',
'responseParameters': {
'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'",
'method.response.header.Access-Control-Allow-Origin': "'*'",
'method.response.header.Access-Control-Allow-Credentials': "'false'",
'method.response.header.Access-Control-Allow-Methods': "'GET,POST,OPTIONS'"
}
}],
passthrough_behavior=apigw.PassthroughBehavior.WHEN_NO_MATCH,
request_templates={"application/json": "{"statusCode":200}"}
),
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-Credentials': True,
'method.response.header.Access-Control-Allow-Origin': True,
}
}],
)

我设法添加代理要求的唯一方法是在代理创建中添加要求。这是更好的方法吗?

查看您的代码片段,我猜您在创建代理资源时,将在默认MethodOptions中添加API Key需求。

proxy_resource = api.root.add_proxy(
any_method=True,
default_integration=api_integration,
default_method_options=apigw.MethodOptions(
api_key_required=True
)
)

因此,CDK也向该方法添加了要求,去掉default_method_options值将修复它

proxy_resource = api.root.add_proxy(
any_method=True,
default_integration=api_integration
)

最新更新