Skip to content
v2.278.0

ListenerAction Class ​

What to do when a client makes a request to a listener.

Some actions can be combined with other ones (specifically, you can perform authentication before serving the request).

Multiple actions form a linked chain; the chain must always terminate in a (weighted)forward, fixedResponse or redirect action.

If an action supports chaining, the next action can be indicated by passing it in the next property.

(Called ListenerAction instead of the more strictly correct ListenerAction because this is the class most users interact with, and we want to make it not too visually overwhelming).

Example ​

ts
import * as acm from 'aws-cdk-lib/aws-certificatemanager';

declare const certificate: acm.Certificate;
declare const lb: elbv2.ApplicationLoadBalancer;
declare const bucket: s3.Bucket;

const trustStore = new elbv2.TrustStore(this, 'Store', {
  bucket,
  key: 'rootCA_cert.pem',
});

lb.addListener('Listener', {
  port: 443,
  protocol: elbv2.ApplicationProtocol.HTTPS,
  certificates: [certificate],
  // mTLS settings
  mutualAuthentication: {
    advertiseTrustStoreCaNames: true,
    ignoreClientCertificateExpiry: false,
    mutualAuthenticationMode: elbv2.MutualAuthenticationMode.VERIFY,
    trustStore,
  },
  defaultAction: elbv2.ListenerAction.fixedResponse(200,
    { contentType: 'text/plain', messageBody: 'Success mTLS' }),
});
python
import aws_cdk.aws_certificatemanager as acm

# certificate: acm.Certificate
# lb: elbv2.ApplicationLoadBalancer
# bucket: s3.Bucket


trust_store = elbv2.TrustStore(self, "Store",
    bucket=bucket,
    key="rootCA_cert.pem"
)

lb.add_listener("Listener",
    port=443,
    protocol=elbv2.ApplicationProtocol.HTTPS,
    certificates=[certificate],
    # mTLS settings
    mutual_authentication=elbv2.MutualAuthentication(
        advertise_trust_store_ca_names=True,
        ignore_client_certificate_expiry=False,
        mutual_authentication_mode=elbv2.MutualAuthenticationMode.VERIFY,
        trust_store=trust_store
    ),
    default_action=elbv2.ListenerAction.fixed_response(200, content_type="text/plain", message_body="Success mTLS")
)
java
import software.amazon.awscdk.services.certificatemanager.*;

Certificate certificate;
ApplicationLoadBalancer lb;
Bucket bucket;


TrustStore trustStore = TrustStore.Builder.create(this, "Store")
        .bucket(bucket)
        .key("rootCA_cert.pem")
        .build();

lb.addListener("Listener", BaseApplicationListenerProps.builder()
        .port(443)
        .protocol(ApplicationProtocol.HTTPS)
        .certificates(List.of(certificate))
        // mTLS settings
        .mutualAuthentication(MutualAuthentication.builder()
                .advertiseTrustStoreCaNames(true)
                .ignoreClientCertificateExpiry(false)
                .mutualAuthenticationMode(MutualAuthenticationMode.VERIFY)
                .trustStore(trustStore)
                .build())
        .defaultAction(ListenerAction.fixedResponse(200, FixedResponseOptions.builder().contentType("text/plain").messageBody("Success mTLS").build()))
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.CertificateManager;

Certificate certificate;
ApplicationLoadBalancer lb;
Bucket bucket;


var trustStore = new TrustStore(this, "Store", new TrustStoreProps {
    Bucket = bucket,
    Key = "rootCA_cert.pem"
});

lb.AddListener("Listener", new BaseApplicationListenerProps {
    Port = 443,
    Protocol = ApplicationProtocol.HTTPS,
    Certificates = new [] { certificate },
    // mTLS settings
    MutualAuthentication = new MutualAuthentication {
        AdvertiseTrustStoreCaNames = true,
        IgnoreClientCertificateExpiry = false,
        MutualAuthenticationMode = MutualAuthenticationMode.VERIFY,
        TrustStore = trustStore
    },
    DefaultAction = ListenerAction.FixedResponse(200, new FixedResponseOptions { ContentType = "text/plain", MessageBody = "Success mTLS" })
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import acm "github.com/aws/aws-cdk-go/awscdk"

var certificate Certificate
var lb ApplicationLoadBalancer
var bucket Bucket


trustStore := elbv2.NewTrustStore(this, jsii.String("Store"), &TrustStoreProps{
	Bucket: Bucket,
	Key: jsii.String("rootCA_cert.pem"),
})

lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(443),
	Protocol: elbv2.ApplicationProtocol_HTTPS,
	Certificates: []IListenerCertificate{
		certificate,
	},
	// mTLS settings
	MutualAuthentication: &MutualAuthentication{
		AdvertiseTrustStoreCaNames: jsii.Boolean(true),
		IgnoreClientCertificateExpiry: jsii.Boolean(false),
		MutualAuthenticationMode: elbv2.MutualAuthenticationMode_VERIFY,
		TrustStore: *TrustStore,
	},
	DefaultAction: elbv2.ListenerAction_FixedResponse(jsii.Number(200), &FixedResponseOptions{
		ContentType: jsii.String("text/plain"),
		MessageBody: jsii.String("Success mTLS"),
	}),
})

Methods ​

authenticateJwt(options: AuthenticateJwtOptions): ListenerAction // chainable@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 // chainable@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 // chainable@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 // chainable@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 // chainable@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 // chainable@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.