微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我需要为代理资源向 API Gateway 添加 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,}
            }],)

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。