Skip to content
v2.278.0

AuthenticateCognitoAction Class ​

A Listener Action to authenticate with Cognito.

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
// Install: dotnet add package Amazon.CDK.Lib
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
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
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,
})

Initializer ​

ts
new AuthenticateCognitoAction(options: AuthenticateCognitoActionProps)
python
AuthenticateCognitoAction(options: AuthenticateCognitoActionProps)
java
new AuthenticateCognitoAction(AuthenticateCognitoActionProps options)
csharp
new AuthenticateCognitoAction(AuthenticateCognitoActionProps options)
go
NewAuthenticateCognitoAction(Options AuthenticateCognitoActionProps)

Methods ​

authenticateJwt(options: AuthenticateJwtOptions): ListenerAction@staticmethod def authenticate_jwt(options: AuthenticateJwtOptions) -> ListenerActionpublic static ListenerAction authenticateJwt(AuthenticateJwtOptions options)public static ListenerAction AuthenticateJwt(AuthenticateJwtOptions options)func AuthenticateJwt(Options AuthenticateJwtOptions) ListenerAction static #
Authenticate using JWT validation.
notes

You can configure ALB to verify JSON Web Tokens (JWT) provided by clients for secure service-to-service (S2S) or machine-to-machine (M2M) communications.

ALB validates the token signature and requires mandatory claims: 'iss' (issuer) and 'exp' (expiration). Additionally, if present, ALB validates 'nbf' (not before) and 'iat' (issued at time) claims.

authenticateOidc(options: AuthenticateOidcOptions): ListenerAction@staticmethod def authenticate_oidc(options: AuthenticateOidcOptions) -> ListenerActionpublic static ListenerAction authenticateOidc(AuthenticateOidcOptions options)public static ListenerAction AuthenticateOidc(AuthenticateOidcOptions options)func AuthenticateOidc(Options AuthenticateOidcOptions) ListenerAction static #
Authenticate using an identity provider (IdP) that is compliant with OpenID Connect (OIDC).
bind(scope: Construct, listener: IApplicationListener, associatingConstruct?: IConstruct): voiddef bind(self, scope: Construct, listener: IApplicationListener, associating_construct: typing.Optional[IConstruct] = None) -> Nonepublic void bind(Construct scope, IApplicationListener listener, IConstruct associatingConstruct)public void Bind(Construct scope, IApplicationListener listener, IConstruct? associatingConstruct = null)func Bind(Scope Construct, Listener IApplicationListener, AssociatingConstruct IConstruct) #
Called when the action is being used in a listener.
fixedResponse(statusCode: number, options?: FixedResponseOptions): ListenerAction@staticmethod def fixed_response(status_code: int | float, options: typing.Optional[FixedResponseOptions] = None) -> ListenerActionpublic static ListenerAction fixedResponse(Number statusCode, FixedResponseOptions options)public static ListenerAction FixedResponse(double statusCode, FixedResponseOptions? options = null)func FixedResponse(StatusCode *float64, Options FixedResponseOptions) ListenerAction static #
Return a fixed response.
forward(targetGroups: IApplicationTargetGroup[], options?: ForwardOptions): ListenerAction@staticmethod def forward(target_groups: typing.List[IApplicationTargetGroup], options: typing.Optional[ForwardOptions] = None) -> ListenerActionpublic static ListenerAction forward(List<IApplicationTargetGroup> targetGroups, ForwardOptions options)public static ListenerAction Forward(IApplicationTargetGroup[] targetGroups, ForwardOptions? options = null)func Forward(TargetGroups *[]IApplicationTargetGroup, Options ForwardOptions) ListenerAction static #
Forward to one or more Target Groups.
redirect(options: RedirectOptions): ListenerAction@staticmethod def redirect(options: RedirectOptions) -> ListenerActionpublic static ListenerAction redirect(RedirectOptions options)public static ListenerAction Redirect(RedirectOptions options)func Redirect(Options RedirectOptions) ListenerAction static #
Redirect to a different URI.
notes

A URI consists of the following components: protocol://hostname:port/path?query. You must modify at least one of the following components to avoid a redirect loop: protocol, hostname, port, or path. Any components that you do not modify retain their original values.

You can reuse URI components using the following reserved keywords:

  • #{protocol}
  • #{host}
  • #{port}
  • #{path} (the leading "/" is removed)
  • #{query}

For example, you can change the path to "/new/#{path}", the hostname to "example.#{host}", or the query to "#{query}&value=xyz".

renderActions(): CfnListener.ActionProperty[]def render_actions(self, ) -> typing.List[ActionProperty]public List<ActionProperty> renderActions()public ActionProperty[] RenderActions()func RenderActions() *[]ActionProperty #
Render the listener default actions in this chain.
renderRuleActions(): CfnListenerRule.ActionProperty[]def render_rule_actions(self, ) -> typing.List[ActionProperty]public List<ActionProperty> renderRuleActions()public ActionProperty[] RenderRuleActions()func RenderRuleActions() *[]ActionProperty #
Render the listener rule actions in this chain.
weightedForward(targetGroups: WeightedTargetGroup[], options?: ForwardOptions): ListenerAction@staticmethod def weighted_forward(target_groups: typing.List[WeightedTargetGroup], options: typing.Optional[ForwardOptions] = None) -> ListenerActionpublic static ListenerAction weightedForward(List<WeightedTargetGroup> targetGroups, ForwardOptions options)public static ListenerAction WeightedForward(WeightedTargetGroup[] targetGroups, ForwardOptions? options = null)func WeightedForward(TargetGroups *[]WeightedTargetGroup, Options ForwardOptions) ListenerAction static #
Forward to one or more Target Groups which are weighted differently.