AWS CDK user pool authorizer

前端 未结 7 1409
滥情空心
滥情空心 2021-02-12 23:31

I\'m trying to create an API gateway using the AWS-CDK and protect the REST endpoints with a Cognito user pool authorizer.

I cannot find any examples how one would do th

7条回答
  •  遇见更好的自我
    2021-02-13 00:11

    The previous answers no longer work because the authorizerId property was replaced with authorizer, which isn't fully implemented at this time.

    Instead, it can be done by using the underlying CfnResource objects, as described in the official guide.

    Here's Python code as an example:

    from aws_cdk import cdk
    from aws_cdk import aws_apigateway
    
    
    class Stk(cdk.Stack):
        def __init__(self, app, id):
            super().__init__(app, id)
    
            api_gw = aws_apigateway.RestApi(self, 'MyApp')
            post_method = api_gw.root.add_method(http_method='POST')
    
            # Create authorizer using low level CfnResource
            api_gw_authorizer = aws_apigateway.CfnAuthorizer(
                scope=self,
                id='my_authorizer',
                rest_api_id=api_gw.rest_api_id,
                name='MyAuth',
                type='COGNITO_USER_POOLS',
                identity_source='method.request.header.name.Authorization',
                provider_arns=[
                    'arn:aws:cognito-idp:eu-west-1:123456789012:userpool/'
                    'eu-west-1_MyCognito'])
    
            # Get underlying post_method Resource object. Returns CfnMethod
            post_method_resource = post_method.node.find_child('Resource')
            # Add properties to low level resource
            post_method_resource.add_property_override('AuthorizationType',
                                                       'COGNITO_USER_POOLS')
            # AuthorizedId uses Ref, simulate with a dictionaty
            post_method_resource.add_property_override(
                    'AuthorizerId',
                    {"Ref": api_gw_authorizer.logical_id})
    
    
    app = cdk.App()
    stk = Stk(app, "myStack")
    
    app.synth()
    

提交回复
热议问题