internal ApigwHttpApiEventbridgeDotnetCdkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var eventBus = new EventBus(this, "MyEventBus", new EventBusProps
            {
                EventBusName = "MyEventBus"
            });

            // Logging
            var eventLoggerRule = new Rule(this, "EventLoggerRule", new RuleProps
            {
                Description  = "Log all events",
                EventPattern = new EventPattern
                {
                    Region = new string[] { "us-west-2" }
                },
                EventBus = eventBus
            });

            var logGroup = new LogGroup(this, "EventLogGroup", new LogGroupProps
            {
                LogGroupName = "/aws/events/MyEventBus",
            });

            eventLoggerRule.AddTarget(new EventTargets.CloudWatchLogGroup(logGroup));

            // API
            var httpApi = new HttpApi(this, "MyHttpApi");

            // There"s no Eventbridge integration available as CDK L2 yet, so we have to use L1 and create Role, Integration and Route
            var apiRole = new Role(this, "EventBridgeIntegrationRole", new RoleProps
            {
                AssumedBy = new ServicePrincipal("apigateway.amazonaws.com"),
            });

            apiRole.AddToPolicy(
                new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Resources = new string[] { eventBus.EventBusArn },
                Actions   = new string[] { "events:PutEvents" },
            })
                );

            var eventbridgeIntegration = new CfnIntegration(
                this,
                "EventBridgeIntegration",
                new CfnIntegrationProps
            {
                ApiId              = httpApi.HttpApiId,
                IntegrationType    = "AWS_PROXY",
                IntegrationSubtype = "EventBridge-PutEvents",
                CredentialsArn     = apiRole.RoleArn,
                RequestParameters  = new Dictionary <string, object>
                {
                    ["Source"]       = "WebApp",
                    ["DetailType"]   = "MyDetailType",
                    ["Detail"]       = "$request.body",
                    ["EventBusName"] = eventBus.EventBusArn
                },
                PayloadFormatVersion = "1.0",
                TimeoutInMillis      = 10000,
            }
                );

            new CfnRoute(this, "EventRoute", new CfnRouteProps
            {
                ApiId    = httpApi.HttpApiId,
                RouteKey = "POST /",
                Target   = $"integrations/{eventbridgeIntegration.Ref}",
            });

            new CfnOutput(this, "apiUrl", new CfnOutputProps {
                Value = httpApi.Url !, Description = "HTTP API endpoint URL"
            });
Esempio n. 2
0
        internal CdkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var startState = new Pass(this, "StartState");

            var logGroup = new LogGroup(this, "HttpExpressWorkflowLogGroup");

            var stepFunction = new StateMachine(this, "HttpExpressWorkflow", new StateMachineProps()
            {
                StateMachineName = "HttpExpressWorkflowExample",
                StateMachineType = StateMachineType.EXPRESS,
                Definition       = startState,
                Logs             = new LogOptions()
                {
                    Destination = logGroup,
                    Level       = LogLevel.ALL
                },
                TracingEnabled = true
            });

            var apiGatewayRole = new Role(this, "ApiGatewayRole", new RoleProps()
            {
                AssumedBy = new ServicePrincipal("apigateway.amazonaws.com")
            });

            apiGatewayRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps()
            {
                Effect  = Effect.ALLOW,
                Sid     = "AllowStepFunctionExecution",
                Actions = new string[1] {
                    "states:StartSyncExecution"
                },
                Resources = new string[1] {
                    stepFunction.StateMachineArn
                }
            }));

            var httpApi = new CfnHttpApi(this, "HttpApi", new CfnHttpApiProps()
            {
                StageName = "Main",
            });

            var integration = new CfnIntegration(this, "StepFunctionIntegration", new CfnIntegrationProps()
            {
                ApiId              = httpApi.Ref,
                IntegrationType    = "AWS_PROXY",
                IntegrationSubtype = "StepFunctions-StartSyncExecution",
                CredentialsArn     = apiGatewayRole.RoleArn,
                RequestParameters  = new Dictionary <string, string>(2)
                {
                    { "Input", "$request.body" },
                    { "StateMachineArn", stepFunction.StateMachineArn }
                },
                PayloadFormatVersion = "1.0",
                ConnectionType       = "INTERNET"
            });

            var route = new CfnRoute(this, "StepFunctionRoute", new CfnRouteProps()
            {
                ApiId    = httpApi.Ref,
                RouteKey = "POST /execute",
                Target   = $"integrations/{integration.Ref}"
            });
        }
Esempio n. 3
0
        internal Apigatewayv2JwtAuthzSampleStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            const string LambdaKey = "secure-lambda";
            // Create a lambda function that will execute the logic when the api is called.
            var function = new Function(this, LambdaKey, new FunctionProps
            {
                Runtime = Runtime.NODEJS_12_X,
                Code    = Code.FromAsset("lambdas"),
                Handler = "my-secure-lambda.handler"
            });

            // Add cors options. (if you intend to call this from a web app)
            var cors = new CorsPreflightOptions
            {
                AllowCredentials = true,
                AllowHeaders     = new string[] { "Authorization" },
                AllowMethods     = new HttpMethod[] { HttpMethod.GET, HttpMethod.OPTIONS },
                AllowOrigins     = new string[] { "http://*****:*****@"/secureresource";

            // add a route to the api, attaching the JWT authorizer and targeting the integration.
            var cr = new CfnRoute(this, $"{LambdaKey}-route", new CfnRouteProps
            {
                ApiId             = api.HttpApiId,
                RouteKey          = $"GET {apiPath}",
                AuthorizationType = "JWT",
                AuthorizerId      = jwtAuthZ.Ref,
                Target            = $"integrations/{integration.Ref}"
            });

            // finally, add permissions so the http api can invoke the lambda for the api path.
            var resource = (CfnResource)api.Node.FindChild("Resource");

            function.AddPermission($"{LambdaKey}-permission", new Permission
            {
                Principal = new Amazon.CDK.AWS.IAM.ServicePrincipal("apigateway.amazonaws.com"),
                Action    = "lambda:InvokeFunction",
                SourceArn = $"arn:aws:execute-api:{this.Region}:{this.Account}:{resource.Ref}/*/*{apiPath}"
            });
        }