0

我需要为代理资源的 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,
                }
            }],
        )

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

4

1 回答 1

0

查看您的代码片段,我的猜测是您在创建代理资源时在默认 MethodOptions 中添加了 API 密钥要求。

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
        )
于 2021-10-14T04:33:12.327 回答