Skip to content
v2.274.0

Amazon Cognito Construct Library ​

Amazon Cognito provides authentication, authorization, and user management for your web and mobile apps. Your users can sign in directly with a user name and password, or through a third party such as Facebook, Amazon, Google or Apple.

The two main components of Amazon Cognito are user pools and identity pools. User pools are user directories that provide sign-up and sign-in options for your app users. Identity pools enable you to grant your users access to other AWS services. Identity Pool L2 Constructs can be found here.

This module is part of the AWS Cloud Development Kit project.

User Pools ​

User pools allow creating and managing your own directory of users that can sign up and sign in. They enable easy integration with social identity providers such as Facebook, Google, Amazon, Microsoft Active Directory, etc. through SAML.

Using the CDK, a new user pool can be created as part of the stack using the construct's constructor. You may specify the userPoolName to give your own identifier to the user pool. If not, CloudFormation will generate a name.

ts
new cognito.UserPool(this, 'myuserpool', {
  userPoolName: 'myawesomeapp-userpool',
  signInCaseSensitive: false, // case insensitive is preferred in most situations
});
python
cognito.UserPool(self, "myuserpool",
    user_pool_name="myawesomeapp-userpool",
    sign_in_case_sensitive=False
)
java
UserPool.Builder.create(this, "myuserpool")
        .userPoolName("myawesomeapp-userpool")
        .signInCaseSensitive(false)
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    UserPoolName = "myawesomeapp-userpool",
    SignInCaseSensitive = false
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	UserPoolName: jsii.String("myawesomeapp-userpool"),
	SignInCaseSensitive: jsii.Boolean(false),
})

By default, usernames and email addresses in user pools are case sensitive, which means user@example.com and User@example.com are considered different. In most situations it is preferred to have usernames and email addresses be case insensitive so that capitalization differences are ignored. As shown above, you can make a user pool case insensitive by setting signInCaseSensitive to false. The case sensitivity cannot be changed once a user pool is created.

The default set up for the user pool is configured such that only administrators will be allowed to create users. Features such as Multi-factor authentication (MFAs) and Lambda Triggers are not configured by default.

Use the grant() method to add an IAM policy statement associated with the user pool to an IAM principal's policy.

ts
const userPool = new cognito.UserPool(this, 'myuserpool');
const role = new iam.Role(this, 'role', {
  assumedBy: new iam.ServicePrincipal('foo'),
});
userPool.grant(role, 'cognito-idp:AdminCreateUser');
python
user_pool = cognito.UserPool(self, "myuserpool")
role = iam.Role(self, "role",
    assumed_by=iam.ServicePrincipal("foo")
)
user_pool.grant(role, "cognito-idp:AdminCreateUser")
java
UserPool userPool = new UserPool(this, "myuserpool");
Role role = Role.Builder.create(this, "role")
        .assumedBy(new ServicePrincipal("foo"))
        .build();
userPool.grant(role, "cognito-idp:AdminCreateUser");
csharp
var userPool = new UserPool(this, "myuserpool");
var role = new Role(this, "role", new RoleProps {
    AssumedBy = new ServicePrincipal("foo")
});
userPool.Grant(role, "cognito-idp:AdminCreateUser");
go
userPool := cognito.NewUserPool(this, jsii.String("myuserpool"))
role := iam.NewRole(this, jsii.String("role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("foo")),
})
userPool.grant(role, jsii.String("cognito-idp:AdminCreateUser"))

User pool feature plans ​

Amazon Cognito has feature plans for user pools. Each plan has a set of features and a monthly cost per active user. Each feature plan unlocks access to more features than the one before it. Learn more about feature plans here.

  • Lite - a low-cost feature plan for user pools with lower numbers of monthly active users.
  • Essentials - all of the latest user pool authentication features.
  • Plus - includes everything in the Essentials plan and adds advanced security features that protect your users.

The default feature plan is Essentials for newly create user pools. For the existing user pools, Lite plan is automatically set.

Previously, some user pool features were included in an advanced security features pricing structure. The features that were included in this structure are now under either the Essentials or Plus plan.

Sign Up ​

Users can either be signed up by the app's administrators or can sign themselves up. Once a user has signed up, their account needs to be confirmed. Cognito provides several ways to sign users up and confirm their accounts. Learn more about user sign up here.

To verify the email address of a user in your user pool with Amazon Cognito, you can send the user an email message with a link that they can select, or you can send them a code that they can enter.

Code Verification ​

When a user signs up, email and SMS messages are used to verify their account and contact methods. The following code snippet configures a user pool with properties relevant to these verification messages -

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  selfSignUpEnabled: true,
  userVerification: {
    emailSubject: 'Verify your email for our awesome app!',
    emailBody: 'Thanks for signing up to our awesome app! Your verification code is {####}',
    emailStyle: cognito.VerificationEmailStyle.CODE,
    smsMessage: 'Thanks for signing up to our awesome app! Your verification code is {####}',
  },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    self_sign_up_enabled=True,
    user_verification=cognito.UserVerificationConfig(
        email_subject="Verify your email for our awesome app!",
        email_body="Thanks for signing up to our awesome app! Your verification code is {####}",
        email_style=cognito.VerificationEmailStyle.CODE,
        sms_message="Thanks for signing up to our awesome app! Your verification code is {####}"
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        .selfSignUpEnabled(true)
        .userVerification(UserVerificationConfig.builder()
                .emailSubject("Verify your email for our awesome app!")
                .emailBody("Thanks for signing up to our awesome app! Your verification code is {####}")
                .emailStyle(VerificationEmailStyle.CODE)
                .smsMessage("Thanks for signing up to our awesome app! Your verification code is {####}")
                .build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    SelfSignUpEnabled = true,
    UserVerification = new UserVerificationConfig {
        EmailSubject = "Verify your email for our awesome app!",
        EmailBody = "Thanks for signing up to our awesome app! Your verification code is {####}",
        EmailStyle = VerificationEmailStyle.CODE,
        SmsMessage = "Thanks for signing up to our awesome app! Your verification code is {####}"
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	SelfSignUpEnabled: jsii.Boolean(true),
	UserVerification: &UserVerificationConfig{
		EmailSubject: jsii.String("Verify your email for our awesome app!"),
		EmailBody: jsii.String("Thanks for signing up to our awesome app! Your verification code is {####}"),
		EmailStyle: cognito.VerificationEmailStyle_CODE,
		SmsMessage: jsii.String("Thanks for signing up to our awesome app! Your verification code is {####}"),
	},
})

By default, self sign up is disabled. Learn more about email and SMS verification messages here.

Besides users signing themselves up, an administrator of any user pool can sign users up. The user then receives an invitation to join the user pool. The following code snippet configures a user pool with properties relevant to the invitation messages -

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  userInvitation: {
    emailSubject: 'Invite to join our awesome app!',
    emailBody: 'Hello {username}, you have been invited to join our awesome app! Your temporary password is {####}',
    smsMessage: 'Hello {username}, your temporary password for our awesome app is {####}',
  },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    user_invitation=cognito.UserInvitationConfig(
        email_subject="Invite to join our awesome app!",
        email_body="Hello {username}, you have been invited to join our awesome app! Your temporary password is {####}",
        sms_message="Hello {username}, your temporary password for our awesome app is {####}"
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        .userInvitation(UserInvitationConfig.builder()
                .emailSubject("Invite to join our awesome app!")
                .emailBody("Hello {username}, you have been invited to join our awesome app! Your temporary password is {####}")
                .smsMessage("Hello {username}, your temporary password for our awesome app is {####}")
                .build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    UserInvitation = new UserInvitationConfig {
        EmailSubject = "Invite to join our awesome app!",
        EmailBody = "Hello {username}, you have been invited to join our awesome app! Your temporary password is {####}",
        SmsMessage = "Hello {username}, your temporary password for our awesome app is {####}"
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	UserInvitation: &UserInvitationConfig{
		EmailSubject: jsii.String("Invite to join our awesome app!"),
		EmailBody: jsii.String("Hello {username}, you have been invited to join our awesome app! Your temporary password is {####}"),
		SmsMessage: jsii.String("Hello {username}, your temporary password for our awesome app is {####}"),
	},
})

Alternatively, users can use link as a verification method. The following code snippet configures a user pool with properties relevant to these verification messages and link verification method.

ts
new cognito.UserPool(this, 'myuserpool', {
  userVerification: {
    emailStyle: cognito.VerificationEmailStyle.LINK,
    emailSubject: 'Invite to join our awesome app!',
    emailBody: 'You have been invited to join our awesome app! {##Verify Your Email##}',
  },
});
python
cognito.UserPool(self, "myuserpool",
    user_verification=cognito.UserVerificationConfig(
        email_style=cognito.VerificationEmailStyle.LINK,
        email_subject="Invite to join our awesome app!",
        email_body="You have been invited to join our awesome app! {##Verify Your Email##}"
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        .userVerification(UserVerificationConfig.builder()
                .emailStyle(VerificationEmailStyle.LINK)
                .emailSubject("Invite to join our awesome app!")
                .emailBody("You have been invited to join our awesome app! {##Verify Your Email##}")
                .build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    UserVerification = new UserVerificationConfig {
        EmailStyle = VerificationEmailStyle.LINK,
        EmailSubject = "Invite to join our awesome app!",
        EmailBody = "You have been invited to join our awesome app! {##Verify Your Email##}"
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	UserVerification: &UserVerificationConfig{
		EmailStyle: cognito.VerificationEmailStyle_LINK,
		EmailSubject: jsii.String("Invite to join our awesome app!"),
		EmailBody: jsii.String("You have been invited to join our awesome app! {##Verify Your Email##}"),
	},
})

All email subjects, bodies and SMS messages for both invitation and verification support Cognito's message templating. Learn more about message templates here.

Sign In ​

Users registering or signing in into your application can do so with multiple identifiers. There are 4 options available:

  • username: Allow signing in using the one time immutable user name that the user chose at the time of sign up.
  • email: Allow signing in using the email address that is associated with the account.
  • phone: Allow signing in using the phone number that is associated with the account.
  • preferredUsername: Allow signing in with an alternate user name that the user can change at any time. However, this is not available if the username option is not chosen.

The following code sets up a user pool so that the user can sign in with either their username or their email address -

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  // ...
  signInAliases: {
    username: true,
    email: true,
  },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    # ...
    sign_in_aliases=cognito.SignInAliases(
        username=True,
        email=True
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        // ...
        .signInAliases(SignInAliases.builder()
                .username(true)
                .email(true)
                .build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    // ...
    SignInAliases = new SignInAliases {
        Username = true,
        Email = true
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	// ...
	SignInAliases: &SignInAliases{
		Username: jsii.Boolean(true),
		Email: jsii.Boolean(true),
	},
})

User pools can either be configured so that user name is primary sign in form, but also allows for the other three to be used additionally; or it can be configured so that email and/or phone numbers are the only ways a user can register and sign in. Read more about this here.

⚠️ The Cognito service prevents changing the signInAlias property for an existing user pool.

To match with 'Option 1' in the above link, with a verified email, signInAliases should be set to { username: true, email: true }. To match with 'Option 2' in the above link with both a verified email and phone number, this property should be set to { email: true, phone: true }.

Cognito recommends that email and phone number be automatically verified, if they are one of the sign in methods for the user pool. Read more about that here. The CDK does this by default, when email and/or phone number are specified as part of signInAliases. This can be overridden by specifying the autoVerify property.

The following code snippet sets up only email as a sign in alias, but both email and phone number to be auto-verified.

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  // ...
  signInAliases: { username: true, email: true },
  autoVerify: { email: true, phone: true },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    # ...
    sign_in_aliases=cognito.SignInAliases(username=True, email=True),
    auto_verify=cognito.AutoVerifiedAttrs(email=True, phone=True)
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        // ...
        .signInAliases(SignInAliases.builder().username(true).email(true).build())
        .autoVerify(AutoVerifiedAttrs.builder().email(true).phone(true).build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    // ...
    SignInAliases = new SignInAliases { Username = true, Email = true },
    AutoVerify = new AutoVerifiedAttrs { Email = true, Phone = true }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	// ...
	SignInAliases: &SignInAliases{
		Username: jsii.Boolean(true),
		Email: jsii.Boolean(true),
	},
	AutoVerify: &AutoVerifiedAttrs{
		Email: jsii.Boolean(true),
		Phone: jsii.Boolean(true),
	},
})

A user pool can optionally ignore case when evaluating sign-ins. When signInCaseSensitive is false, Cognito will not check the capitalization of the alias when signing in. Default is true.

Choice-based authentication: passwordless sign-in / passkey sign-in ​

User pools can be configured to allow the following authentication methods in choice-based authentication:

  • Passwordless sign-in with email message one-time password
  • Passwordless sign-in with SMS message one-time password
  • Passkey (WebAuthn) sign-in

To use choice-based authentication, User pool feature plan should be Essentials or higher.

For details of authentication methods and client implementation, see Manage authentication methods in AWS SDKs.

The following code configures a user pool with choice-based authentication enabled:

ts
const userPool = new cognito.UserPool(this, 'myuserpool', {
  signInPolicy: {
    allowedFirstAuthFactors: {
      password: true, // password authentication must be enabled
      emailOtp: true, // enables email message one-time password
      smsOtp: true,   // enables SMS message one-time password
      passkey: true,  // enables passkey sign-in
    },
  },
});

// You should also configure the user pool client with USER_AUTH authentication flow allowed
userPool.addClient('myclient', {
  authFlows: { user: true },
});
python
user_pool = cognito.UserPool(self, "myuserpool",
    sign_in_policy=cognito.SignInPolicy(
        allowed_first_auth_factors=cognito.AllowedFirstAuthFactors(
            password=True,  # password authentication must be enabled
            email_otp=True,  # enables email message one-time password
            sms_otp=True,  # enables SMS message one-time password
            passkey=True
        )
    )
)

# You should also configure the user pool client with USER_AUTH authentication flow allowed
user_pool.add_client("myclient",
    auth_flows=cognito.AuthFlow(user=True)
)
java
UserPool userPool = UserPool.Builder.create(this, "myuserpool")
        .signInPolicy(SignInPolicy.builder()
                .allowedFirstAuthFactors(AllowedFirstAuthFactors.builder()
                        .password(true) // password authentication must be enabled
                        .emailOtp(true) // enables email message one-time password
                        .smsOtp(true) // enables SMS message one-time password
                        .passkey(true)
                        .build())
                .build())
        .build();

// You should also configure the user pool client with USER_AUTH authentication flow allowed
userPool.addClient("myclient", UserPoolClientOptions.builder()
        .authFlows(AuthFlow.builder().user(true).build())
        .build());
csharp
var userPool = new UserPool(this, "myuserpool", new UserPoolProps {
    SignInPolicy = new SignInPolicy {
        AllowedFirstAuthFactors = new AllowedFirstAuthFactors {
            Password = true,  // password authentication must be enabled
            EmailOtp = true,  // enables email message one-time password
            SmsOtp = true,  // enables SMS message one-time password
            Passkey = true
        }
    }
});

// You should also configure the user pool client with USER_AUTH authentication flow allowed
userPool.AddClient("myclient", new UserPoolClientOptions {
    AuthFlows = new AuthFlow { User = true }
});
go
userPool := cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	SignInPolicy: &SignInPolicy{
		AllowedFirstAuthFactors: &AllowedFirstAuthFactors{
			Password: jsii.Boolean(true),
			 // password authentication must be enabled
			EmailOtp: jsii.Boolean(true),
			 // enables email message one-time password
			SmsOtp: jsii.Boolean(true),
			 // enables SMS message one-time password
			Passkey: jsii.Boolean(true),
		},
	},
})

// You should also configure the user pool client with USER_AUTH authentication flow allowed
userPool.addClient(jsii.String("myclient"), &UserPoolClientOptions{
	AuthFlows: &AuthFlow{
		User: jsii.Boolean(true),
	},
})

⚠️ Enabling SMS message one-time password requires the AWS account be activated to SMS message sending. Learn more about SMS message settings for Amazon Cognito user pools.

When enabling passkey sign-in, you should specify the authentication domain used as the relying party ID. Learn more about passkey sign-in of user pools and Web Authentication API.

ts
// Use the hosted Amazon Cognito domain as the relying party ID
new cognito.UserPool(this, 'myuserpool', {
  signInPolicy: {
    allowedFirstAuthFactors: { password: true, passkey: true },
  },
  passkeyRelyingPartyId: 'myclientname.auth.region-name.amazoncognito.com',
});

// Use the custom domain as the relying party ID
new cognito.UserPool(this, 'myuserpool', {
  signInPolicy: {
    allowedFirstAuthFactors: { password: true, passkey: true },
  },
  passkeyRelyingPartyId: 'auth.example.com',
});
python
# Use the hosted Amazon Cognito domain as the relying party ID
cognito.UserPool(self, "myuserpool",
    sign_in_policy=cognito.SignInPolicy(
        allowed_first_auth_factors=cognito.AllowedFirstAuthFactors(password=True, passkey=True)
    ),
    passkey_relying_party_id="myclientname.auth.region-name.amazoncognito.com"
)

# Use the custom domain as the relying party ID
cognito.UserPool(self, "myuserpool",
    sign_in_policy=cognito.SignInPolicy(
        allowed_first_auth_factors=cognito.AllowedFirstAuthFactors(password=True, passkey=True)
    ),
    passkey_relying_party_id="auth.example.com"
)
java
// Use the hosted Amazon Cognito domain as the relying party ID
// Use the hosted Amazon Cognito domain as the relying party ID
UserPool.Builder.create(this, "myuserpool")
        .signInPolicy(SignInPolicy.builder()
                .allowedFirstAuthFactors(AllowedFirstAuthFactors.builder().password(true).passkey(true).build())
                .build())
        .passkeyRelyingPartyId("myclientname.auth.region-name.amazoncognito.com")
        .build();

// Use the custom domain as the relying party ID
// Use the custom domain as the relying party ID
UserPool.Builder.create(this, "myuserpool")
        .signInPolicy(SignInPolicy.builder()
                .allowedFirstAuthFactors(AllowedFirstAuthFactors.builder().password(true).passkey(true).build())
                .build())
        .passkeyRelyingPartyId("auth.example.com")
        .build();
csharp
// Use the hosted Amazon Cognito domain as the relying party ID
// Use the hosted Amazon Cognito domain as the relying party ID
new UserPool(this, "myuserpool", new UserPoolProps {
    SignInPolicy = new SignInPolicy {
        AllowedFirstAuthFactors = new AllowedFirstAuthFactors { Password = true, Passkey = true }
    },
    PasskeyRelyingPartyId = "myclientname.auth.region-name.amazoncognito.com"
});

// Use the custom domain as the relying party ID
// Use the custom domain as the relying party ID
new UserPool(this, "myuserpool", new UserPoolProps {
    SignInPolicy = new SignInPolicy {
        AllowedFirstAuthFactors = new AllowedFirstAuthFactors { Password = true, Passkey = true }
    },
    PasskeyRelyingPartyId = "auth.example.com"
});
go
// Use the hosted Amazon Cognito domain as the relying party ID
// Use the hosted Amazon Cognito domain as the relying party ID
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	SignInPolicy: &SignInPolicy{
		AllowedFirstAuthFactors: &AllowedFirstAuthFactors{
			Password: jsii.Boolean(true),
			Passkey: jsii.Boolean(true),
		},
	},
	PasskeyRelyingPartyId: jsii.String("myclientname.auth.region-name.amazoncognito.com"),
})

// Use the custom domain as the relying party ID
// Use the custom domain as the relying party ID
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	SignInPolicy: &SignInPolicy{
		AllowedFirstAuthFactors: &AllowedFirstAuthFactors{
			Password: jsii.Boolean(true),
			Passkey: jsii.Boolean(true),
		},
	},
	PasskeyRelyingPartyId: jsii.String("auth.example.com"),
})

You can configure user verification to be preferred (default) or required. When you set user verification to preferred, users can set up authenticators that don't have the user verification capability, and registration and authentication operations can succeed without user verification. To mandate user verification in passkey registration and authentication, specify passkeyUserVerification to PasskeyUserVerification.REQUIRED.

ts
new cognito.UserPool(this, 'myuserpool', {
  signInPolicy: {
    allowedFirstAuthFactors: { password: true, passkey: true },
  },
  passkeyRelyingPartyId: 'auth.example.com',
  passkeyUserVerification: cognito.PasskeyUserVerification.REQUIRED,
});
python
cognito.UserPool(self, "myuserpool",
    sign_in_policy=cognito.SignInPolicy(
        allowed_first_auth_factors=cognito.AllowedFirstAuthFactors(password=True, passkey=True)
    ),
    passkey_relying_party_id="auth.example.com",
    passkey_user_verification=cognito.PasskeyUserVerification.REQUIRED
)
java
UserPool.Builder.create(this, "myuserpool")
        .signInPolicy(SignInPolicy.builder()
                .allowedFirstAuthFactors(AllowedFirstAuthFactors.builder().password(true).passkey(true).build())
                .build())
        .passkeyRelyingPartyId("auth.example.com")
        .passkeyUserVerification(PasskeyUserVerification.REQUIRED)
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    SignInPolicy = new SignInPolicy {
        AllowedFirstAuthFactors = new AllowedFirstAuthFactors { Password = true, Passkey = true }
    },
    PasskeyRelyingPartyId = "auth.example.com",
    PasskeyUserVerification = PasskeyUserVerification.REQUIRED
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	SignInPolicy: &SignInPolicy{
		AllowedFirstAuthFactors: &AllowedFirstAuthFactors{
			Password: jsii.Boolean(true),
			Passkey: jsii.Boolean(true),
		},
	},
	PasskeyRelyingPartyId: jsii.String("auth.example.com"),
	PasskeyUserVerification: cognito.PasskeyUserVerification_REQUIRED,
})

To disable choice-based authentication explicitly, specify password only.

ts
new cognito.UserPool(this, 'myuserpool', {
  signInPolicy: {
    allowedFirstAuthFactors: { password: true },
  },
  featurePlan: cognito.FeaturePlan.LITE,
});
python
cognito.UserPool(self, "myuserpool",
    sign_in_policy=cognito.SignInPolicy(
        allowed_first_auth_factors=cognito.AllowedFirstAuthFactors(password=True)
    ),
    feature_plan=cognito.FeaturePlan.LITE
)
java
UserPool.Builder.create(this, "myuserpool")
        .signInPolicy(SignInPolicy.builder()
                .allowedFirstAuthFactors(AllowedFirstAuthFactors.builder().password(true).build())
                .build())
        .featurePlan(FeaturePlan.LITE)
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    SignInPolicy = new SignInPolicy {
        AllowedFirstAuthFactors = new AllowedFirstAuthFactors { Password = true }
    },
    FeaturePlan = FeaturePlan.LITE
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	SignInPolicy: &SignInPolicy{
		AllowedFirstAuthFactors: &AllowedFirstAuthFactors{
			Password: jsii.Boolean(true),
		},
	},
	FeaturePlan: cognito.FeaturePlan_LITE,
})

Attributes ​

Attributes represent the various properties of each user that's collected and stored in the user pool. Cognito provides a set of standard attributes that are available for all user pools. Users are allowed to select any of these standard attributes to be required. Users will not be able to sign up to the user pool without providing the required attributes. Besides these, additional attributes can be further defined, and are known as custom attributes.

Learn more on attributes in Cognito's documentation.

The following code configures a user pool with two standard attributes (name and address) as required and mutable, and adds four custom attributes.

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  standardAttributes: {
    fullname: {
      required: true,
      mutable: false,
    },
    address: {
      required: false,
      mutable: true,
    },
  },
  customAttributes: {
    'myappid': new cognito.StringAttribute({ minLen: 5, maxLen: 15, mutable: false }),
    'callingcode': new cognito.NumberAttribute({ min: 1, max: 3, mutable: true }),
    'isEmployee': new cognito.BooleanAttribute({ mutable: true }),
    'joinedOn': new cognito.DateTimeAttribute(),
  },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    standard_attributes=cognito.StandardAttributes(
        fullname=cognito.StandardAttribute(
            required=True,
            mutable=False
        ),
        address=cognito.StandardAttribute(
            required=False,
            mutable=True
        )
    ),
    custom_attributes={
        "myappid": cognito.StringAttribute(min_len=5, max_len=15, mutable=False),
        "callingcode": cognito.NumberAttribute(min=1, max=3, mutable=True),
        "isEmployee": cognito.BooleanAttribute(mutable=True),
        "joinedOn": cognito.DateTimeAttribute()
    }
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        .standardAttributes(StandardAttributes.builder()
                .fullname(StandardAttribute.builder()
                        .required(true)
                        .mutable(false)
                        .build())
                .address(StandardAttribute.builder()
                        .required(false)
                        .mutable(true)
                        .build())
                .build())
        .customAttributes(Map.of(
                "myappid", StringAttribute.Builder.create().minLen(5).maxLen(15).mutable(false).build(),
                "callingcode", NumberAttribute.Builder.create().min(1).max(3).mutable(true).build(),
                "isEmployee", BooleanAttribute.Builder.create().mutable(true).build(),
                "joinedOn", new DateTimeAttribute()))
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    StandardAttributes = new StandardAttributes {
        Fullname = new StandardAttribute {
            Required = true,
            Mutable = false
        },
        Address = new StandardAttribute {
            Required = false,
            Mutable = true
        }
    },
    CustomAttributes = new Dictionary<string, ICustomAttribute> {
        { "myappid", new StringAttribute(new StringAttributeProps { MinLen = 5, MaxLen = 15, Mutable = false }) },
        { "callingcode", new NumberAttribute(new NumberAttributeProps { Min = 1, Max = 3, Mutable = true }) },
        { "isEmployee", new BooleanAttribute(new CustomAttributeProps { Mutable = true }) },
        { "joinedOn", new DateTimeAttribute() }
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	StandardAttributes: &StandardAttributes{
		Fullname: &StandardAttribute{
			Required: jsii.Boolean(true),
			Mutable: jsii.Boolean(false),
		},
		Address: &StandardAttribute{
			Required: jsii.Boolean(false),
			Mutable: jsii.Boolean(true),
		},
	},
	CustomAttributes: map[string]ICustomAttribute{
		"myappid": cognito.NewStringAttribute(&StringAttributeProps{
			"minLen": jsii.Number(5),
			"maxLen": jsii.Number(15),
			"mutable": jsii.Boolean(false),
		}),
		"callingcode": cognito.NewNumberAttribute(&NumberAttributeProps{
			"min": jsii.Number(1),
			"max": jsii.Number(3),
			"mutable": jsii.Boolean(true),
		}),
		"isEmployee": cognito.NewBooleanAttribute(&CustomAttributeProps{
			"mutable": jsii.Boolean(true),
		}),
		"joinedOn": cognito.NewDateTimeAttribute(),
	},
})

As shown in the code snippet, there are data types that are available for custom attributes. The 'String' and 'Number' data types allow for further constraints on their length and values, respectively.

Custom attributes cannot be marked as required.

All custom attributes share the property mutable that specifies whether the value of the attribute can be changed. The default value is false.

User pools come with two 'built-in' attributes - email_verified and phone_number_verified. These cannot be configured (required-ness or mutability) as part of user pool creation. However, user pool administrators can modify them for specific users using the AdminUpdateUserAttributes API.

Attribute verification ​

When your user updates an email address or phone number attribute, Amazon Cognito marks it unverified until they verify the new value. You can’t send messages to an unverified email address or phone number. Your user can’t sign in with an unverified alias attribute. You can choose how Amazon Cognito handles an updated email address or phone number after the update and before the verification.

Learn more on configuring email or phone verification in Cognito's documentation.

The following code configures a user pool that keeps the original value for the two standard attributes (email and phone_number) until the new values are verified.

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  signInAliases: { username: true },
  autoVerify: { email: true, phone: true },
  keepOriginal: {
    email: true,
    phone: true,
  },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    sign_in_aliases=cognito.SignInAliases(username=True),
    auto_verify=cognito.AutoVerifiedAttrs(email=True, phone=True),
    keep_original=cognito.KeepOriginalAttrs(
        email=True,
        phone=True
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        .signInAliases(SignInAliases.builder().username(true).build())
        .autoVerify(AutoVerifiedAttrs.builder().email(true).phone(true).build())
        .keepOriginal(KeepOriginalAttrs.builder()
                .email(true)
                .phone(true)
                .build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    SignInAliases = new SignInAliases { Username = true },
    AutoVerify = new AutoVerifiedAttrs { Email = true, Phone = true },
    KeepOriginal = new KeepOriginalAttrs {
        Email = true,
        Phone = true
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	SignInAliases: &SignInAliases{
		Username: jsii.Boolean(true),
	},
	AutoVerify: &AutoVerifiedAttrs{
		Email: jsii.Boolean(true),
		Phone: jsii.Boolean(true),
	},
	KeepOriginal: &KeepOriginalAttrs{
		Email: jsii.Boolean(true),
		Phone: jsii.Boolean(true),
	},
})

Security ​

Cognito sends various messages to its users via SMS, for different actions, ranging from account verification to marketing. In order to send SMS messages, Cognito needs an IAM role that it can assume, with permissions that allow it to send SMS messages.

By default, the CDK looks at all of the specified properties (and their defaults when not explicitly specified) and automatically creates an SMS role, when needed. For example, if MFA second factor by SMS is enabled, the CDK will create a new role. The smsRole property can be used to specify the user supplied role that should be used instead. Additionally, the property enableSmsRole can be used to override the CDK's default behaviour to either enable or suppress automatic role creation.

ts
const poolSmsRole = new iam.Role(this, 'userpoolsmsrole', {
  assumedBy: new iam.ServicePrincipal('foo'),
});

new cognito.UserPool(this, 'myuserpool', {
  // ...
  smsRole: poolSmsRole,
  smsRoleExternalId: 'c87467be-4f34-11ea-b77f-2e728ce88125',
});
python
pool_sms_role = iam.Role(self, "userpoolsmsrole",
    assumed_by=iam.ServicePrincipal("foo")
)

cognito.UserPool(self, "myuserpool",
    # ...
    sms_role=pool_sms_role,
    sms_role_external_id="c87467be-4f34-11ea-b77f-2e728ce88125"
)
java
Role poolSmsRole = Role.Builder.create(this, "userpoolsmsrole")
        .assumedBy(new ServicePrincipal("foo"))
        .build();

UserPool.Builder.create(this, "myuserpool")
        // ...
        .smsRole(poolSmsRole)
        .smsRoleExternalId("c87467be-4f34-11ea-b77f-2e728ce88125")
        .build();
csharp
var poolSmsRole = new Role(this, "userpoolsmsrole", new RoleProps {
    AssumedBy = new ServicePrincipal("foo")
});

new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    SmsRole = poolSmsRole,
    SmsRoleExternalId = "c87467be-4f34-11ea-b77f-2e728ce88125"
});
go
poolSmsRole := iam.NewRole(this, jsii.String("userpoolsmsrole"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("foo")),
})

cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	SmsRole: poolSmsRole,
	SmsRoleExternalId: jsii.String("c87467be-4f34-11ea-b77f-2e728ce88125"),
})

When the smsRole property is specified, the smsRoleExternalId may also be specified. The value of smsRoleExternalId will be used as the sts:ExternalId when the Cognito service assumes the role. In turn, the role's assume role policy should be configured to accept this value as the ExternalId. Learn more about ExternalId here.

Multi-factor Authentication (MFA) ​

User pools can be configured to enable multi-factor authentication (MFA). It can either be turned off, set to optional or made required. Setting MFA to optional means that individual users can choose to enable it. Additionally, the MFA code can be sent either via SMS text message or via a time-based software token. See the documentation on MFA to learn more.

The following code snippet marks MFA for the user pool as required. This means that all users are required to configure an MFA token and use it for sign in. It also allows for the users to use both SMS based MFA, as well, time-based one time password (TOTP).

If you want to enable email-based MFA, set email property to the Amazon SES email-sending configuration and set featurePlan to FeaturePlan.ESSENTIALS or FeaturePlan.PLUS. For more information, see SMS and email message MFA.

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  mfa: cognito.Mfa.REQUIRED,
  mfaSecondFactor: {
    sms: true,
    otp: true,
    email: false, // email-based MFA
  },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    mfa=cognito.Mfa.REQUIRED,
    mfa_second_factor=cognito.MfaSecondFactor(
        sms=True,
        otp=True,
        email=False
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        .mfa(Mfa.REQUIRED)
        .mfaSecondFactor(MfaSecondFactor.builder()
                .sms(true)
                .otp(true)
                .email(false)
                .build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    Mfa = Mfa.REQUIRED,
    MfaSecondFactor = new MfaSecondFactor {
        Sms = true,
        Otp = true,
        Email = false
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	Mfa: cognito.Mfa_REQUIRED,
	MfaSecondFactor: &MfaSecondFactor{
		Sms: jsii.Boolean(true),
		Otp: jsii.Boolean(true),
		Email: jsii.Boolean(false),
	},
})

User pools can be configured with policies around a user's password. This includes the password length and the character sets that they must contain.

Further to this, it can also be configured with the validity of the auto-generated temporary password. A temporary password is generated by the user pool either when an admin signs up a user or when a password reset is requested. The validity of this password dictates how long to give the user to use this password before expiring it.

You can also set a policy for password reuse by setting the passwordHistorySize property. You can prevent a user from resetting their password to a new password that matches their current password or any of up to 23 additional previous passwords, for a maximum total of 24. The passwordHistorySize property can not be set when featurePlan is FeaturePlan.LITE.

The following code snippet configures these properties -

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  passwordPolicy: {
    minLength: 12,
    requireLowercase: true,
    requireUppercase: true,
    requireDigits: true,
    requireSymbols: true,
    tempPasswordValidity: Duration.days(3),
  },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    password_policy=cognito.PasswordPolicy(
        min_length=12,
        require_lowercase=True,
        require_uppercase=True,
        require_digits=True,
        require_symbols=True,
        temp_password_validity=Duration.days(3)
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        .passwordPolicy(PasswordPolicy.builder()
                .minLength(12)
                .requireLowercase(true)
                .requireUppercase(true)
                .requireDigits(true)
                .requireSymbols(true)
                .tempPasswordValidity(Duration.days(3))
                .build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    PasswordPolicy = new PasswordPolicy {
        MinLength = 12,
        RequireLowercase = true,
        RequireUppercase = true,
        RequireDigits = true,
        RequireSymbols = true,
        TempPasswordValidity = Duration.Days(3)
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	PasswordPolicy: &PasswordPolicy{
		MinLength: jsii.Number(12),
		RequireLowercase: jsii.Boolean(true),
		RequireUppercase: jsii.Boolean(true),
		RequireDigits: jsii.Boolean(true),
		RequireSymbols: jsii.Boolean(true),
		TempPasswordValidity: awscdk.Duration_Days(jsii.Number(3)),
	},
})

Note that, tempPasswordValidity can be specified only in whole days. Specifying fractional days would throw an error.

Account Recovery Settings ​

User pools can be configured on which method a user should use when recovering the password for their account. This can either be email and/or SMS. Read more at Recovering User Accounts

ts
new cognito.UserPool(this, 'UserPool', {
  // ...
  accountRecovery: cognito.AccountRecovery.EMAIL_ONLY,
})
python
cognito.UserPool(self, "UserPool",
    # ...
    account_recovery=cognito.AccountRecovery.EMAIL_ONLY
)
java
UserPool.Builder.create(this, "UserPool")
        // ...
        .accountRecovery(AccountRecovery.EMAIL_ONLY)
        .build();
csharp
new UserPool(this, "UserPool", new UserPoolProps {
    // ...
    AccountRecovery = AccountRecovery.EMAIL_ONLY
});
go
cognito.NewUserPool(this, jsii.String("UserPool"), &UserPoolProps{
	// ...
	AccountRecovery: cognito.AccountRecovery_EMAIL_ONLY,
})

The default for account recovery is by phone if available and by email otherwise. A user will not be allowed to reset their password via phone if they are also using it for MFA.

Advanced Security Mode ​

⚠️ Advanced Security Mode is deprecated in favor of Threat Protection.

User pools can be configured to use Advanced security. You can turn the user pool advanced security features on, and customize the actions that are taken in response to different risks. Or you can use audit mode to gather metrics on detected risks without taking action. In audit mode, the advanced security features publish metrics to Amazon CloudWatch. See the documentation on Advanced security to learn more.

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  advancedSecurityMode: cognito.AdvancedSecurityMode.ENFORCED,
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    advanced_security_mode=cognito.AdvancedSecurityMode.ENFORCED
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        .advancedSecurityMode(AdvancedSecurityMode.ENFORCED)
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    AdvancedSecurityMode = AdvancedSecurityMode.ENFORCED
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	AdvancedSecurityMode: cognito.AdvancedSecurityMode_ENFORCED,
})

Threat Protection ​

Threat Protection can be set to configure enforcement levels and automatic responses for users in password-based and custom-challenge authentication flows. For configuration, there are 2 options for standard authentication and custom authentication. These are represented with properties standardThreatProtectionMode and customThreatProtectionMode. See the documentation on Threat Protection

Note: Threat Protection requires the PLUS feature plan for new user pools. CDK allows you to configure threat protection settings at synthesis time, and CloudFormation will validate feature plan requirements at deployment time. Existing user pools that are grandfathered on LITE plans with threat protection enabled will continue to work.

Emails ​

Cognito sends emails to users in the user pool, when particular actions take place, such as welcome emails, invitation emails, password resets, etc. The address from which these emails are sent can be configured on the user pool. Read more at Email settings for User Pools.

By default, user pools are configured to use Cognito's built in email capability, which will send emails from no-reply@verificationemail.com. If you want to use a custom email address you can configure Cognito to send emails through Amazon SES, which is detailed below.

ts
new cognito.UserPool(this, 'myuserpool', {
  email: cognito.UserPoolEmail.withCognito('support@myawesomeapp.com'),
});
python
cognito.UserPool(self, "myuserpool",
    email=cognito.UserPoolEmail.with_cognito("support@myawesomeapp.com")
)
java
UserPool.Builder.create(this, "myuserpool")
        .email(UserPoolEmail.withCognito("support@myawesomeapp.com"))
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    Email = UserPoolEmail.WithCognito("support@myawesomeapp.com")
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	Email: cognito.UserPoolEmail_WithCognito(jsii.String("support@myawesomeapp.com")),
})

For typical production environments, the default email limit is below the required delivery volume. To enable a higher delivery volume, you can configure the UserPool to send emails through Amazon SES. To do so, follow the steps in the Cognito Developer Guide to verify an email address, move the account out of the SES sandbox, and grant Cognito email permissions via an authorization policy.

Once the SES setup is complete, the UserPool can be configured to use the SES email.

ts
new cognito.UserPool(this, 'myuserpool', {
  email: cognito.UserPoolEmail.withSES({
    fromEmail: 'noreply@myawesomeapp.com',
    fromName: 'Awesome App',
    replyTo: 'support@myawesomeapp.com',
  }),
});
python
cognito.UserPool(self, "myuserpool",
    email=cognito.UserPoolEmail.with_ses(
        from_email="noreply@myawesomeapp.com",
        from_name="Awesome App",
        reply_to="support@myawesomeapp.com"
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        .email(UserPoolEmail.withSES(UserPoolSESOptions.builder()
                .fromEmail("noreply@myawesomeapp.com")
                .fromName("Awesome App")
                .replyTo("support@myawesomeapp.com")
                .build()))
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    Email = UserPoolEmail.WithSES(new UserPoolSESOptions {
        FromEmail = "noreply@myawesomeapp.com",
        FromName = "Awesome App",
        ReplyTo = "support@myawesomeapp.com"
    })
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	Email: cognito.UserPoolEmail_WithSES(&UserPoolSESOptions{
		FromEmail: jsii.String("noreply@myawesomeapp.com"),
		FromName: jsii.String("Awesome App"),
		ReplyTo: jsii.String("support@myawesomeapp.com"),
	}),
})

Sending emails through SES requires that SES be configured (as described above) in a valid SES region. If the UserPool is being created in a different region, sesRegion must be used to specify the correct SES region.

ts
new cognito.UserPool(this, 'myuserpool', {
  email: cognito.UserPoolEmail.withSES({
    sesRegion: 'us-east-1',
    fromEmail: 'noreply@myawesomeapp.com',
    fromName: 'Awesome App',
    replyTo: 'support@myawesomeapp.com',
  }),
});
python
cognito.UserPool(self, "myuserpool",
    email=cognito.UserPoolEmail.with_ses(
        ses_region="us-east-1",
        from_email="noreply@myawesomeapp.com",
        from_name="Awesome App",
        reply_to="support@myawesomeapp.com"
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        .email(UserPoolEmail.withSES(UserPoolSESOptions.builder()
                .sesRegion("us-east-1")
                .fromEmail("noreply@myawesomeapp.com")
                .fromName("Awesome App")
                .replyTo("support@myawesomeapp.com")
                .build()))
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    Email = UserPoolEmail.WithSES(new UserPoolSESOptions {
        SesRegion = "us-east-1",
        FromEmail = "noreply@myawesomeapp.com",
        FromName = "Awesome App",
        ReplyTo = "support@myawesomeapp.com"
    })
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	Email: cognito.UserPoolEmail_WithSES(&UserPoolSESOptions{
		SesRegion: jsii.String("us-east-1"),
		FromEmail: jsii.String("noreply@myawesomeapp.com"),
		FromName: jsii.String("Awesome App"),
		ReplyTo: jsii.String("support@myawesomeapp.com"),
	}),
})

When sending emails from an SES verified domain, sesVerifiedDomain can be used to specify the domain. The email address does not need to be verified when sending emails from a verified domain, because the identity of the email configuration is can be determined from the domain alone.

ts
new cognito.UserPool(this, 'myuserpool', {
  email: cognito.UserPoolEmail.withSES({
    sesRegion: 'us-east-1',
    fromEmail: 'noreply@myawesomeapp.com',
    fromName: 'Awesome App',
    replyTo: 'support@myawesomeapp.com',
    sesVerifiedDomain: 'myawesomeapp.com',
  }),
});
python
cognito.UserPool(self, "myuserpool",
    email=cognito.UserPoolEmail.with_ses(
        ses_region="us-east-1",
        from_email="noreply@myawesomeapp.com",
        from_name="Awesome App",
        reply_to="support@myawesomeapp.com",
        ses_verified_domain="myawesomeapp.com"
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        .email(UserPoolEmail.withSES(UserPoolSESOptions.builder()
                .sesRegion("us-east-1")
                .fromEmail("noreply@myawesomeapp.com")
                .fromName("Awesome App")
                .replyTo("support@myawesomeapp.com")
                .sesVerifiedDomain("myawesomeapp.com")
                .build()))
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    Email = UserPoolEmail.WithSES(new UserPoolSESOptions {
        SesRegion = "us-east-1",
        FromEmail = "noreply@myawesomeapp.com",
        FromName = "Awesome App",
        ReplyTo = "support@myawesomeapp.com",
        SesVerifiedDomain = "myawesomeapp.com"
    })
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	Email: cognito.UserPoolEmail_WithSES(&UserPoolSESOptions{
		SesRegion: jsii.String("us-east-1"),
		FromEmail: jsii.String("noreply@myawesomeapp.com"),
		FromName: jsii.String("Awesome App"),
		ReplyTo: jsii.String("support@myawesomeapp.com"),
		SesVerifiedDomain: jsii.String("myawesomeapp.com"),
	}),
})

If fromName does not comply RFC 5322 atom or quoted-string, it will be quoted or mime-encoded.

ts
new cognito.UserPool(this, 'myuserpool', {
  email: cognito.UserPoolEmail.withSES({
    fromEmail: 'noreply@myawesomeapp.com',
    fromName: 'myname@mycompany.com',
  }),
});
// => From: "myname@mycompany.com" <noreply@myawesomeapp.com>
python
cognito.UserPool(self, "myuserpool",
    email=cognito.UserPoolEmail.with_ses(
        from_email="noreply@myawesomeapp.com",
        from_name="myname@mycompany.com"
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        .email(UserPoolEmail.withSES(UserPoolSESOptions.builder()
                .fromEmail("noreply@myawesomeapp.com")
                .fromName("myname@mycompany.com")
                .build()))
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    Email = UserPoolEmail.WithSES(new UserPoolSESOptions {
        FromEmail = "noreply@myawesomeapp.com",
        FromName = "myname@mycompany.com"
    })
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	Email: cognito.UserPoolEmail_WithSES(&UserPoolSESOptions{
		FromEmail: jsii.String("noreply@myawesomeapp.com"),
		FromName: jsii.String("myname@mycompany.com"),
	}),
})

Device Tracking ​

User pools can be configured to track devices that users have logged in to. Read more at Device Tracking

ts
new cognito.UserPool(this, 'myuserpool', {
  // ...
  deviceTracking: {
    challengeRequiredOnNewDevice: true,
    deviceOnlyRememberedOnUserPrompt: true,
  },
});
python
cognito.UserPool(self, "myuserpool",
    # ...
    device_tracking=cognito.DeviceTracking(
        challenge_required_on_new_device=True,
        device_only_remembered_on_user_prompt=True
    )
)
java
UserPool.Builder.create(this, "myuserpool")
        // ...
        .deviceTracking(DeviceTracking.builder()
                .challengeRequiredOnNewDevice(true)
                .deviceOnlyRememberedOnUserPrompt(true)
                .build())
        .build();
csharp
new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    DeviceTracking = new DeviceTracking {
        ChallengeRequiredOnNewDevice = true,
        DeviceOnlyRememberedOnUserPrompt = true
    }
});
go
cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	DeviceTracking: &DeviceTracking{
		ChallengeRequiredOnNewDevice: jsii.Boolean(true),
		DeviceOnlyRememberedOnUserPrompt: jsii.Boolean(true),
	},
})

The default is to not track devices.

Lambda Triggers ​

User pools can be configured such that AWS Lambda functions can be triggered when certain user operations or actions occur, such as, sign up, user confirmation, sign in, etc. They can also be used to add custom authentication challenges, user migrations and custom verification messages. Learn more about triggers at User Pool Workflows with Triggers.

Lambda triggers can either be specified as part of the UserPool initialization, or it can be added later, via methods on the construct, as so -

ts
const authChallengeFn = new lambda.Function(this, 'authChallengeFn', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'path/to/asset')),
});

const userpool = new cognito.UserPool(this, 'myuserpool', {
  // ...
  lambdaTriggers: {
    createAuthChallenge: authChallengeFn,
    // ...
  },
});

userpool.addTrigger(cognito.UserPoolOperation.USER_MIGRATION, new lambda.Function(this, 'userMigrationFn', {
    runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'path/to/asset')),
}));
python
auth_challenge_fn = lambda_.Function(self, "authChallengeFn",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "path/to/asset"))
)

userpool = cognito.UserPool(self, "myuserpool",
    # ...
    lambda_triggers=cognito.UserPoolTriggers(
        create_auth_challenge=auth_challenge_fn
    )
)

userpool.add_trigger(cognito.UserPoolOperation.USER_MIGRATION, lambda_.Function(self, "userMigrationFn",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "path/to/asset"))
))
java
Function authChallengeFn = Function.Builder.create(this, "authChallengeFn")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "path/to/asset")))
        .build();

UserPool userpool = UserPool.Builder.create(this, "myuserpool")
        // ...
        .lambdaTriggers(UserPoolTriggers.builder()
                .createAuthChallenge(authChallengeFn)
                .build())
        .build();

userpool.addTrigger(UserPoolOperation.USER_MIGRATION, Function.Builder.create(this, "userMigrationFn")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "path/to/asset")))
        .build());
csharp
var authChallengeFn = new Function(this, "authChallengeFn", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "path/to/asset"))
});

var userpool = new UserPool(this, "myuserpool", new UserPoolProps {
    // ...
    LambdaTriggers = new UserPoolTriggers {
        CreateAuthChallenge = authChallengeFn
    }
});

userpool.AddTrigger(UserPoolOperation.USER_MIGRATION, new Function(this, "userMigrationFn", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "path/to/asset"))
}));
go
authChallengeFn := lambda.NewFunction(this, jsii.String("authChallengeFn"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("path/to/asset"))),
})

userpool := cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	// ...
	LambdaTriggers: &UserPoolTriggers{
		CreateAuthChallenge: authChallengeFn,
	},
})

userpool.AddTrigger(cognito.UserPoolOperation_USER_MIGRATION(), lambda.NewFunction(this, jsii.String("userMigrationFn"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_*FromAsset(path.join(__dirname, jsii.String("path/to/asset"))),
}))

Additionally, only the pre token generation Lambda trigger supports trigger events with lambda version V2.0 or V3.0. For details, see Pre Token Generation Lambda Trigger.

ts
declare const userpool: cognito.UserPool;
declare const preTokenGenerationFn: lambda.Function;

userpool.addTrigger(cognito.UserPoolOperation.PRE_TOKEN_GENERATION_CONFIG, preTokenGenerationFn, cognito.LambdaVersion.V2_0);
python
# userpool: cognito.UserPool
# pre_token_generation_fn: lambda.Function


userpool.add_trigger(cognito.UserPoolOperation.PRE_TOKEN_GENERATION_CONFIG, pre_token_generation_fn, cognito.LambdaVersion.V2_0)
java
UserPool userpool;
Function preTokenGenerationFn;


userpool.addTrigger(UserPoolOperation.PRE_TOKEN_GENERATION_CONFIG, preTokenGenerationFn, LambdaVersion.V2_0);
csharp
UserPool userpool;
Function preTokenGenerationFn;


userpool.AddTrigger(UserPoolOperation.PRE_TOKEN_GENERATION_CONFIG, preTokenGenerationFn, LambdaVersion.V2_0);
go
var userpool UserPool
var preTokenGenerationFn Function


userpool.AddTrigger(cognito.UserPoolOperation_PRE_TOKEN_GENERATION_CONFIG(), preTokenGenerationFn, cognito.LambdaVersion_V2_0)

The following table lists the set of triggers available, and their corresponding method to add it to the user pool. For more information on the function of these triggers and how to configure them, read User Pool Workflows with Triggers.

Trigger Permissions ​

The function.attachToRolePolicy() API can be used to add additional IAM permissions to the lambda trigger as necessary.

⚠️ Using the attachToRolePolicy API to provide permissions to your user pool will result in a circular dependency. See aws/aws-cdk#7016. Error message when running cdk synth or cdk deploy:

Circular dependency between resources: [pool056F3F7E, fnPostAuthFnCognitoA630A2B1, ...]

To work around the circular dependency issue, use the attachInlinePolicy() API instead, as shown below.

ts
declare const postAuthFn: lambda.Function;

const userpool = new cognito.UserPool(this, 'myuserpool', {
  lambdaTriggers: {
    postAuthentication: postAuthFn,
  },
});

// provide permissions to describe the user pool scoped to the ARN the user pool
postAuthFn.role?.attachInlinePolicy(new iam.Policy(this, 'userpool-policy', {
  statements: [new iam.PolicyStatement({
    actions: ['cognito-idp:DescribeUserPool'],
    resources: [userpool.userPoolArn],
  })],
}));
python
# post_auth_fn: lambda.Function


userpool = cognito.UserPool(self, "myuserpool",
    lambda_triggers=cognito.UserPoolTriggers(
        post_authentication=post_auth_fn
    )
)

# provide permissions to describe the user pool scoped to the ARN the user pool
post_auth_fn.role.attach_inline_policy(iam.Policy(self, "userpool-policy",
    statements=[iam.PolicyStatement(
        actions=["cognito-idp:DescribeUserPool"],
        resources=[userpool.user_pool_arn]
    )]
))
java
Function postAuthFn;


UserPool userpool = UserPool.Builder.create(this, "myuserpool")
        .lambdaTriggers(UserPoolTriggers.builder()
                .postAuthentication(postAuthFn)
                .build())
        .build();

// provide permissions to describe the user pool scoped to the ARN the user pool
postAuthFn.role.attachInlinePolicy(Policy.Builder.create(this, "userpool-policy")
        .statements(List.of(PolicyStatement.Builder.create()
                .actions(List.of("cognito-idp:DescribeUserPool"))
                .resources(List.of(userpool.getUserPoolArn()))
                .build()))
        .build());
csharp
Function postAuthFn;


var userpool = new UserPool(this, "myuserpool", new UserPoolProps {
    LambdaTriggers = new UserPoolTriggers {
        PostAuthentication = postAuthFn
    }
});

// provide permissions to describe the user pool scoped to the ARN the user pool
postAuthFn.Role.AttachInlinePolicy(new Policy(this, "userpool-policy", new PolicyProps {
    Statements = new [] { new PolicyStatement(new PolicyStatementProps {
        Actions = new [] { "cognito-idp:DescribeUserPool" },
        Resources = new [] { userpool.UserPoolArn }
    }) }
}));
go
var postAuthFn Function


userpool := cognito.NewUserPool(this, jsii.String("myuserpool"), &UserPoolProps{
	LambdaTriggers: &UserPoolTriggers{
		PostAuthentication: postAuthFn,
	},
})

// provide permissions to describe the user pool scoped to the ARN the user pool
postAuthFn.Role.AttachInlinePolicy(iam.NewPolicy(this, jsii.String("userpool-policy"), &PolicyProps{
	Statements: []PolicyStatement{
		iam.NewPolicyStatement(&PolicyStatementProps{
			Actions: []*string{
				jsii.String("cognito-idp:DescribeUserPool"),
			},
			Resources: []*string{
				userpool.UserPoolArn,
			},
		}),
	},
}))

Importing User Pools ​

Any user pool that has been created outside of this stack, can be imported into the CDK app. Importing a user pool allows for it to be used in other parts of the CDK app that reference an IUserPool. However, imported user pools have limited configurability. As a rule of thumb, none of the properties that are part of the AWS::Cognito::UserPool CloudFormation resource can be configured.

User pools can be imported either using their id via the UserPool.fromUserPoolId(), or by using their ARN, via the UserPool.fromUserPoolArn() API.

ts
const awesomePool = cognito.UserPool.fromUserPoolId(this, 'awesome-user-pool', 'us-east-1_oiuR12Abd');

const otherAwesomePool = cognito.UserPool.fromUserPoolArn(this, 'other-awesome-user-pool',
  'arn:aws:cognito-idp:eu-west-1:123456789012:userpool/us-east-1_mtRyYQ14D');
python
awesome_pool = cognito.UserPool.from_user_pool_id(self, "awesome-user-pool", "us-east-1_oiuR12Abd")

other_awesome_pool = cognito.UserPool.from_user_pool_arn(self, "other-awesome-user-pool", "arn:aws:cognito-idp:eu-west-1:123456789012:userpool/us-east-1_mtRyYQ14D")
java
IUserPool awesomePool = UserPool.fromUserPoolId(this, "awesome-user-pool", "us-east-1_oiuR12Abd");

IUserPool otherAwesomePool = UserPool.fromUserPoolArn(this, "other-awesome-user-pool", "arn:aws:cognito-idp:eu-west-1:123456789012:userpool/us-east-1_mtRyYQ14D");
csharp
var awesomePool = UserPool.FromUserPoolId(this, "awesome-user-pool", "us-east-1_oiuR12Abd");

var otherAwesomePool = UserPool.FromUserPoolArn(this, "other-awesome-user-pool", "arn:aws:cognito-idp:eu-west-1:123456789012:userpool/us-east-1_mtRyYQ14D");
go
awesomePool := cognito.UserPool_FromUserPoolId(this, jsii.String("awesome-user-pool"), jsii.String("us-east-1_oiuR12Abd"))

otherAwesomePool := cognito.UserPool_FromUserPoolArn(this, jsii.String("other-awesome-user-pool"), jsii.String("arn:aws:cognito-idp:eu-west-1:123456789012:userpool/us-east-1_mtRyYQ14D"))

Identity Providers ​

Users that are part of a user pool can sign in either directly through a user pool, or federate through a third-party identity provider. Once configured, the Cognito backend will take care of integrating with the third-party provider. Read more about Adding User Pool Sign-in Through a Third Party.

The following third-party identity providers are currently supported in the CDK -

The following code configures a user pool to federate with the third party provider, 'Login with Amazon'. The identity provider needs to be configured with a set of credentials that the Cognito backend can use to federate with the third-party identity provider.

ts
const userpool = new cognito.UserPool(this, 'Pool');

const provider = new cognito.UserPoolIdentityProviderAmazon(this, 'Amazon', {
  clientId: 'amzn-client-id',
  clientSecret: 'amzn-client-secret',
  userPool: userpool,
});
python
userpool = cognito.UserPool(self, "Pool")

provider = cognito.UserPoolIdentityProviderAmazon(self, "Amazon",
    client_id="amzn-client-id",
    client_secret="amzn-client-secret",
    user_pool=userpool
)
java
UserPool userpool = new UserPool(this, "Pool");

UserPoolIdentityProviderAmazon provider = UserPoolIdentityProviderAmazon.Builder.create(this, "Amazon")
        .clientId("amzn-client-id")
        .clientSecret("amzn-client-secret")
        .userPool(userpool)
        .build();
csharp
var userpool = new UserPool(this, "Pool");

var provider = new UserPoolIdentityProviderAmazon(this, "Amazon", new UserPoolIdentityProviderAmazonProps {
    ClientId = "amzn-client-id",
    ClientSecret = "amzn-client-secret",
    UserPool = userpool
});
go
userpool := cognito.NewUserPool(this, jsii.String("Pool"))

provider := cognito.NewUserPoolIdentityProviderAmazon(this, jsii.String("Amazon"), &UserPoolIdentityProviderAmazonProps{
	ClientId: jsii.String("amzn-client-id"),
	ClientSecret: jsii.String("amzn-client-secret"),
	UserPool: userpool,
})

Using Google identity provider is possible to use clientSecretValue with SecretValue from secrets manager.

ts
const userpool = new cognito.UserPool(this, 'Pool');
const secret = secretsmanager.Secret.fromSecretAttributes(this, "CognitoClientSecret", {
    secretCompleteArn: "arn:aws:secretsmanager:xxx:xxx:secret:xxx-xxx"
}).secretValue

const provider = new cognito.UserPoolIdentityProviderGoogle(this, 'Google', {
  clientId: 'amzn-client-id',
  clientSecretValue: secret,
  userPool: userpool,
});
python
userpool = cognito.UserPool(self, "Pool")
secret = secretsmanager.Secret.from_secret_attributes(self, "CognitoClientSecret",
    secret_complete_arn="arn:aws:secretsmanager:xxx:xxx:secret:xxx-xxx"
).secret_value

provider = cognito.UserPoolIdentityProviderGoogle(self, "Google",
    client_id="amzn-client-id",
    client_secret_value=secret,
    user_pool=userpool
)
java
UserPool userpool = new UserPool(this, "Pool");
SecretValue secret = Secret.fromSecretAttributes(this, "CognitoClientSecret", SecretAttributes.builder()
        .secretCompleteArn("arn:aws:secretsmanager:xxx:xxx:secret:xxx-xxx")
        .build()).getSecretValue();

UserPoolIdentityProviderGoogle provider = UserPoolIdentityProviderGoogle.Builder.create(this, "Google")
        .clientId("amzn-client-id")
        .clientSecretValue(secret)
        .userPool(userpool)
        .build();
csharp
var userpool = new UserPool(this, "Pool");
var secret = Secret.FromSecretAttributes(this, "CognitoClientSecret", new SecretAttributes {
    SecretCompleteArn = "arn:aws:secretsmanager:xxx:xxx:secret:xxx-xxx"
}).SecretValue;

var provider = new UserPoolIdentityProviderGoogle(this, "Google", new UserPoolIdentityProviderGoogleProps {
    ClientId = "amzn-client-id",
    ClientSecretValue = secret,
    UserPool = userpool
});
go
userpool := cognito.NewUserPool(this, jsii.String("Pool"))
secret := secretsmanager.Secret_FromSecretAttributes(this, jsii.String("CognitoClientSecret"), &SecretAttributes{
	SecretCompleteArn: jsii.String("arn:aws:secretsmanager:xxx:xxx:secret:xxx-xxx"),
}).SecretValue

provider := cognito.NewUserPoolIdentityProviderGoogle(this, jsii.String("Google"), &UserPoolIdentityProviderGoogleProps{
	ClientId: jsii.String("amzn-client-id"),
	ClientSecretValue: secret,
	UserPool: userpool,
})

Using SAML identity provider is possible to use SAML metadata file content or SAML metadata file url.

ts
const userpool = new cognito.UserPool(this, 'Pool');

// specify the metadata as a file content
new cognito.UserPoolIdentityProviderSaml(this, 'userpoolIdpFile', {
  userPool: userpool,
  metadata: cognito.UserPoolIdentityProviderSamlMetadata.file('my-file-contents'),
  // Whether to require encrypted SAML assertions from IdP
  encryptedResponses: true,
  // The signing algorithm for the SAML requests
  requestSigningAlgorithm: cognito.SigningAlgorithm.RSA_SHA256,
  // Enable IdP initiated SAML auth flow
  idpInitiated: true,
});

// specify the metadata as a URL
new cognito.UserPoolIdentityProviderSaml(this, 'userpoolidpUrl', {
  userPool: userpool,
  metadata: cognito.UserPoolIdentityProviderSamlMetadata.url('https://my-metadata-url.com'),
});
python
userpool = cognito.UserPool(self, "Pool")

# specify the metadata as a file content
cognito.UserPoolIdentityProviderSaml(self, "userpoolIdpFile",
    user_pool=userpool,
    metadata=cognito.UserPoolIdentityProviderSamlMetadata.file("my-file-contents"),
    # Whether to require encrypted SAML assertions from IdP
    encrypted_responses=True,
    # The signing algorithm for the SAML requests
    request_signing_algorithm=cognito.SigningAlgorithm.RSA_SHA256,
    # Enable IdP initiated SAML auth flow
    idp_initiated=True
)

# specify the metadata as a URL
cognito.UserPoolIdentityProviderSaml(self, "userpoolidpUrl",
    user_pool=userpool,
    metadata=cognito.UserPoolIdentityProviderSamlMetadata.url("https://my-metadata-url.com")
)
java
UserPool userpool = new UserPool(this, "Pool");

// specify the metadata as a file content
// specify the metadata as a file content
UserPoolIdentityProviderSaml.Builder.create(this, "userpoolIdpFile")
        .userPool(userpool)
        .metadata(UserPoolIdentityProviderSamlMetadata.file("my-file-contents"))
        // Whether to require encrypted SAML assertions from IdP
        .encryptedResponses(true)
        // The signing algorithm for the SAML requests
        .requestSigningAlgorithm(SigningAlgorithm.RSA_SHA256)
        // Enable IdP initiated SAML auth flow
        .idpInitiated(true)
        .build();

// specify the metadata as a URL
// specify the metadata as a URL
UserPoolIdentityProviderSaml.Builder.create(this, "userpoolidpUrl")
        .userPool(userpool)
        .metadata(UserPoolIdentityProviderSamlMetadata.url("https://my-metadata-url.com"))
        .build();
csharp
var userpool = new UserPool(this, "Pool");

// specify the metadata as a file content
// specify the metadata as a file content
new UserPoolIdentityProviderSaml(this, "userpoolIdpFile", new UserPoolIdentityProviderSamlProps {
    UserPool = userpool,
    Metadata = UserPoolIdentityProviderSamlMetadata.File("my-file-contents"),
    // Whether to require encrypted SAML assertions from IdP
    EncryptedResponses = true,
    // The signing algorithm for the SAML requests
    RequestSigningAlgorithm = SigningAlgorithm.RSA_SHA256,
    // Enable IdP initiated SAML auth flow
    IdpInitiated = true
});

// specify the metadata as a URL
// specify the metadata as a URL
new UserPoolIdentityProviderSaml(this, "userpoolidpUrl", new UserPoolIdentityProviderSamlProps {
    UserPool = userpool,
    Metadata = UserPoolIdentityProviderSamlMetadata.Url("https://my-metadata-url.com")
});
go
userpool := cognito.NewUserPool(this, jsii.String("Pool"))

// specify the metadata as a file content
// specify the metadata as a file content
cognito.NewUserPoolIdentityProviderSaml(this, jsii.String("userpoolIdpFile"), &UserPoolIdentityProviderSamlProps{
	UserPool: userpool,
	Metadata: cognito.UserPoolIdentityProviderSamlMetadata_File(jsii.String("my-file-contents")),
	// Whether to require encrypted SAML assertions from IdP
	EncryptedResponses: jsii.Boolean(true),
	// The signing algorithm for the SAML requests
	RequestSigningAlgorithm: cognito.SigningAlgorithm_RSA_SHA256,
	// Enable IdP initiated SAML auth flow
	IdpInitiated: jsii.Boolean(true),
})

// specify the metadata as a URL
// specify the metadata as a URL
cognito.NewUserPoolIdentityProviderSaml(this, jsii.String("userpoolidpUrl"), &UserPoolIdentityProviderSamlProps{
	UserPool: userpool,
	Metadata: cognito.UserPoolIdentityProviderSamlMetadata_Url(jsii.String("https://my-metadata-url.com")),
})

Attribute mapping allows mapping attributes provided by the third-party identity providers to standard and custom attributes of the user pool. Learn more about Specifying Identity Provider Attribute Mappings for Your User Pool.

The following code shows how different attributes provided by 'Login With Amazon' can be mapped to standard and custom user pool attributes.

ts
const userpool = new cognito.UserPool(this, 'Pool');

new cognito.UserPoolIdentityProviderAmazon(this, 'Amazon', {
  clientId: 'amzn-client-id',
  clientSecret: 'amzn-client-secret',
  userPool: userpool,
  attributeMapping: {
    email: cognito.ProviderAttribute.AMAZON_EMAIL,
    website: cognito.ProviderAttribute.other('url'), // use other() when an attribute is not pre-defined in the CDK
    custom: {
      // custom user pool attributes go here
      uniqueId: cognito.ProviderAttribute.AMAZON_USER_ID,
    },
  },
});
python
userpool = cognito.UserPool(self, "Pool")

cognito.UserPoolIdentityProviderAmazon(self, "Amazon",
    client_id="amzn-client-id",
    client_secret="amzn-client-secret",
    user_pool=userpool,
    attribute_mapping=cognito.AttributeMapping(
        email=cognito.ProviderAttribute.AMAZON_EMAIL,
        website=cognito.ProviderAttribute.other("url"),  # use other() when an attribute is not pre-defined in the CDK
        custom={
            # custom user pool attributes go here
            "unique_id": cognito.ProviderAttribute.AMAZON_USER_ID
        }
    )
)
java
UserPool userpool = new UserPool(this, "Pool");

UserPoolIdentityProviderAmazon.Builder.create(this, "Amazon")
        .clientId("amzn-client-id")
        .clientSecret("amzn-client-secret")
        .userPool(userpool)
        .attributeMapping(AttributeMapping.builder()
                .email(ProviderAttribute.AMAZON_EMAIL)
                .website(ProviderAttribute.other("url")) // use other() when an attribute is not pre-defined in the CDK
                .custom(Map.of(
                        // custom user pool attributes go here
                        "uniqueId", ProviderAttribute.AMAZON_USER_ID))
                .build())
        .build();
csharp
var userpool = new UserPool(this, "Pool");

new UserPoolIdentityProviderAmazon(this, "Amazon", new UserPoolIdentityProviderAmazonProps {
    ClientId = "amzn-client-id",
    ClientSecret = "amzn-client-secret",
    UserPool = userpool,
    AttributeMapping = new AttributeMapping {
        Email = ProviderAttribute.AMAZON_EMAIL,
        Website = ProviderAttribute.Other("url"),  // use other() when an attribute is not pre-defined in the CDK
        Custom = new Dictionary<string, ProviderAttribute> {
            // custom user pool attributes go here
            { "uniqueId", ProviderAttribute.AMAZON_USER_ID }
        }
    }
});
go
userpool := cognito.NewUserPool(this, jsii.String("Pool"))

cognito.NewUserPoolIdentityProviderAmazon(this, jsii.String("Amazon"), &UserPoolIdentityProviderAmazonProps{
	ClientId: jsii.String("amzn-client-id"),
	ClientSecret: jsii.String("amzn-client-secret"),
	UserPool: userpool,
	AttributeMapping: &AttributeMapping{
		Email: cognito.ProviderAttribute_AMAZON_EMAIL(),
		Website: cognito.ProviderAttribute_Other(jsii.String("url")),
		 // use other() when an attribute is not pre-defined in the CDK
		Custom: map[string]ProviderAttribute{
			// custom user pool attributes go here
			"uniqueId": cognito.ProviderAttribute_AMAZON_USER_ID(),
		},
	},
})

App Clients ​

An app is an entity within a user pool that has permission to call unauthenticated APIs (APIs that do not have an authenticated user), such as APIs to register, sign in, and handle forgotten passwords. To call these APIs, you need an app client ID and an optional client secret. Read Configuring a User Pool App Client to learn more.

The following code creates an app client and retrieves the client id -

ts
const pool = new cognito.UserPool(this, 'pool');
const client = pool.addClient('customer-app-client');
const clientId = client.userPoolClientId;
python
pool = cognito.UserPool(self, "pool")
client = pool.add_client("customer-app-client")
client_id = client.user_pool_client_id
java
UserPool pool = new UserPool(this, "pool");
UserPoolClient client = pool.addClient("customer-app-client");
String clientId = client.getUserPoolClientId();
csharp
var pool = new UserPool(this, "pool");
var client = pool.AddClient("customer-app-client");
var clientId = client.UserPoolClientId;
go
pool := cognito.NewUserPool(this, jsii.String("pool"))
client := pool.addClient(jsii.String("customer-app-client"))
clientId := client.UserPoolClientId

Existing app clients can be imported into the CDK app using the UserPoolClient.fromUserPoolClientId() API. For new and imported user pools, clients can also be created via the UserPoolClient constructor, as so -

ts
const importedPool = cognito.UserPool.fromUserPoolId(this, 'imported-pool', 'us-east-1_oiuR12Abd');
new cognito.UserPoolClient(this, 'customer-app-client', {
  userPool: importedPool,
});
python
imported_pool = cognito.UserPool.from_user_pool_id(self, "imported-pool", "us-east-1_oiuR12Abd")
cognito.UserPoolClient(self, "customer-app-client",
    user_pool=imported_pool
)
java
IUserPool importedPool = UserPool.fromUserPoolId(this, "imported-pool", "us-east-1_oiuR12Abd");
UserPoolClient.Builder.create(this, "customer-app-client")
        .userPool(importedPool)
        .build();
csharp
var importedPool = UserPool.FromUserPoolId(this, "imported-pool", "us-east-1_oiuR12Abd");
new UserPoolClient(this, "customer-app-client", new UserPoolClientProps {
    UserPool = importedPool
});
go
importedPool := cognito.UserPool_FromUserPoolId(this, jsii.String("imported-pool"), jsii.String("us-east-1_oiuR12Abd"))
cognito.NewUserPoolClient(this, jsii.String("customer-app-client"), &UserPoolClientProps{
	UserPool: importedPool,
})

Clients can be configured with authentication flows. Authentication flows allow users on a client to be authenticated with a user pool. Cognito user pools provide several different types of authentication, such as, SRP (Secure Remote Password) authentication, username-and-password authentication, etc. Learn more about this at UserPool Authentication Flow.

The following code configures a client to use both SRP and username-and-password authentication -

ts
const pool = new cognito.UserPool(this, 'pool');
pool.addClient('app-client', {
  authFlows: {
    userPassword: true,
    userSrp: true,
  },
});
python
pool = cognito.UserPool(self, "pool")
pool.add_client("app-client",
    auth_flows=cognito.AuthFlow(
        user_password=True,
        user_srp=True
    )
)
java
UserPool pool = new UserPool(this, "pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        .authFlows(AuthFlow.builder()
                .userPassword(true)
                .userSrp(true)
                .build())
        .build());
csharp
var pool = new UserPool(this, "pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    AuthFlows = new AuthFlow {
        UserPassword = true,
        UserSrp = true
    }
});
go
pool := cognito.NewUserPool(this, jsii.String("pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	AuthFlows: &AuthFlow{
		UserPassword: jsii.Boolean(true),
		UserSrp: jsii.Boolean(true),
	},
})

Custom authentication protocols can be configured by setting the custom property under authFlow and defining lambda functions for the corresponding user pool triggers. Learn more at Custom Authentication Flow.

Choice-based authentication can be configured by setting the user property under authFlow. This enables the USER_AUTH authentication flow. Learn more at Choice-based authentication.

In addition to these authentication mechanisms, Cognito user pools also support using OAuth 2.0 framework for authenticating users. User pool clients can be configured with OAuth 2.0 authorization flows and scopes. Learn more about the OAuth 2.0 authorization framework and Cognito user pool's implementation of OAuth2.0.

The following code configures an app client with the authorization code grant flow and registers the app's welcome page as a callback (or redirect) URL. It also configures the access token scope to 'openid'. All of these concepts can be found in the OAuth 2.0 RFC.

ts
const pool = new cognito.UserPool(this, 'Pool');
pool.addClient('app-client', {
  oAuth: {
    flows: {
      authorizationCodeGrant: true,
    },
    scopes: [ cognito.OAuthScope.OPENID ],
    callbackUrls: [ 'https://my-app-domain.com/welcome' ],
    logoutUrls: [ 'https://my-app-domain.com/signin' ],
  },
});
python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    o_auth=cognito.OAuthSettings(
        flows=cognito.OAuthFlows(
            authorization_code_grant=True
        ),
        scopes=[cognito.OAuthScope.OPENID],
        callback_urls=["https://my-app-domain.com/welcome"],
        logout_urls=["https://my-app-domain.com/signin"]
    )
)
java
UserPool pool = new UserPool(this, "Pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        .oAuth(OAuthSettings.builder()
                .flows(OAuthFlows.builder()
                        .authorizationCodeGrant(true)
                        .build())
                .scopes(List.of(OAuthScope.OPENID))
                .callbackUrls(List.of("https://my-app-domain.com/welcome"))
                .logoutUrls(List.of("https://my-app-domain.com/signin"))
                .build())
        .build());
csharp
var pool = new UserPool(this, "Pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    OAuth = new OAuthSettings {
        Flows = new OAuthFlows {
            AuthorizationCodeGrant = true
        },
        Scopes = new [] { OAuthScope.OPENID },
        CallbackUrls = new [] { "https://my-app-domain.com/welcome" },
        LogoutUrls = new [] { "https://my-app-domain.com/signin" }
    }
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	OAuth: &OAuthSettings{
		Flows: &OAuthFlows{
			AuthorizationCodeGrant: jsii.Boolean(true),
		},
		Scopes: []OAuthScope{
			cognito.OAuthScope_OPENID(),
		},
		CallbackUrls: []*string{
			jsii.String("https://my-app-domain.com/welcome"),
		},
		LogoutUrls: []*string{
			jsii.String("https://my-app-domain.com/signin"),
		},
	},
})

To set a default redirect URI, use the defaultRedirectUri property. Its value must be present in the callbackUrls list.

ts
const pool = new cognito.UserPool(this, 'Pool');
pool.addClient('app-client', {
  oAuth: {
    flows: {
      authorizationCodeGrant: true,
    },
    scopes: [ cognito.OAuthScope.OPENID ],
    defaultRedirectUri: 'https://my-app-domain.com/welcome',
    callbackUrls: [ 'https://my-app-domain.com/welcome', 'https://my-app-domain.com/hello' ],
    logoutUrls: [ 'https://my-app-domain.com/signin' ],
  },
});
python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    o_auth=cognito.OAuthSettings(
        flows=cognito.OAuthFlows(
            authorization_code_grant=True
        ),
        scopes=[cognito.OAuthScope.OPENID],
        default_redirect_uri="https://my-app-domain.com/welcome",
        callback_urls=["https://my-app-domain.com/welcome", "https://my-app-domain.com/hello"],
        logout_urls=["https://my-app-domain.com/signin"]
    )
)
java
UserPool pool = new UserPool(this, "Pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        .oAuth(OAuthSettings.builder()
                .flows(OAuthFlows.builder()
                        .authorizationCodeGrant(true)
                        .build())
                .scopes(List.of(OAuthScope.OPENID))
                .defaultRedirectUri("https://my-app-domain.com/welcome")
                .callbackUrls(List.of("https://my-app-domain.com/welcome", "https://my-app-domain.com/hello"))
                .logoutUrls(List.of("https://my-app-domain.com/signin"))
                .build())
        .build());
csharp
var pool = new UserPool(this, "Pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    OAuth = new OAuthSettings {
        Flows = new OAuthFlows {
            AuthorizationCodeGrant = true
        },
        Scopes = new [] { OAuthScope.OPENID },
        DefaultRedirectUri = "https://my-app-domain.com/welcome",
        CallbackUrls = new [] { "https://my-app-domain.com/welcome", "https://my-app-domain.com/hello" },
        LogoutUrls = new [] { "https://my-app-domain.com/signin" }
    }
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	OAuth: &OAuthSettings{
		Flows: &OAuthFlows{
			AuthorizationCodeGrant: jsii.Boolean(true),
		},
		Scopes: []OAuthScope{
			cognito.OAuthScope_OPENID(),
		},
		DefaultRedirectUri: jsii.String("https://my-app-domain.com/welcome"),
		CallbackUrls: []*string{
			jsii.String("https://my-app-domain.com/welcome"),
			jsii.String("https://my-app-domain.com/hello"),
		},
		LogoutUrls: []*string{
			jsii.String("https://my-app-domain.com/signin"),
		},
	},
})

An app client can be configured to prevent user existence errors. This instructs the Cognito authentication API to return generic authentication failure responses instead of an UserNotFoundException. By default, the flag is not set, which means the CloudFormation default (false) will be used. See the documentation for the full details on the behavior of this flag.

ts
const pool = new cognito.UserPool(this, 'Pool');
pool.addClient('app-client', {
  preventUserExistenceErrors: true,
});
python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    prevent_user_existence_errors=True
)
java
UserPool pool = new UserPool(this, "Pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        .preventUserExistenceErrors(true)
        .build());
csharp
var pool = new UserPool(this, "Pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    PreventUserExistenceErrors = true
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	PreventUserExistenceErrors: jsii.Boolean(true),
})

All identity providers created in the CDK app are automatically registered into the corresponding user pool. All app clients created in the CDK have all of the identity providers enabled by default. The 'Cognito' identity provider, that allows users to register and sign in directly with the Cognito user pool, is also enabled by default. Alternatively, the list of supported identity providers for a client can be explicitly specified -

ts
const pool = new cognito.UserPool(this, 'Pool');
pool.addClient('app-client', {
  // ...
  supportedIdentityProviders: [
    cognito.UserPoolClientIdentityProvider.AMAZON,
    cognito.UserPoolClientIdentityProvider.COGNITO,
  ],
});
python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    # ...
    supported_identity_providers=[cognito.UserPoolClientIdentityProvider.AMAZON, cognito.UserPoolClientIdentityProvider.COGNITO
    ]
)
java
UserPool pool = new UserPool(this, "Pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        // ...
        .supportedIdentityProviders(List.of(UserPoolClientIdentityProvider.AMAZON, UserPoolClientIdentityProvider.COGNITO))
        .build());
csharp
var pool = new UserPool(this, "Pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    // ...
    SupportedIdentityProviders = new [] { UserPoolClientIdentityProvider.AMAZON, UserPoolClientIdentityProvider.COGNITO }
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	// ...
	SupportedIdentityProviders: []UserPoolClientIdentityProvider{
		cognito.UserPoolClientIdentityProvider_AMAZON(),
		cognito.UserPoolClientIdentityProvider_COGNITO(),
	},
})

If the identity provider and the app client are created in the same stack, specify the dependency between both constructs to make sure that the identity provider already exists when the app client will be created. The app client cannot handle the dependency to the identity provider automatically because the client does not have access to the provider's construct.

ts
const pool = new cognito.UserPool(this, 'Pool');
const provider = new cognito.UserPoolIdentityProviderAmazon(this, 'Amazon', {
  userPool: pool,
  clientId: 'amzn-client-id',
  clientSecret: 'amzn-client-secret',
});

const client = pool.addClient('app-client', {
  // ...
  supportedIdentityProviders: [
    cognito.UserPoolClientIdentityProvider.AMAZON,
  ],
});

client.node.addDependency(provider);
python
pool = cognito.UserPool(self, "Pool")
provider = cognito.UserPoolIdentityProviderAmazon(self, "Amazon",
    user_pool=pool,
    client_id="amzn-client-id",
    client_secret="amzn-client-secret"
)

client = pool.add_client("app-client",
    # ...
    supported_identity_providers=[cognito.UserPoolClientIdentityProvider.AMAZON
    ]
)

client.node.add_dependency(provider)
java
UserPool pool = new UserPool(this, "Pool");
UserPoolIdentityProviderAmazon provider = UserPoolIdentityProviderAmazon.Builder.create(this, "Amazon")
        .userPool(pool)
        .clientId("amzn-client-id")
        .clientSecret("amzn-client-secret")
        .build();

UserPoolClient client = pool.addClient("app-client", UserPoolClientOptions.builder()
        // ...
        .supportedIdentityProviders(List.of(UserPoolClientIdentityProvider.AMAZON))
        .build());

client.node.addDependency(provider);
csharp
var pool = new UserPool(this, "Pool");
var provider = new UserPoolIdentityProviderAmazon(this, "Amazon", new UserPoolIdentityProviderAmazonProps {
    UserPool = pool,
    ClientId = "amzn-client-id",
    ClientSecret = "amzn-client-secret"
});

var client = pool.AddClient("app-client", new UserPoolClientOptions {
    // ...
    SupportedIdentityProviders = new [] { UserPoolClientIdentityProvider.AMAZON }
});

client.Node.AddDependency(provider);
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
provider := cognito.NewUserPoolIdentityProviderAmazon(this, jsii.String("Amazon"), &UserPoolIdentityProviderAmazonProps{
	UserPool: pool,
	ClientId: jsii.String("amzn-client-id"),
	ClientSecret: jsii.String("amzn-client-secret"),
})

client := pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	// ...
	SupportedIdentityProviders: []UserPoolClientIdentityProvider{
		cognito.UserPoolClientIdentityProvider_AMAZON(),
	},
})

client.Node.AddDependency(provider)

The property authSessionValidity is the session token for each API request in the authentication flow. Valid duration is from 3 to 15 minutes.

ts
const pool = new cognito.UserPool(this, 'Pool');
pool.addClient('app-client', {
  // ...
  authSessionValidity: Duration.minutes(15),
});
python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    # ...
    auth_session_validity=Duration.minutes(15)
)
java
UserPool pool = new UserPool(this, "Pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        // ...
        .authSessionValidity(Duration.minutes(15))
        .build());
csharp
var pool = new UserPool(this, "Pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    // ...
    AuthSessionValidity = Duration.Minutes(15)
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	// ...
	AuthSessionValidity: awscdk.Duration_Minutes(jsii.Number(15)),
})

In accordance with the OIDC open standard, Cognito user pool clients provide access tokens, ID tokens and refresh tokens. More information is available at Using Tokens with User Pools. The expiration time for these tokens can be configured as shown below.

ts
const pool = new cognito.UserPool(this, 'Pool');
pool.addClient('app-client', {
  // ...
  accessTokenValidity: Duration.minutes(60),
  idTokenValidity: Duration.minutes(60),
  refreshTokenValidity: Duration.days(30),
});
python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    # ...
    access_token_validity=Duration.minutes(60),
    id_token_validity=Duration.minutes(60),
    refresh_token_validity=Duration.days(30)
)
java
UserPool pool = new UserPool(this, "Pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        // ...
        .accessTokenValidity(Duration.minutes(60))
        .idTokenValidity(Duration.minutes(60))
        .refreshTokenValidity(Duration.days(30))
        .build());
csharp
var pool = new UserPool(this, "Pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    // ...
    AccessTokenValidity = Duration.Minutes(60),
    IdTokenValidity = Duration.Minutes(60),
    RefreshTokenValidity = Duration.Days(30)
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	// ...
	AccessTokenValidity: awscdk.Duration_Minutes(jsii.Number(60)),
	IdTokenValidity: awscdk.Duration_*Minutes(jsii.Number(60)),
	RefreshTokenValidity: awscdk.Duration_Days(jsii.Number(30)),
})

Clients can (and should) be allowed to read and write relevant user attributes only. Usually every client can be allowed to read the given_name attribute but not every client should be allowed to set the email_verified attribute. The same criteria applies for both standard and custom attributes, more info is available at Attribute Permissions and Scopes. The default behaviour is to allow read and write permissions on all attributes. The following code shows how this can be configured for a client.

ts
const pool = new cognito.UserPool(this, 'Pool');

const clientWriteAttributes = (new cognito.ClientAttributes())
  .withStandardAttributes({fullname: true, email: true})
  .withCustomAttributes('favoritePizza', 'favoriteBeverage');

const clientReadAttributes = clientWriteAttributes
  .withStandardAttributes({emailVerified: true})
  .withCustomAttributes('pointsEarned');

pool.addClient('app-client', {
  // ...
  readAttributes: clientReadAttributes,
  writeAttributes: clientWriteAttributes,
});
python
pool = cognito.UserPool(self, "Pool")

client_write_attributes = (cognito.ClientAttributes()).with_standard_attributes(fullname=True, email=True).with_custom_attributes("favoritePizza", "favoriteBeverage")

client_read_attributes = client_write_attributes.with_standard_attributes(email_verified=True).with_custom_attributes("pointsEarned")

pool.add_client("app-client",
    # ...
    read_attributes=client_read_attributes,
    write_attributes=client_write_attributes
)
java
UserPool pool = new UserPool(this, "Pool");

ClientAttributes clientWriteAttributes = (new ClientAttributes()).withStandardAttributes(StandardAttributesMask.builder().fullname(true).email(true).build()).withCustomAttributes("favoritePizza", "favoriteBeverage");

ClientAttributes clientReadAttributes = clientWriteAttributes.withStandardAttributes(StandardAttributesMask.builder().emailVerified(true).build()).withCustomAttributes("pointsEarned");

pool.addClient("app-client", UserPoolClientOptions.builder()
        // ...
        .readAttributes(clientReadAttributes)
        .writeAttributes(clientWriteAttributes)
        .build());
csharp
var pool = new UserPool(this, "Pool");

var clientWriteAttributes = (new ClientAttributes()).WithStandardAttributes(new StandardAttributesMask { Fullname = true, Email = true }).WithCustomAttributes("favoritePizza", "favoriteBeverage");

var clientReadAttributes = clientWriteAttributes.WithStandardAttributes(new StandardAttributesMask { EmailVerified = true }).WithCustomAttributes("pointsEarned");

pool.AddClient("app-client", new UserPoolClientOptions {
    // ...
    ReadAttributes = clientReadAttributes,
    WriteAttributes = clientWriteAttributes
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))

clientWriteAttributes := (cognito.NewClientAttributes()).WithStandardAttributes(&StandardAttributesMask{
	Fullname: jsii.Boolean(true),
	Email: jsii.Boolean(true),
}).WithCustomAttributes(jsii.String("favoritePizza"), jsii.String("favoriteBeverage"))

clientReadAttributes := clientWriteAttributes.WithStandardAttributes(&StandardAttributesMask{
	EmailVerified: jsii.Boolean(true),
}).WithCustomAttributes(jsii.String("pointsEarned"))

pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	// ...
	ReadAttributes: clientReadAttributes,
	WriteAttributes: clientWriteAttributes,
})

Token revocation can be configured to be able to revoke refresh tokens in app clients. By default, token revocation is enabled for new user pools. The property can be used to enable the token revocation in existing app clients or to change the default behavior.

ts
const pool = new cognito.UserPool(this, 'Pool');
pool.addClient('app-client', {
  // ...
  enableTokenRevocation: true,
});
python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    # ...
    enable_token_revocation=True
)
java
UserPool pool = new UserPool(this, "Pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        // ...
        .enableTokenRevocation(true)
        .build());
csharp
var pool = new UserPool(this, "Pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    // ...
    EnableTokenRevocation = true
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	// ...
	EnableTokenRevocation: jsii.Boolean(true),
})

User Pool clients can generate a client ID as well as a client secret, to support more advanced authentication workflows.

To create a client with an autogenerated client secret, pass the generateSecret: true prop:

ts
declare const importedPool: cognito.UserPool;

const userPoolClient = new cognito.UserPoolClient(this, 'UserPoolClient', {
  userPool: importedPool,
  generateSecret: true,
});

// Allows you to pass the generated secret to other pieces of infrastructure
const secret = userPoolClient.userPoolClientSecret;
python
# imported_pool: cognito.UserPool


user_pool_client = cognito.UserPoolClient(self, "UserPoolClient",
    user_pool=imported_pool,
    generate_secret=True
)

# Allows you to pass the generated secret to other pieces of infrastructure
secret = user_pool_client.user_pool_client_secret
java
UserPool importedPool;


UserPoolClient userPoolClient = UserPoolClient.Builder.create(this, "UserPoolClient")
        .userPool(importedPool)
        .generateSecret(true)
        .build();

// Allows you to pass the generated secret to other pieces of infrastructure
SecretValue secret = userPoolClient.getUserPoolClientSecret();
csharp
UserPool importedPool;


var userPoolClient = new UserPoolClient(this, "UserPoolClient", new UserPoolClientProps {
    UserPool = importedPool,
    GenerateSecret = true
});

// Allows you to pass the generated secret to other pieces of infrastructure
var secret = userPoolClient.UserPoolClientSecret;
go
var importedPool UserPool


userPoolClient := cognito.NewUserPoolClient(this, jsii.String("UserPoolClient"), &UserPoolClientProps{
	UserPool: importedPool,
	GenerateSecret: jsii.Boolean(true),
})

// Allows you to pass the generated secret to other pieces of infrastructure
secret := userPoolClient.userPoolClientSecret

If you set enablePropagateAdditionalUserContextData: true, you can collect and pass information about your user's session to Amazon Cognito advanced security when you use the API to sign them up, sign them in, and reset their password.

ts
declare const importedPool: cognito.UserPool;

const userPoolClient = new cognito.UserPoolClient(this, 'UserPoolClient', {
  userPool: importedPool,
  generateSecret: true,
  enablePropagateAdditionalUserContextData: true,
});
python
# imported_pool: cognito.UserPool


user_pool_client = cognito.UserPoolClient(self, "UserPoolClient",
    user_pool=imported_pool,
    generate_secret=True,
    enable_propagate_additional_user_context_data=True
)
java
UserPool importedPool;


UserPoolClient userPoolClient = UserPoolClient.Builder.create(this, "UserPoolClient")
        .userPool(importedPool)
        .generateSecret(true)
        .enablePropagateAdditionalUserContextData(true)
        .build();
csharp
UserPool importedPool;


var userPoolClient = new UserPoolClient(this, "UserPoolClient", new UserPoolClientProps {
    UserPool = importedPool,
    GenerateSecret = true,
    EnablePropagateAdditionalUserContextData = true
});
go
var importedPool UserPool


userPoolClient := cognito.NewUserPoolClient(this, jsii.String("UserPoolClient"), &UserPoolClientProps{
	UserPool: importedPool,
	GenerateSecret: jsii.Boolean(true),
	EnablePropagateAdditionalUserContextData: jsii.Boolean(true),
})

Refresh token rotation can be configured to enable automatic rotation of refresh tokens. By default, refresh token rotation is disabled. When the refreshTokenRotationGracePeriod is 0, the grace period is disabled and a successful request immediately invalidates the submitted refresh token.

ts
const pool = new cognito.UserPool(this, 'Pool');
pool.addClient('app-client', {
  // ...
  refreshTokenRotationGracePeriod: Duration.seconds(40)
});
python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    # ...
    refresh_token_rotation_grace_period=Duration.seconds(40)
)
java
UserPool pool = new UserPool(this, "Pool");
pool.addClient("app-client", UserPoolClientOptions.builder()
        // ...
        .refreshTokenRotationGracePeriod(Duration.seconds(40))
        .build());
csharp
var pool = new UserPool(this, "Pool");
pool.AddClient("app-client", new UserPoolClientOptions {
    // ...
    RefreshTokenRotationGracePeriod = Duration.Seconds(40)
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))
pool.addClient(jsii.String("app-client"), &UserPoolClientOptions{
	// ...
	RefreshTokenRotationGracePeriod: awscdk.Duration_Seconds(jsii.Number(40)),
})

See Adding user device and session data to API requests for more information.

Resource Servers ​

A resource server is a server for access-protected resources. It handles authenticated requests from an app that has an access token. See Defining Resource Servers for more information.

An application may choose to model custom permissions via OAuth. Resource Servers provide this capability via custom scopes that are attached to an app client. The following example sets up a resource server for the 'users' resource for two different app clients and configures the clients to use these scopes.

ts
const pool = new cognito.UserPool(this, 'Pool');

const readOnlyScope = new cognito.ResourceServerScope({ scopeName: 'read', scopeDescription: 'Read-only access' });
const fullAccessScope = new cognito.ResourceServerScope({ scopeName: '*', scopeDescription: 'Full access' });

const userServer = pool.addResourceServer('ResourceServer', {
  identifier: 'users',
  scopes: [ readOnlyScope, fullAccessScope ],
});

const readOnlyClient = pool.addClient('read-only-client', {
  // ...
  oAuth: {
    // ...
    scopes: [ cognito.OAuthScope.resourceServer(userServer, readOnlyScope) ],
  },
});

const fullAccessClient = pool.addClient('full-access-client', {
  // ...
  oAuth: {
    // ...
    scopes: [ cognito.OAuthScope.resourceServer(userServer, fullAccessScope) ],
  },
});
python
pool = cognito.UserPool(self, "Pool")

read_only_scope = cognito.ResourceServerScope(scope_name="read", scope_description="Read-only access")
full_access_scope = cognito.ResourceServerScope(scope_name="*", scope_description="Full access")

user_server = pool.add_resource_server("ResourceServer",
    identifier="users",
    scopes=[read_only_scope, full_access_scope]
)

read_only_client = pool.add_client("read-only-client",
    # ...
    o_auth=cognito.OAuthSettings(
        # ...
        scopes=[cognito.OAuthScope.resource_server(user_server, read_only_scope)]
    )
)

full_access_client = pool.add_client("full-access-client",
    # ...
    o_auth=cognito.OAuthSettings(
        # ...
        scopes=[cognito.OAuthScope.resource_server(user_server, full_access_scope)]
    )
)
java
UserPool pool = new UserPool(this, "Pool");

ResourceServerScope readOnlyScope = ResourceServerScope.Builder.create().scopeName("read").scopeDescription("Read-only access").build();
ResourceServerScope fullAccessScope = ResourceServerScope.Builder.create().scopeName("*").scopeDescription("Full access").build();

UserPoolResourceServer userServer = pool.addResourceServer("ResourceServer", UserPoolResourceServerOptions.builder()
        .identifier("users")
        .scopes(List.of(readOnlyScope, fullAccessScope))
        .build());

UserPoolClient readOnlyClient = pool.addClient("read-only-client", UserPoolClientOptions.builder()
        // ...
        .oAuth(OAuthSettings.builder()
                // ...
                .scopes(List.of(OAuthScope.resourceServer(userServer, readOnlyScope)))
                .build())
        .build());

UserPoolClient fullAccessClient = pool.addClient("full-access-client", UserPoolClientOptions.builder()
        // ...
        .oAuth(OAuthSettings.builder()
                // ...
                .scopes(List.of(OAuthScope.resourceServer(userServer, fullAccessScope)))
                .build())
        .build());
csharp
var pool = new UserPool(this, "Pool");

var readOnlyScope = new ResourceServerScope(new ResourceServerScopeProps { ScopeName = "read", ScopeDescription = "Read-only access" });
var fullAccessScope = new ResourceServerScope(new ResourceServerScopeProps { ScopeName = "*", ScopeDescription = "Full access" });

var userServer = pool.AddResourceServer("ResourceServer", new UserPoolResourceServerOptions {
    Identifier = "users",
    Scopes = new [] { readOnlyScope, fullAccessScope }
});

var readOnlyClient = pool.AddClient("read-only-client", new UserPoolClientOptions {
    // ...
    OAuth = new OAuthSettings {
        // ...
        Scopes = new [] { OAuthScope.ResourceServer(userServer, readOnlyScope) }
    }
});

var fullAccessClient = pool.AddClient("full-access-client", new UserPoolClientOptions {
    // ...
    OAuth = new OAuthSettings {
        // ...
        Scopes = new [] { OAuthScope.ResourceServer(userServer, fullAccessScope) }
    }
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))

readOnlyScope := cognito.NewResourceServerScope(&ResourceServerScopeProps{
	ScopeName: jsii.String("read"),
	ScopeDescription: jsii.String("Read-only access"),
})
fullAccessScope := cognito.NewResourceServerScope(&ResourceServerScopeProps{
	ScopeName: jsii.String("*"),
	ScopeDescription: jsii.String("Full access"),
})

userServer := pool.addResourceServer(jsii.String("ResourceServer"), &UserPoolResourceServerOptions{
	Identifier: jsii.String("users"),
	Scopes: []ResourceServerScope{
		readOnlyScope,
		fullAccessScope,
	},
})

readOnlyClient := pool.addClient(jsii.String("read-only-client"), &UserPoolClientOptions{
	// ...
	OAuth: &OAuthSettings{
		// ...
		Scopes: []OAuthScope{
			cognito.OAuthScope_ResourceServer(userServer, readOnlyScope),
		},
	},
})

fullAccessClient := pool.addClient(jsii.String("full-access-client"), &UserPoolClientOptions{
	// ...
	OAuth: &OAuthSettings{
		// ...
		Scopes: []OAuthScope{
			cognito.OAuthScope_*ResourceServer(userServer, fullAccessScope),
		},
	},
})

Domains ​

After setting up an app client, the address for the user pool's sign-up and sign-in webpages can be configured using domains. There are two ways to set up a domain - either the Amazon Cognito hosted domain can be chosen with an available domain prefix, or a custom domain name can be chosen. The custom domain must be one that is already owned, and whose certificate is registered in AWS Certificate Manager.

The following code sets up a user pool domain in Amazon Cognito hosted domain with the prefix 'my-awesome-app', and another domain with the custom domain 'user.myapp.com' -

ts
const pool = new cognito.UserPool(this, 'Pool');

pool.addDomain('CognitoDomain', {
  cognitoDomain: {
    domainPrefix: 'my-awesome-app',
  },
});

const certificateArn = 'arn:aws:acm:us-east-1:123456789012:certificate/11-3336f1-44483d-adc7-9cd375c5169d';

const domainCert = certificatemanager.Certificate.fromCertificateArn(this, 'domainCert', certificateArn);
pool.addDomain('CustomDomain', {
  customDomain: {
    domainName: 'user.myapp.com',
    certificate: domainCert,
  },
});
python
pool = cognito.UserPool(self, "Pool")

pool.add_domain("CognitoDomain",
    cognito_domain=cognito.CognitoDomainOptions(
        domain_prefix="my-awesome-app"
    )
)

certificate_arn = "arn:aws:acm:us-east-1:123456789012:certificate/11-3336f1-44483d-adc7-9cd375c5169d"

domain_cert = certificatemanager.Certificate.from_certificate_arn(self, "domainCert", certificate_arn)
pool.add_domain("CustomDomain",
    custom_domain=cognito.CustomDomainOptions(
        domain_name="user.myapp.com",
        certificate=domain_cert
    )
)
java
UserPool pool = new UserPool(this, "Pool");

pool.addDomain("CognitoDomain", UserPoolDomainOptions.builder()
        .cognitoDomain(CognitoDomainOptions.builder()
                .domainPrefix("my-awesome-app")
                .build())
        .build());

String certificateArn = "arn:aws:acm:us-east-1:123456789012:certificate/11-3336f1-44483d-adc7-9cd375c5169d";

ICertificate domainCert = Certificate.fromCertificateArn(this, "domainCert", certificateArn);
pool.addDomain("CustomDomain", UserPoolDomainOptions.builder()
        .customDomain(CustomDomainOptions.builder()
                .domainName("user.myapp.com")
                .certificate(domainCert)
                .build())
        .build());
csharp
var pool = new UserPool(this, "Pool");

pool.AddDomain("CognitoDomain", new UserPoolDomainOptions {
    CognitoDomain = new CognitoDomainOptions {
        DomainPrefix = "my-awesome-app"
    }
});

var certificateArn = "arn:aws:acm:us-east-1:123456789012:certificate/11-3336f1-44483d-adc7-9cd375c5169d";

var domainCert = Certificate.FromCertificateArn(this, "domainCert", certificateArn);
pool.AddDomain("CustomDomain", new UserPoolDomainOptions {
    CustomDomain = new CustomDomainOptions {
        DomainName = "user.myapp.com",
        Certificate = domainCert
    }
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))

pool.addDomain(jsii.String("CognitoDomain"), &UserPoolDomainOptions{
	CognitoDomain: &CognitoDomainOptions{
		DomainPrefix: jsii.String("my-awesome-app"),
	},
})

certificateArn := "arn:aws:acm:us-east-1:123456789012:certificate/11-3336f1-44483d-adc7-9cd375c5169d"

domainCert := certificatemanager.Certificate_FromCertificateArn(this, jsii.String("domainCert"), certificateArn)
pool.addDomain(jsii.String("CustomDomain"), &UserPoolDomainOptions{
	CustomDomain: &CustomDomainOptions{
		DomainName: jsii.String("user.myapp.com"),
		Certificate: domainCert,
	},
})

Read more about Using the Amazon Cognito Domain and Using Your Own Domain.

You can use the managed login page provided by Amazon Cognito to sign in users. The managed login page has two versions: a classic version and a new version. You can switch between the two versions by using the managedLoginVersion property.

ts
const pool = new cognito.UserPool(this, 'Pool');

// Use the new managed login page
pool.addDomain('CognitoDomainWithBlandingDesignManagedLogin', {
  cognitoDomain: {
    domainPrefix: 'blanding-design-ui',
  },
  managedLoginVersion: cognito.ManagedLoginVersion.NEWER_MANAGED_LOGIN,
});

// Use the classic hosted UI
pool.addDomain('DomainWithClassicHostedUi', {
  cognitoDomain: {
    domainPrefix: 'classic-hosted-ui',
  },
  managedLoginVersion: cognito.ManagedLoginVersion.CLASSIC_HOSTED_UI,
});
python
pool = cognito.UserPool(self, "Pool")

# Use the new managed login page
pool.add_domain("CognitoDomainWithBlandingDesignManagedLogin",
    cognito_domain=cognito.CognitoDomainOptions(
        domain_prefix="blanding-design-ui"
    ),
    managed_login_version=cognito.ManagedLoginVersion.NEWER_MANAGED_LOGIN
)

# Use the classic hosted UI
pool.add_domain("DomainWithClassicHostedUi",
    cognito_domain=cognito.CognitoDomainOptions(
        domain_prefix="classic-hosted-ui"
    ),
    managed_login_version=cognito.ManagedLoginVersion.CLASSIC_HOSTED_UI
)
java
UserPool pool = new UserPool(this, "Pool");

// Use the new managed login page
pool.addDomain("CognitoDomainWithBlandingDesignManagedLogin", UserPoolDomainOptions.builder()
        .cognitoDomain(CognitoDomainOptions.builder()
                .domainPrefix("blanding-design-ui")
                .build())
        .managedLoginVersion(ManagedLoginVersion.NEWER_MANAGED_LOGIN)
        .build());

// Use the classic hosted UI
pool.addDomain("DomainWithClassicHostedUi", UserPoolDomainOptions.builder()
        .cognitoDomain(CognitoDomainOptions.builder()
                .domainPrefix("classic-hosted-ui")
                .build())
        .managedLoginVersion(ManagedLoginVersion.CLASSIC_HOSTED_UI)
        .build());
csharp
var pool = new UserPool(this, "Pool");

// Use the new managed login page
pool.AddDomain("CognitoDomainWithBlandingDesignManagedLogin", new UserPoolDomainOptions {
    CognitoDomain = new CognitoDomainOptions {
        DomainPrefix = "blanding-design-ui"
    },
    ManagedLoginVersion = ManagedLoginVersion.NEWER_MANAGED_LOGIN
});

// Use the classic hosted UI
pool.AddDomain("DomainWithClassicHostedUi", new UserPoolDomainOptions {
    CognitoDomain = new CognitoDomainOptions {
        DomainPrefix = "classic-hosted-ui"
    },
    ManagedLoginVersion = ManagedLoginVersion.CLASSIC_HOSTED_UI
});
go
pool := cognito.NewUserPool(this, jsii.String("Pool"))

// Use the new managed login page
pool.addDomain(jsii.String("CognitoDomainWithBlandingDesignManagedLogin"), &UserPoolDomainOptions{
	CognitoDomain: &CognitoDomainOptions{
		DomainPrefix: jsii.String("blanding-design-ui"),
	},
	ManagedLoginVersion: cognito.ManagedLoginVersion_NEWER_MANAGED_LOGIN,
})

// Use the classic hosted UI
pool.addDomain(jsii.String("DomainWithClassicHostedUi"), &UserPoolDomainOptions{
	CognitoDomain: &CognitoDomainOptions{
		DomainPrefix: jsii.String("classic-hosted-ui"),
	},
	ManagedLoginVersion: cognito.ManagedLoginVersion_CLASSIC_HOSTED_UI,
})

The signInUrl() methods returns the fully qualified URL to the login page for the user pool. This page comes from the hosted UI configured with Cognito. Learn more at Hosted UI with the Amazon Cognito Console.

ts
const userpool = new cognito.UserPool(this, 'UserPool', {
  // ...
});
const client = userpool.addClient('Client', {
  // ...
  oAuth: {
    flows: {
      implicitCodeGrant: true,
    },
    callbackUrls: [
      'https://myapp.com/home',
      'https://myapp.com/users',
    ],
  },
});
const domain = userpool.addDomain('Domain', {
  // ...
});
const signInUrl = domain.signInUrl(client, {
  redirectUri: 'https://myapp.com/home', // must be a URL configured under 'callbackUrls' with the client
});
python
userpool = cognito.UserPool(self, "UserPool")
client = userpool.add_client("Client",
    # ...
    o_auth=cognito.OAuthSettings(
        flows=cognito.OAuthFlows(
            implicit_code_grant=True
        ),
        callback_urls=["https://myapp.com/home", "https://myapp.com/users"
        ]
    )
)
domain = userpool.add_domain("Domain")
sign_in_url = domain.sign_in_url(client,
    redirect_uri="https://myapp.com/home"
)
java
UserPool userpool = UserPool.Builder.create(this, "UserPool").build();
UserPoolClient client = userpool.addClient("Client", UserPoolClientOptions.builder()
        // ...
        .oAuth(OAuthSettings.builder()
                .flows(OAuthFlows.builder()
                        .implicitCodeGrant(true)
                        .build())
                .callbackUrls(List.of("https://myapp.com/home", "https://myapp.com/users"))
                .build())
        .build());
UserPoolDomain domain = userpool.addDomain("Domain", UserPoolDomainOptions.builder().build());
String signInUrl = domain.signInUrl(client, SignInUrlOptions.builder()
        .redirectUri("https://myapp.com/home")
        .build());
csharp
var userpool = new UserPool(this, "UserPool", new UserPoolProps { });
var client = userpool.AddClient("Client", new UserPoolClientOptions {
    // ...
    OAuth = new OAuthSettings {
        Flows = new OAuthFlows {
            ImplicitCodeGrant = true
        },
        CallbackUrls = new [] { "https://myapp.com/home", "https://myapp.com/users" }
    }
});
var domain = userpool.AddDomain("Domain", new UserPoolDomainOptions { });
var signInUrl = domain.SignInUrl(client, new SignInUrlOptions {
    RedirectUri = "https://myapp.com/home"
});
go
userpool := cognito.NewUserPool(this, jsii.String("UserPool"), &UserPoolProps{
})
client := userpool.addClient(jsii.String("Client"), &UserPoolClientOptions{
	// ...
	OAuth: &OAuthSettings{
		Flows: &OAuthFlows{
			ImplicitCodeGrant: jsii.Boolean(true),
		},
		CallbackUrls: []*string{
			jsii.String("https://myapp.com/home"),
			jsii.String("https://myapp.com/users"),
		},
	},
})
domain := userpool.addDomain(jsii.String("Domain"), &UserPoolDomainOptions{
})
signInUrl := domain.SignInUrl(client, &SignInUrlOptions{
	RedirectUri: jsii.String("https://myapp.com/home"),
})

Existing domains can be imported into CDK apps using UserPoolDomain.fromDomainName() API

ts
const myUserPoolDomain = cognito.UserPoolDomain.fromDomainName(this, 'my-user-pool-domain', 'domain-name');
python
my_user_pool_domain = cognito.UserPoolDomain.from_domain_name(self, "my-user-pool-domain", "domain-name")
java
IUserPoolDomain myUserPoolDomain = UserPoolDomain.fromDomainName(this, "my-user-pool-domain", "domain-name");
csharp
var myUserPoolDomain = UserPoolDomain.FromDomainName(this, "my-user-pool-domain", "domain-name");
go
myUserPoolDomain := cognito.UserPoolDomain_FromDomainName(this, jsii.String("my-user-pool-domain"), jsii.String("domain-name"))

To get the domain name of the CloudFront distribution associated with the user pool domain, use cloudFrontEndpoint method.

ts
const userpool = new cognito.UserPool(this, 'UserPool');
const domain = userpool.addDomain('Domain', {
  cognitoDomain: {
    domainPrefix: 'my-awesome-app',
  },
});

new CfnOutput(this, 'CloudFrontEndpoint', {
  value: domain.cloudFrontEndpoint,
});
python
userpool = cognito.UserPool(self, "UserPool")
domain = userpool.add_domain("Domain",
    cognito_domain=cognito.CognitoDomainOptions(
        domain_prefix="my-awesome-app"
    )
)

CfnOutput(self, "CloudFrontEndpoint",
    value=domain.cloud_front_endpoint
)
java
UserPool userpool = new UserPool(this, "UserPool");
UserPoolDomain domain = userpool.addDomain("Domain", UserPoolDomainOptions.builder()
        .cognitoDomain(CognitoDomainOptions.builder()
                .domainPrefix("my-awesome-app")
                .build())
        .build());

CfnOutput.Builder.create(this, "CloudFrontEndpoint")
        .value(domain.getCloudFrontEndpoint())
        .build();
csharp
var userpool = new UserPool(this, "UserPool");
var domain = userpool.AddDomain("Domain", new UserPoolDomainOptions {
    CognitoDomain = new CognitoDomainOptions {
        DomainPrefix = "my-awesome-app"
    }
});

new CfnOutput(this, "CloudFrontEndpoint", new CfnOutputProps {
    Value = domain.CloudFrontEndpoint
});
go
userpool := cognito.NewUserPool(this, jsii.String("UserPool"))
domain := userpool.addDomain(jsii.String("Domain"), &UserPoolDomainOptions{
	CognitoDomain: &CognitoDomainOptions{
		DomainPrefix: jsii.String("my-awesome-app"),
	},
})

awscdk.NewCfnOutput(this, jsii.String("CloudFrontEndpoint"), &CfnOutputProps{
	Value: domain.cloudFrontEndpoint,
})

Deletion protection ​

Deletion protection can be enabled on a user pool to prevent accidental deletion:

ts
const userpool = new cognito.UserPool(this, 'UserPool', {
  // ...
  deletionProtection: true,
});
python
userpool = cognito.UserPool(self, "UserPool",
    # ...
    deletion_protection=True
)
java
UserPool userpool = UserPool.Builder.create(this, "UserPool")
        // ...
        .deletionProtection(true)
        .build();
csharp
var userpool = new UserPool(this, "UserPool", new UserPoolProps {
    // ...
    DeletionProtection = true
});
go
userpool := cognito.NewUserPool(this, jsii.String("UserPool"), &UserPoolProps{
	// ...
	DeletionProtection: jsii.Boolean(true),
})

By default deletion protection is disabled.

email_verified Attribute Mapping ​

If you use a third-party identity provider, you can specify the email_verified attribute in attributeMapping.

ts
const userpool = new cognito.UserPool(this, 'Pool');

new cognito.UserPoolIdentityProviderGoogle(this, 'google', {
  userPool: userpool,
  clientId: 'google-client-id',
  attributeMapping: {
    email: cognito.ProviderAttribute.GOOGLE_EMAIL,
    emailVerified: cognito.ProviderAttribute.GOOGLE_EMAIL_VERIFIED, // you can mapping the `email_verified` attribute.
  },
});
python
userpool = cognito.UserPool(self, "Pool")

cognito.UserPoolIdentityProviderGoogle(self, "google",
    user_pool=userpool,
    client_id="google-client-id",
    attribute_mapping=cognito.AttributeMapping(
        email=cognito.ProviderAttribute.GOOGLE_EMAIL,
        email_verified=cognito.ProviderAttribute.GOOGLE_EMAIL_VERIFIED
    )
)
java
UserPool userpool = new UserPool(this, "Pool");

UserPoolIdentityProviderGoogle.Builder.create(this, "google")
        .userPool(userpool)
        .clientId("google-client-id")
        .attributeMapping(AttributeMapping.builder()
                .email(ProviderAttribute.GOOGLE_EMAIL)
                .emailVerified(ProviderAttribute.GOOGLE_EMAIL_VERIFIED)
                .build())
        .build();
csharp
var userpool = new UserPool(this, "Pool");

new UserPoolIdentityProviderGoogle(this, "google", new UserPoolIdentityProviderGoogleProps {
    UserPool = userpool,
    ClientId = "google-client-id",
    AttributeMapping = new AttributeMapping {
        Email = ProviderAttribute.GOOGLE_EMAIL,
        EmailVerified = ProviderAttribute.GOOGLE_EMAIL_VERIFIED
    }
});
go
userpool := cognito.NewUserPool(this, jsii.String("Pool"))

cognito.NewUserPoolIdentityProviderGoogle(this, jsii.String("google"), &UserPoolIdentityProviderGoogleProps{
	UserPool: userpool,
	ClientId: jsii.String("google-client-id"),
	AttributeMapping: &AttributeMapping{
		Email: cognito.ProviderAttribute_GOOGLE_EMAIL(),
		EmailVerified: cognito.ProviderAttribute_GOOGLE_EMAIL_VERIFIED(),
	},
})

User Pool Group ​

Support for groups in Amazon Cognito user pools enables you to create and manage groups and add users to groups. Use groups to create collections of users to manage their permissions or to represent different types of users.

You can assign an AWS Identity and Access Management (IAM) role to a group to define the permissions for members of a group.

For more information, see Adding groups to a user pool.

ts
declare const userPool: cognito.UserPool;
declare const role: iam.Role;

new cognito.UserPoolGroup(this, 'UserPoolGroup', {
  userPool,
  groupName: 'my-group-name',
  precedence: 1,
  role,  // assign IAM Role
});

// You can also add a group by using addGroup method.
userPool.addGroup('AnotherUserPoolGroup', {
  groupName: 'another-group-name'
});
python
# user_pool: cognito.UserPool
# role: iam.Role


cognito.UserPoolGroup(self, "UserPoolGroup",
    user_pool=user_pool,
    group_name="my-group-name",
    precedence=1,
    role=role
)

# You can also add a group by using addGroup method.
user_pool.add_group("AnotherUserPoolGroup",
    group_name="another-group-name"
)
java
UserPool userPool;
Role role;


UserPoolGroup.Builder.create(this, "UserPoolGroup")
        .userPool(userPool)
        .groupName("my-group-name")
        .precedence(1)
        .role(role)
        .build();

// You can also add a group by using addGroup method.
userPool.addGroup("AnotherUserPoolGroup", UserPoolGroupOptions.builder()
        .groupName("another-group-name")
        .build());
csharp
UserPool userPool;
Role role;


new UserPoolGroup(this, "UserPoolGroup", new UserPoolGroupProps {
    UserPool = userPool,
    GroupName = "my-group-name",
    Precedence = 1,
    Role = role
});

// You can also add a group by using addGroup method.
userPool.AddGroup("AnotherUserPoolGroup", new UserPoolGroupOptions {
    GroupName = "another-group-name"
});
go
var userPool UserPool
var role Role


cognito.NewUserPoolGroup(this, jsii.String("UserPoolGroup"), &UserPoolGroupProps{
	UserPool: UserPool,
	GroupName: jsii.String("my-group-name"),
	Precedence: jsii.Number(1),
	Role: Role,
})

// You can also add a group by using addGroup method.
userPool.addGroup(jsii.String("AnotherUserPoolGroup"), &UserPoolGroupOptions{
	GroupName: jsii.String("another-group-name"),
})

Analytics Configuration ​

User pool clients can be configured with Amazon Pinpoint analytics to collect user activity metrics. This integration enables you to track user engagement and campaign effectiveness.

📝 Note: Amazon Pinpoint isn't available in all AWS Regions. For a list of available Regions, see Amazon Cognito and Amazon Pinpoint Region availability.

The following example shows how to configure analytics for a user pool client:

When specifying a Pinpoint application from the same account ​

If you specify the application property, do not specify the applicationId, externalId, or roleArn properties.

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

declare const userPool: cognito.UserPool;
declare const pinpointApp: pinpoint.CfnApp;
declare const pinpointRole: iam.Role;

new cognito.UserPoolClient(this, 'Client', {
  userPool,
  analytics: {
    // Your Pinpoint project
    application: pinpointApp,

    // Whether to include user data in analytics events
    shareUserData: true,
  },
});
python
import aws_cdk.aws_pinpoint as pinpoint

# user_pool: cognito.UserPool
# pinpoint_app: pinpoint.CfnApp
# pinpoint_role: iam.Role


cognito.UserPoolClient(self, "Client",
    user_pool=user_pool,
    analytics=cognito.AnalyticsConfiguration(
        # Your Pinpoint project
        application=pinpoint_app,

        # Whether to include user data in analytics events
        share_user_data=True
    )
)
java
import software.amazon.awscdk.services.pinpoint.*;

UserPool userPool;
CfnApp pinpointApp;
Role pinpointRole;


UserPoolClient.Builder.create(this, "Client")
        .userPool(userPool)
        .analytics(AnalyticsConfiguration.builder()
                // Your Pinpoint project
                .application(pinpointApp)

                // Whether to include user data in analytics events
                .shareUserData(true)
                .build())
        .build();
csharp
using Amazon.CDK.AWS.Pinpoint;

UserPool userPool;
CfnApp pinpointApp;
Role pinpointRole;


new UserPoolClient(this, "Client", new UserPoolClientProps {
    UserPool = userPool,
    Analytics = new AnalyticsConfiguration {
        // Your Pinpoint project
        Application = pinpointApp,

        // Whether to include user data in analytics events
        ShareUserData = true
    }
});
go
import pinpoint "github.com/aws/aws-cdk-go/awscdk"

var userPool UserPool
var pinpointApp CfnApp
var pinpointRole Role


cognito.NewUserPoolClient(this, jsii.String("Client"), &UserPoolClientProps{
	UserPool: UserPool,
	Analytics: &AnalyticsConfiguration{
		// Your Pinpoint project
		Application: pinpointApp,

		// Whether to include user data in analytics events
		ShareUserData: jsii.Boolean(true),
	},
})

When specifying a Pinpoint application from a different account ​

If you specify the applicationId, externalId, or roleArn properties, do not specify the application property. (In this case, the applicationId, externalId, and roleArn must all be specified.)

Those three attributes are for the cases when Cognito user pool need to be connected to Pinpoint app in other account.

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

declare const userPool: cognito.UserPool;
declare const pinpointApp: pinpoint.CfnApp;
declare const pinpointRole: iam.Role;

new cognito.UserPoolClient(this, 'Client', {
  userPool,
  analytics: {
    // Your Pinpoint project ID
    applicationId: pinpointApp.ref,

    // External ID for the IAM role
    externalId: "sample-external-id",

    // IAM role that Cognito can assume to publish to Pinpoint
    role: pinpointRole,

    // Whether to include user data in analytics events
    shareUserData: true,
  },
});
python
import aws_cdk.aws_pinpoint as pinpoint

# user_pool: cognito.UserPool
# pinpoint_app: pinpoint.CfnApp
# pinpoint_role: iam.Role


cognito.UserPoolClient(self, "Client",
    user_pool=user_pool,
    analytics=cognito.AnalyticsConfiguration(
        # Your Pinpoint project ID
        application_id=pinpoint_app.ref,

        # External ID for the IAM role
        external_id="sample-external-id",

        # IAM role that Cognito can assume to publish to Pinpoint
        role=pinpoint_role,

        # Whether to include user data in analytics events
        share_user_data=True
    )
)
java
import software.amazon.awscdk.services.pinpoint.*;

UserPool userPool;
CfnApp pinpointApp;
Role pinpointRole;


UserPoolClient.Builder.create(this, "Client")
        .userPool(userPool)
        .analytics(AnalyticsConfiguration.builder()
                // Your Pinpoint project ID
                .applicationId(pinpointApp.getRef())

                // External ID for the IAM role
                .externalId("sample-external-id")

                // IAM role that Cognito can assume to publish to Pinpoint
                .role(pinpointRole)

                // Whether to include user data in analytics events
                .shareUserData(true)
                .build())
        .build();
csharp
using Amazon.CDK.AWS.Pinpoint;

UserPool userPool;
CfnApp pinpointApp;
Role pinpointRole;


new UserPoolClient(this, "Client", new UserPoolClientProps {
    UserPool = userPool,
    Analytics = new AnalyticsConfiguration {
        // Your Pinpoint project ID
        ApplicationId = pinpointApp.Ref,

        // External ID for the IAM role
        ExternalId = "sample-external-id",

        // IAM role that Cognito can assume to publish to Pinpoint
        Role = pinpointRole,

        // Whether to include user data in analytics events
        ShareUserData = true
    }
});
go
import pinpoint "github.com/aws/aws-cdk-go/awscdk"

var userPool UserPool
var pinpointApp CfnApp
var pinpointRole Role


cognito.NewUserPoolClient(this, jsii.String("Client"), &UserPoolClientProps{
	UserPool: UserPool,
	Analytics: &AnalyticsConfiguration{
		// Your Pinpoint project ID
		ApplicationId: pinpointApp.ref,

		// External ID for the IAM role
		ExternalId: jsii.String("sample-external-id"),

		// IAM role that Cognito can assume to publish to Pinpoint
		Role: pinpointRole,

		// Whether to include user data in analytics events
		ShareUserData: jsii.Boolean(true),
	},
})

Types ​

NameKindSummary
UserPoolConstruct (L2)Define a Cognito User Pool.
UserPoolClientConstruct (L2)Define a UserPool App Client.
UserPoolDomainConstruct (L2)Define a user pool domain.
UserPoolGroupConstruct (L2)Define a user pool group.
UserPoolIdentityProviderAmazonConstruct (L2)Represents an identity provider that integrates with Login with Amazon.
UserPoolIdentityProviderAppleConstruct (L2)Represents an identity provider that integrates with Apple.
UserPoolIdentityProviderFacebookConstruct (L2)Represents an identity provider that integrates with Facebook Login.
UserPoolIdentityProviderGoogleConstruct (L2)Represents an identity provider that integrates with Google.
UserPoolIdentityProviderOidcConstruct (L2)Represents an identity provider that integrates with OpenID Connect.
UserPoolIdentityProviderSamlConstruct (L2)Represents an identity provider that integrates with SAML.
UserPoolResourceServerConstruct (L2)Defines a User Pool OAuth2.0 Resource Server.
CfnIdentityPoolConstruct (L1)The AWS::Cognito::IdentityPool resource creates an Amazon Cognito identity pool.
CfnIdentityPoolPrincipalTagConstruct (L1)A list of the identity pool principal tag assignments for attributes for access control.
CfnIdentityPoolRoleAttachmentConstruct (L1)The AWS::Cognito::IdentityPoolRoleAttachment resource manages the role configuration for an Amazon Cognito identity pool.
CfnLogDeliveryConfigurationConstruct (L1)Sets up or modifies the logging configuration of a user pool.
CfnManagedLoginBrandingConstruct (L1)Creates a new set of branding settings for a user pool style and associates it with an app client.
CfnTermsConstruct (L1)Creates terms documents for the requested app client.
CfnUserPoolConstruct (L1)The AWS::Cognito::UserPool resource creates an Amazon Cognito user pool.
CfnUserPoolClientConstruct (L1)The AWS::Cognito::UserPoolClient resource specifies an Amazon Cognito user pool client.
CfnUserPoolDomainConstruct (L1)The AWS::Cognito::UserPoolDomain resource creates a new domain for a user pool.
CfnUserPoolGroupConstruct (L1)A user pool group.
CfnUserPoolIdentityProviderConstruct (L1)The AWS::Cognito::UserPoolIdentityProvider resource creates an identity provider for a user pool.
CfnUserPoolRegionalConfigurationAttachmentConstruct (L1)Resource Type definition for AWS::Cognito::UserPoolRegionalConfigurationAttachment.
CfnUserPoolReplicaConstruct (L1)Resource Type definition for AWS::Cognito::UserPoolReplica.
CfnUserPoolResourceServerConstruct (L1)The AWS::Cognito::UserPoolResourceServer resource creates a new OAuth2.0 resource server and defines custom scopes in it.
CfnUserPoolRiskConfigurationAttachmentConstruct (L1)The AWS::Cognito::UserPoolRiskConfigurationAttachment resource sets the risk configuration that is used for Amazon Cognito advanced security features.
CfnUserPoolUICustomizationAttachmentConstruct (L1)A container for the UI customization information for the hosted UI in a user pool.
CfnUserPoolUserConstruct (L1)The AWS::Cognito::UserPoolUser resource creates an Amazon Cognito user pool user.
CfnUserPoolUserToGroupAttachmentConstruct (L1)Adds a user to a group.
AccountRecoveryEnumHow will a user be able to recover their account?
AdvancedSecurityModeEnumThe different ways in which a user pool's Advanced Security Mode can be configured.
AllowedFirstAuthFactorsStructThe types of authentication that you want to allow for users' first authentication prompt.
AnalyticsConfigurationStructThe settings for Amazon Pinpoint analytics configuration.
AttributeMappingStructThe mapping of user pool attributes to the attributes provided by the identity providers.
AuthFlowStructTypes of authentication flow.
AutoVerifiedAttrsStructAttributes that can be automatically verified for users in a user pool.
BaseUrlOptionsStructOptions to customize the behaviour of baseUrl().
BooleanAttributeClassThe Boolean custom attribute type.
CfnIdentityPool.CognitoIdentityProviderPropertyStructCognitoIdentityProvider is a property of the AWS::Cognito::IdentityPool resource that represents an Amazon Cognito user pool and its client ID.
CfnIdentityPool.CognitoStreamsPropertyStructCognitoStreams is a property of the AWS::Cognito::IdentityPool resource that defines configuration options for Amazon Cognito streams.
CfnIdentityPool.PushSyncPropertyStructPushSync is a property of the AWS::Cognito::IdentityPool resource that defines the configuration options to be applied to an Amazon Cognito identity pool.
CfnIdentityPoolPrincipalTagPropsStructProperties for defining a CfnIdentityPoolPrincipalTag.
CfnIdentityPoolPropsStructProperties for defining a CfnIdentityPool.
CfnIdentityPoolRoleAttachment.MappingRulePropertyStructDefines how to map a claim to a role ARN.
CfnIdentityPoolRoleAttachment.RoleMappingPropertyStructOne of a set of RoleMappings , a property of the AWS::Cognito::IdentityPoolRoleAttachment resource that defines the role-mapping attributes of an Amazon Cognito identity pool.
CfnIdentityPoolRoleAttachment.RulesConfigurationTypePropertyStructRulesConfigurationType is a subproperty of the RoleMapping property that defines the rules to be used for mapping users to roles.
CfnIdentityPoolRoleAttachmentPropsStructProperties for defining a CfnIdentityPoolRoleAttachment.
CfnLogDeliveryConfiguration.CloudWatchLogsConfigurationPropertyStructConfiguration for the CloudWatch log group destination of user pool detailed activity logging, or of user activity log export with advanced security features.
CfnLogDeliveryConfiguration.FirehoseConfigurationPropertyStructConfiguration for the Amazon Data Firehose stream destination of user activity log export with threat protection.
CfnLogDeliveryConfiguration.LogConfigurationPropertyStructThe configuration of user event logs to an external AWS service like Amazon Data Firehose, Amazon S3, or Amazon CloudWatch Logs.
CfnLogDeliveryConfiguration.S3ConfigurationPropertyStructConfiguration for the Amazon S3 bucket destination of user activity log export with threat protection.
CfnLogDeliveryConfigurationPropsStructProperties for defining a CfnLogDeliveryConfiguration.
CfnManagedLoginBranding.AssetTypePropertyStructAn image file from a managed login branding style in a user pool.
CfnManagedLoginBrandingPropsStructProperties for defining a CfnManagedLoginBranding.
CfnTermsPropsStructProperties for defining a CfnTerms.
CfnUserPool.AccountRecoverySettingPropertyStructThe available verified method a user can use to recover their password when they call ForgotPassword .
CfnUserPool.AdminCreateUserConfigPropertyStructThe settings for administrator creation of users in a user pool.
CfnUserPool.AdvancedSecurityAdditionalFlowsPropertyStructThreat protection configuration options for additional authentication types in your user pool, including custom authentication.
CfnUserPool.CustomEmailSenderPropertyStructThe configuration of a custom email sender Lambda trigger.
CfnUserPool.CustomSMSSenderPropertyStructThe configuration of a custom SMS sender Lambda trigger.
CfnUserPool.DeviceConfigurationPropertyStructThe device-remembering configuration for a user pool.
CfnUserPool.EmailConfigurationPropertyStructThe email configuration of your user pool.
CfnUserPool.EumsSmsConfigurationPropertyStruct
CfnUserPool.InboundFederationPropertyStruct
CfnUserPool.InviteMessageTemplatePropertyStructThe template for the welcome message to new users.
CfnUserPool.IssuerConfigurationPropertyStruct
CfnUserPool.KeyConfigurationPropertyStruct
CfnUserPool.LambdaConfigPropertyStructA collection of user pool Lambda triggers.
CfnUserPool.NumberAttributeConstraintsPropertyStructThe minimum and maximum values of an attribute that is of the number type, for example custom:age .
CfnUserPool.PasswordPolicyPropertyStructThe password policy settings for a user pool, including complexity, history, and length requirements.
CfnUserPool.PoliciesPropertyStructA list of user pool policies.
CfnUserPool.PreTokenGenerationConfigPropertyStructThe properties of a pre token generation Lambda trigger.
CfnUserPool.RecoveryOptionPropertyStructA recovery option for a user.
CfnUserPool.SchemaAttributePropertyStructA list of the user attributes and their properties in your user pool.
CfnUserPool.SignInPolicyPropertyStructThe policy for allowed types of authentication in a user pool.
CfnUserPool.SmsConfigurationPropertyStructUser pool configuration for delivery of SMS messages with Amazon Simple Notification Service.
CfnUserPool.StringAttributeConstraintsPropertyStructThe minimum and maximum length values of an attribute that is of the string type, for example custom:department .
CfnUserPool.UserAttributeUpdateSettingsPropertyStructThe settings for updates to user attributes.
CfnUserPool.UsernameConfigurationPropertyStructCase sensitivity of the username input for the selected sign-in option.
CfnUserPool.UserPoolAddOnsPropertyStructUser pool add-ons.
CfnUserPool.VerificationMessageTemplatePropertyStructThe template for the verification message that your user pool delivers to users who set an email address or phone number attribute.
CfnUserPoolClient.AnalyticsConfigurationPropertyStructThe settings for Amazon Pinpoint analytics configuration.
CfnUserPoolClient.RefreshTokenRotationPropertyStructThe configuration of your app client for refresh token rotation.
CfnUserPoolClient.TokenValidityUnitsPropertyStructThe units that validity times are represented in.
CfnUserPoolClientPropsStructProperties for defining a CfnUserPoolClient.
CfnUserPoolDomain.CustomDomainConfigTypePropertyStructThe configuration for a hosted UI custom domain.
CfnUserPoolDomain.FailoverTypePropertyStruct
CfnUserPoolDomain.RoutingTypePropertyStruct
CfnUserPoolDomainPropsStructProperties for defining a CfnUserPoolDomain.
CfnUserPoolGroupPropsStructProperties for defining a CfnUserPoolGroup.
CfnUserPoolIdentityProviderPropsStructProperties for defining a CfnUserPoolIdentityProvider.
CfnUserPoolPropsStructProperties for defining a CfnUserPool.
CfnUserPoolRegionalConfigurationAttachment.CustomEmailSenderPropertyStruct
CfnUserPoolRegionalConfigurationAttachment.CustomSMSSenderPropertyStruct
CfnUserPoolRegionalConfigurationAttachment.EmailConfigurationPropertyStruct
CfnUserPoolRegionalConfigurationAttachment.EumsSmsConfigurationPropertyStruct
CfnUserPoolRegionalConfigurationAttachment.InboundFederationPropertyStruct
CfnUserPoolRegionalConfigurationAttachment.LambdaConfigPropertyStruct
CfnUserPoolRegionalConfigurationAttachment.PreTokenGenerationConfigPropertyStruct
CfnUserPoolRegionalConfigurationAttachment.SmsConfigurationPropertyStruct
CfnUserPoolRegionalConfigurationAttachmentPropsStructProperties for defining a CfnUserPoolRegionalConfigurationAttachment.
CfnUserPoolReplicaPropsStructProperties for defining a CfnUserPoolReplica.
CfnUserPoolResourceServer.ResourceServerScopeTypePropertyStructOne custom scope associated with a user pool resource server.
CfnUserPoolResourceServerPropsStructProperties for defining a CfnUserPoolResourceServer.
CfnUserPoolRiskConfigurationAttachment.AccountTakeoverActionsTypePropertyStructA list of account-takeover actions for each level of risk that Amazon Cognito might assess with advanced security features.
CfnUserPoolRiskConfigurationAttachment.AccountTakeoverActionTypePropertyStructThe automated response to a risk level for adaptive authentication in full-function, or ENFORCED , mode.
CfnUserPoolRiskConfigurationAttachment.AccountTakeoverRiskConfigurationTypePropertyStructThe settings for automated responses and notification templates for adaptive authentication with advanced security features.
CfnUserPoolRiskConfigurationAttachment.CompromisedCredentialsActionsTypePropertyStructSettings for user pool actions when Amazon Cognito detects compromised credentials with advanced security features in full-function ENFORCED mode.
CfnUserPoolRiskConfigurationAttachment.CompromisedCredentialsRiskConfigurationTypePropertyStructSettings for compromised-credentials actions and authentication-event sources with advanced security features in full-function ENFORCED mode.
CfnUserPoolRiskConfigurationAttachment.NotifyConfigurationTypePropertyStructThe configuration for Amazon SES email messages that advanced security features sends to a user when your adaptive authentication automated response has a Notify action.
CfnUserPoolRiskConfigurationAttachment.NotifyEmailTypePropertyStructThe template for email messages that advanced security features sends to a user when your threat protection automated response has a Notify action.
CfnUserPoolRiskConfigurationAttachment.RiskExceptionConfigurationTypePropertyStructExceptions to the risk evaluation configuration, including always-allow and always-block IP address ranges.
CfnUserPoolRiskConfigurationAttachmentPropsStructProperties for defining a CfnUserPoolRiskConfigurationAttachment.
CfnUserPoolUICustomizationAttachmentPropsStructProperties for defining a CfnUserPoolUICustomizationAttachment.
CfnUserPoolUser.AttributeTypePropertyStructThe name and value of a user attribute.
CfnUserPoolUserPropsStructProperties for defining a CfnUserPoolUser.
CfnUserPoolUserToGroupAttachmentPropsStructProperties for defining a CfnUserPoolUserToGroupAttachment.
ClientAttributesClassA set of attributes, useful to set Read and Write attributes.
CognitoDomainOptionsStructOptions while specifying a cognito prefix domain.
CustomAttributeConfigStructConfiguration that will be fed into CloudFormation for any custom attribute type.
CustomAttributePropsStructConstraints that can be applied to a custom attribute of any type.
CustomDomainOptionsStructOptions while specifying custom domain.
CustomThreatProtectionModeEnumThe Type of Threat Protection Enabled for Custom Authentication.
DateTimeAttributeClassThe DateTime custom attribute type.
DeviceTrackingStructDevice tracking settings.
EmailSettingsStructEmail settings for the user pool.
FeaturePlanEnumThe user pool feature plan, or tier.
ICustomAttributeInterfaceRepresents a custom attribute type.
IUserPoolInterfaceRepresents a Cognito UserPool.
IUserPoolClientInterfaceRepresents a Cognito user pool client.
IUserPoolDomainInterfaceRepresents a user pool domain.
IUserPoolGroupInterfaceRepresents a user pool group.
IUserPoolIdentityProviderInterfaceRepresents a UserPoolIdentityProvider.
IUserPoolResourceServerInterfaceRepresents a Cognito user pool resource server.
KeepOriginalAttrsStructAttributes that will be kept until the user verifies the changed attribute.
LambdaVersionEnumThe user pool trigger version of the request that Amazon Cognito sends to your Lambda function.
ManagedLoginVersionEnumThe branding version of managed login for the domain.
MfaEnumThe different ways in which a user pool's MFA enforcement can be configured.
MfaSecondFactorStructThe different ways in which a user pool can obtain their MFA token for sign in.
NumberAttributeClassThe Number custom attribute type.
NumberAttributeConstraintsStructConstraints that can be applied to a custom attribute of number type.
NumberAttributePropsStructProps for NumberAttr.
OAuthFlowsStructTypes of OAuth grant flows.
OAuthScopeClassOAuth scopes that are allowed with this client.
OAuthSettingsStructOAuth settings to configure the interaction between the app and this client.
OidcAttributeRequestMethodEnumThe method to use to request attributes.
OidcEndpointsStructOpenID Connect endpoints.
PasskeyUserVerificationEnumThe user-pool treatment for MFA with a passkey.
PasswordPolicyStructPassword policy for User Pools.
ProviderAttributeClassAn attribute available from a third party identity provider.
ResourceServerScopeClassA scope for ResourceServer.
ResourceServerScopePropsStructProps to initialize ResourceServerScope.
SignInAliasesStructThe different ways in which users of this pool can sign up or sign in.
SigningAlgorithmEnumSigning algorithms for SAML requests.
SignInPolicyStructSign-in policy for User Pools.
SignInUrlOptionsStructOptions to customize the behaviour of signInUrl().
StandardAttributeStructStandard attribute that can be marked as required or mutable.
StandardAttributesStructThe set of standard attributes that can be marked as required or mutable.
StandardAttributesMaskStructThis interface contains standard attributes recognized by Cognito from https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html including built-in attributes email_verified and phone_number_verified.
StandardThreatProtectionModeEnumThe Type of Threat Protection Enabled for Standard Authentication.
StringAttributeClassThe String custom attribute type.
StringAttributeConstraintsStructConstraints that can be applied to a custom attribute of string type.
StringAttributePropsStructProps for constructing a StringAttr.
UserInvitationConfigStructUser pool configuration when administrators sign users up.
UserPoolClientIdentityProviderClassIdentity providers supported by the UserPoolClient.
UserPoolClientOptionsStructOptions to create a UserPoolClient.
UserPoolClientPropsStructProperties for the UserPoolClient construct.
UserPoolDomainOptionsStructOptions to create a UserPoolDomain.
UserPoolDomainPropsStructProps for UserPoolDomain construct.
UserPoolEmailClassConfigure how Cognito sends emails.
UserPoolEmailConfigStructResult of binding email settings with a user pool.
UserPoolGroupOptionsStructOptions to create a UserPoolGroup.
UserPoolGroupPropsStructProps for UserPoolGroup construct.
UserPoolIdentityProviderClassUser pool third-party identity providers.
UserPoolIdentityProviderAmazonPropsStructProperties to initialize UserPoolAmazonIdentityProvider.
UserPoolIdentityProviderApplePropsStructProperties to initialize UserPoolAppleIdentityProvider.
UserPoolIdentityProviderFacebookPropsStructProperties to initialize UserPoolFacebookIdentityProvider.
UserPoolIdentityProviderGooglePropsStructProperties to initialize UserPoolGoogleIdentityProvider.
UserPoolIdentityProviderOidcPropsStructProperties to initialize UserPoolIdentityProviderOidc.
UserPoolIdentityProviderPropsStructProperties to create a new instance of UserPoolIdentityProvider.
UserPoolIdentityProviderSamlMetadataClassMetadata for a SAML user pool identity provider.
UserPoolIdentityProviderSamlMetadataTypeEnumMetadata types that can be used for a SAML user pool identity provider.
UserPoolIdentityProviderSamlPropsStructProperties to initialize UserPoolIdentityProviderSaml.
UserPoolOperationClassUser pool operations to which lambda triggers can be attached.
UserPoolPropsStructProps for the UserPool construct.
UserPoolResourceServerOptionsStructOptions to create a UserPoolResourceServer.
UserPoolResourceServerPropsStructProperties for the UserPoolResourceServer construct.
UserPoolSESOptionsStructConfiguration for Cognito sending emails via Amazon SES.
UserPoolTriggersStructTriggers for a user pool.
UserVerificationConfigStructUser pool configuration for user self sign up.
VerificationEmailStyleEnumThe email verification style.