Skip to content

Instantly share code, notes, and snippets.

@norbinsh
Last active December 21, 2020 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save norbinsh/9dd727679ee22171b907ffb360671f8f to your computer and use it in GitHub Desktop.
Save norbinsh/9dd727679ee22171b907ffb360671f8f to your computer and use it in GitHub Desktop.
aws cdk http api
import * as cdk from '@aws-cdk/core';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as apigwv2 from '@aws-cdk/aws-apigatewayv2';
import * as apigwv2i from '@aws-cdk/aws-apigatewayv2-integrations';
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2'
import * as lambda from '@aws-cdk/aws-lambda';
interface ApiStackProps extends cdk.StackProps {
vpc: ec2.IVpc;
reposmanagerAlbListener: elbv2.IApplicationListener;
albSg: ec2.ISecurityGroup;
}
export class demoInfraApiStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props: ApiStackProps) {
super(scope, id, props);
const vpcLink = new apigwv2.VpcLink(this, 'demo-vpc-link', {
vpc: props.vpc,
securityGroups: [props.albSg],
vpcLinkName: 'demo-vpc-link'
})
const demoAPI = new apigwv2.HttpApi(this, 'demo-http-api', {
apiName: 'demo-http-api',
description: 'HTTP Api serving as an entry point for demo flow'
})
const code = lambda.Code.fromAsset(`${__dirname}/authorizer`);
const demoauthorizerLambda = new lambda.Function(this, 'demoAuthorizerLambda', {
code,
handler: 'index.handler',
runtime: lambda.Runtime.NODEJS_10_X,
memorySize: 512,
timeout: cdk.Duration.seconds(5)
});
const authorizerUri = `arn:aws:apigateway:${props.env?.region}:lambda:path/2015-03-31/functions/${
demoauthorizerLambda.functionArn
}/invocations`;
const authorizer = new apigwv2.CfnAuthorizer(this, 'demoauthorizer', {
apiId: demoAPI.httpApiId,
authorizerType: "REQUEST",
identitySource: ["$request.header.Authorization"],
name: "demoauthorizer",
enableSimpleResponses: true,
authorizerPayloadFormatVersion: "2.0",
authorizerUri: authorizerUri
})
const rootRoute = new apigwv2.HttpRoute(this, 'rootRoute', {
httpApi: demoAPI,
integration: new apigwv2i.HttpAlbIntegration({
vpcLink: vpcLink,
listener: props.reposmanagerAlbListener,
}),
routeKey: apigwv2.HttpRouteKey.with("/", apigwv2.HttpMethod.GET),
})
const cfnRootRoute = rootRoute.node.defaultChild as apigwv2.CfnRoute
cfnRootRoute.authorizationType = "CUSTOM"
cfnRootRoute.authorizerId = authorizer.ref
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment