Skip to content
v2.273.0

Actions for AWS Elastic Load Balancing V2 ​

This package contains integration actions for ELBv2. See the README of the aws-cdk-lib/aws-elasticloadbalancingv2 library.

Cognito ​

ELB allows for requests to be authenticated against a Cognito user pool using the AuthenticateCognitoAction. For details on the setup's requirements, read Prepare to use Amazon Cognito. Here's an example:

ts
import { aws_certificatemanager as acm } from 'aws-cdk-lib';

declare const vpc: ec2.Vpc;
declare const certificate: acm.Certificate;

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
  vpc,
  internetFacing: true,
});

const userPool = new cognito.UserPool(this, 'UserPool');
const userPoolClient = new cognito.UserPoolClient(this, 'Client', {
  userPool,

  // Required minimal configuration for use with an ELB
  generateSecret: true,
  authFlows: {
    userPassword: true,
  },
  oAuth: {
    flows: {
      authorizationCodeGrant: true,
    },
    scopes: [cognito.OAuthScope.EMAIL],
    callbackUrls: [
      `https://${lb.loadBalancerDnsName}/oauth2/idpresponse`,
    ],
  },
});
const cfnClient = userPoolClient.node.defaultChild as cognito.CfnUserPoolClient;
cfnClient.addPropertyOverride('RefreshTokenValidity', 1);
cfnClient.addPropertyOverride('SupportedIdentityProviders', ['COGNITO']);

const userPoolDomain = new cognito.UserPoolDomain(this, 'Domain', {
  userPool,
  cognitoDomain: {
    domainPrefix: 'test-cdk-prefix',
  },
});

lb.addListener('Listener', {
  port: 443,
  certificates: [certificate],
  defaultAction: new actions.AuthenticateCognitoAction({
    userPool,
    userPoolClient,
    userPoolDomain,
    next: elbv2.ListenerAction.fixedResponse(200, {
      contentType: 'text/plain',
      messageBody: 'Authenticated',
    }),
  }),
});

new CfnOutput(this, 'DNS', {
  value: lb.loadBalancerDnsName,
});
python
from aws_cdk import aws_certificatemanager as acm

# vpc: ec2.Vpc
# certificate: acm.Certificate


lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True
)

user_pool = cognito.UserPool(self, "UserPool")
user_pool_client = cognito.UserPoolClient(self, "Client",
    user_pool=user_pool,

    # Required minimal configuration for use with an ELB
    generate_secret=True,
    auth_flows=cognito.AuthFlow(
        user_password=True
    ),
    o_auth=cognito.OAuthSettings(
        flows=cognito.OAuthFlows(
            authorization_code_grant=True
        ),
        scopes=[cognito.OAuthScope.EMAIL],
        callback_urls=[f"https://{lb.loadBalancerDnsName}/oauth2/idpresponse"
        ]
    )
)
cfn_client = user_pool_client.node.default_child
cfn_client.add_property_override("RefreshTokenValidity", 1)
cfn_client.add_property_override("SupportedIdentityProviders", ["COGNITO"])

user_pool_domain = cognito.UserPoolDomain(self, "Domain",
    user_pool=user_pool,
    cognito_domain=cognito.CognitoDomainOptions(
        domain_prefix="test-cdk-prefix"
    )
)

lb.add_listener("Listener",
    port=443,
    certificates=[certificate],
    default_action=actions.AuthenticateCognitoAction(
        user_pool=user_pool,
        user_pool_client=user_pool_client,
        user_pool_domain=user_pool_domain,
        next=elbv2.ListenerAction.fixed_response(200,
            content_type="text/plain",
            message_body="Authenticated"
        )
    )
)

CfnOutput(self, "DNS",
    value=lb.load_balancer_dns_name
)
java
import software.amazon.awscdk.services.certificatemanager.*;

Vpc vpc;
Certificate certificate;


ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .internetFacing(true)
        .build();

UserPool userPool = new UserPool(this, "UserPool");
UserPoolClient userPoolClient = UserPoolClient.Builder.create(this, "Client")
        .userPool(userPool)

        // Required minimal configuration for use with an ELB
        .generateSecret(true)
        .authFlows(AuthFlow.builder()
                .userPassword(true)
                .build())
        .oAuth(OAuthSettings.builder()
                .flows(OAuthFlows.builder()
                        .authorizationCodeGrant(true)
                        .build())
                .scopes(List.of(OAuthScope.EMAIL))
                .callbackUrls(List.of(String.format("https://%s/oauth2/idpresponse", lb.getLoadBalancerDnsName())))
                .build())
        .build();
CfnUserPoolClient cfnClient = (CfnUserPoolClient)userPoolClient.getNode().getDefaultChild();
cfnClient.addPropertyOverride("RefreshTokenValidity", 1);
cfnClient.addPropertyOverride("SupportedIdentityProviders", List.of("COGNITO"));

UserPoolDomain userPoolDomain = UserPoolDomain.Builder.create(this, "Domain")
        .userPool(userPool)
        .cognitoDomain(CognitoDomainOptions.builder()
                .domainPrefix("test-cdk-prefix")
                .build())
        .build();

lb.addListener("Listener", BaseApplicationListenerProps.builder()
        .port(443)
        .certificates(List.of(certificate))
        .defaultAction(AuthenticateCognitoAction.Builder.create()
                .userPool(userPool)
                .userPoolClient(userPoolClient)
                .userPoolDomain(userPoolDomain)
                .next(ListenerAction.fixedResponse(200, FixedResponseOptions.builder()
                        .contentType("text/plain")
                        .messageBody("Authenticated")
                        .build()))
                .build())
        .build());

CfnOutput.Builder.create(this, "DNS")
        .value(lb.getLoadBalancerDnsName())
        .build();
csharp
using Amazon.CDK.AWS.CertificateManager;

Vpc vpc;
Certificate certificate;


var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = true
});

var userPool = new UserPool(this, "UserPool");
var userPoolClient = new UserPoolClient(this, "Client", new UserPoolClientProps {
    UserPool = userPool,

    // Required minimal configuration for use with an ELB
    GenerateSecret = true,
    AuthFlows = new AuthFlow {
        UserPassword = true
    },
    OAuth = new OAuthSettings {
        Flows = new OAuthFlows {
            AuthorizationCodeGrant = true
        },
        Scopes = new [] { OAuthScope.EMAIL },
        CallbackUrls = new [] { $"https://{lb.loadBalancerDnsName}/oauth2/idpresponse" }
    }
});
var cfnClient = (CfnUserPoolClient)userPoolClient.Node.DefaultChild;
cfnClient.AddPropertyOverride("RefreshTokenValidity", 1);
cfnClient.AddPropertyOverride("SupportedIdentityProviders", new [] { "COGNITO" });

var userPoolDomain = new UserPoolDomain(this, "Domain", new UserPoolDomainProps {
    UserPool = userPool,
    CognitoDomain = new CognitoDomainOptions {
        DomainPrefix = "test-cdk-prefix"
    }
});

lb.AddListener("Listener", new BaseApplicationListenerProps {
    Port = 443,
    Certificates = new [] { certificate },
    DefaultAction = new AuthenticateCognitoAction(new AuthenticateCognitoActionProps {
        UserPool = userPool,
        UserPoolClient = userPoolClient,
        UserPoolDomain = userPoolDomain,
        Next = ListenerAction.FixedResponse(200, new FixedResponseOptions {
            ContentType = "text/plain",
            MessageBody = "Authenticated"
        })
    })
});

new CfnOutput(this, "DNS", new CfnOutputProps {
    Value = lb.LoadBalancerDnsName
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var vpc Vpc
var certificate Certificate


lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
})

userPool := awscdk.Aws_cognito.NewUserPool(this, jsii.String("UserPool"))
userPoolClient := awscdk.Aws_cognito.NewUserPoolClient(this, jsii.String("Client"), &UserPoolClientProps{
	UserPool: UserPool,

	// Required minimal configuration for use with an ELB
	GenerateSecret: jsii.Boolean(true),
	AuthFlows: &AuthFlow{
		UserPassword: jsii.Boolean(true),
	},
	OAuth: &OAuthSettings{
		Flows: &OAuthFlows{
			AuthorizationCodeGrant: jsii.Boolean(true),
		},
		Scopes: []OAuthScope{
			awscdk.*Aws_cognito.OAuthScope_EMAIL(),
		},
		CallbackUrls: []*string{
			fmt.Sprintf("https://%v/oauth2/idpresponse", lb.LoadBalancerDnsName),
		},
	},
})
cfnClient := userPoolClient.Node.defaultChild.(CfnUserPoolClient)
cfnClient.AddPropertyOverride(jsii.String("RefreshTokenValidity"), jsii.Number(1))
cfnClient.AddPropertyOverride(jsii.String("SupportedIdentityProviders"), []interface{}{
	jsii.String("COGNITO"),
})

userPoolDomain := awscdk.Aws_cognito.NewUserPoolDomain(this, jsii.String("Domain"), &UserPoolDomainProps{
	UserPool: UserPool,
	CognitoDomain: &CognitoDomainOptions{
		DomainPrefix: jsii.String("test-cdk-prefix"),
	},
})

lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(443),
	Certificates: []IListenerCertificate{
		certificate,
	},
	DefaultAction: actions.NewAuthenticateCognitoAction(&AuthenticateCognitoActionProps{
		UserPool: *UserPool,
		UserPoolClient: *UserPoolClient,
		UserPoolDomain: *UserPoolDomain,
		Next: elbv2.ListenerAction_FixedResponse(jsii.Number(200), &FixedResponseOptions{
			ContentType: jsii.String("text/plain"),
			MessageBody: jsii.String("Authenticated"),
		}),
	}),
})

awscdk.NewCfnOutput(this, jsii.String("DNS"), &CfnOutputProps{
	Value: lb.*LoadBalancerDnsName,
})

Types ​

NameKindSummary
AuthenticateCognitoActionClassA Listener Action to authenticate with Cognito.
AuthenticateCognitoActionPropsStructProperties for AuthenticateCognitoAction.