Beispiel #1
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}"
            });
        }