Search code examples
aws-api-gatewayaws-cdklambda-authorizer

Reuse custom authorizer for AWS ApiGW using CDK


I would like to reuse a custom authorizer that was created using CDK in one repository for a new AWS ApiGW method that was created in another repo. Currently, there is no CDK built-in method for importing an existing authorizer.


Solution

  • I have found a way to overcome the problem:

    # Import rest api from the environment using ids
    rest_api = RestApi.from_rest_api_attributes(self, "fromrestapiid",
                                                        rest_api_id=rest_api_id,
                                                        root_resource_id=resource_id)
    # Retrieve or create an API method
    method_resource = rest_api.root.resource_for_path(endpoint_path)
    
    # Change the property of the resource using the existing authorizer id
    method_resource = method.node.find_child('Resource')
    method_resource.add_property_override('AuthorizationType', 'CUSTOM')
    method_resource.add_property_override('AuthorizerId', authorizer_id)