UserPool L2 construct
Define a Cognito User Pool.
Example
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' ],
},
});
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"]
)
)
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());
// Install: dotnet add package Amazon.CDK.Lib
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" }
}
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
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"),
},
},
})
Initializer
new UserPool(scope: Construct, id: string, props?: UserPoolProps)
UserPool(scope: Construct, id: str, props: typing.Optional[UserPoolProps] = None)
new UserPool(Construct scope, String id, UserPoolProps props)
new UserPool(Construct scope, string id, UserPoolProps? props = null)
NewUserPool(Scope Construct, Id *string, Props UserPoolProps)
Construct Props
accountRecoveryoptionalAccountRecoveryaccount_recoveryoptionalAccountRecoveryaccountRecoveryoptionalAccountRecoveryAccountRecoveryoptionalAccountRecoveryAccountRecoveryoptionalAccountRecovery#Default: AccountRecovery.PHONE_WITHOUT_MFA_AND_EMAIL
advancedSecurityModeoptionalAdvancedSecurityModeadvanced_security_modeoptionalAdvancedSecurityModeadvancedSecurityModeoptionalAdvancedSecurityModeAdvancedSecurityModeoptionalAdvancedSecurityModeAdvancedSecurityModeoptionalAdvancedSecurityModedeprecated#Default: no value
autoVerifyoptionalAutoVerifiedAttrsauto_verifyoptionalAutoVerifiedAttrsautoVerifyoptionalAutoVerifiedAttrsAutoVerifyoptionalAutoVerifiedAttrsAutoVerifyoptionalAutoVerifiedAttrs#Default: If signInAlias includes email and/or phone, they will be included in autoVerifiedAttributes by default. If absent, no attributes will be auto-verified.
EMAIL and PHONE are the only available options.
customAttributesoptional{ [key: string]: ICustomAttribute }custom_attributesoptionaltyping.Mapping[str, ICustomAttribute]customAttributesoptionalMap<String, ICustomAttribute>CustomAttributesoptionalIDictionary<string, ICustomAttribute>CustomAttributesoptional*map[string]ICustomAttribute#Default: No custom attributes.
customSenderKmsKeyoptionalIKeyRefcustom_sender_kms_keyoptionalIKeyRefcustomSenderKmsKeyoptionalIKeyRefCustomSenderKmsKeyoptionalIKeyRefCustomSenderKmsKeyoptionalIKeyRef#Default: no key ID configured
customThreatProtectionModeoptionalCustomThreatProtectionModecustom_threat_protection_modeoptionalCustomThreatProtectionModecustomThreatProtectionModeoptionalCustomThreatProtectionModeCustomThreatProtectionModeoptionalCustomThreatProtectionModeCustomThreatProtectionModeoptionalCustomThreatProtectionMode#Default: no value
This feature only functions if your FeaturePlan is set to FeaturePlan.PLUS
deletionProtectionoptionalbooleandeletion_protectionoptionalbooldeletionProtectionoptionalBooleanDeletionProtectionoptionalboolDeletionProtectionoptional*bool= false#deviceTrackingoptionalDeviceTrackingdevice_trackingoptionalDeviceTrackingdeviceTrackingoptionalDeviceTrackingDeviceTrackingoptionalDeviceTrackingDeviceTrackingoptionalDeviceTracking#Default: see defaults on each property of DeviceTracking.
emailoptionalUserPoolEmailemailoptionalUserPoolEmailemailoptionalUserPoolEmailEmailoptionalUserPoolEmailEmailoptionalUserPoolEmail#Default: cognito will use the default email configuration
enableSmsRoleoptionalbooleanenable_sms_roleoptionalboolenableSmsRoleoptionalBooleanEnableSmsRoleoptionalboolEnableSmsRoleoptional*bool#Default: CDK will determine based on other properties of the user pool if an SMS role should be created or not.
When left unspecified, CDK will determine based on other properties if a role is needed or not.
featurePlanoptionalFeaturePlanfeature_planoptionalFeaturePlanfeaturePlanoptionalFeaturePlanFeaturePlanoptionalFeaturePlanFeaturePlanoptionalFeaturePlan#Default: FeaturePlan.ESSENTIALS for a newly created user pool; FeaturePlan.LITE otherwise
This parameter determines the eligibility of the user pool for features like managed login, access-token customization, and threat protection.
keepOriginaloptionalKeepOriginalAttrskeep_originaloptionalKeepOriginalAttrskeepOriginaloptionalKeepOriginalAttrsKeepOriginaloptionalKeepOriginalAttrsKeepOriginaloptionalKeepOriginalAttrs#Default: Nothing is kept.
EMAIL and PHONE are the only available options.
lambdaTriggersoptionalUserPoolTriggerslambda_triggersoptionalUserPoolTriggerslambdaTriggersoptionalUserPoolTriggersLambdaTriggersoptionalUserPoolTriggersLambdaTriggersoptionalUserPoolTriggers#Default: No Lambda triggers.
mfaMessageoptionalstringmfa_messageoptionalstrmfaMessageoptionalStringMfaMessageoptionalstringMfaMessageoptional*string#Default: 'Your authentication code is {####}.'
Use '{####}' in the template where Cognito should insert the verification code.
mfaSecondFactoroptionalMfaSecondFactormfa_second_factoroptionalMfaSecondFactormfaSecondFactoroptionalMfaSecondFactorMfaSecondFactoroptionalMfaSecondFactorMfaSecondFactoroptionalMfaSecondFactor#Default: { sms: true, otp: false, email: false }, if mfa is set to OPTIONAL or REQUIRED. { sms: false, otp: false, email:false }, otherwise
Ignored if mfa is set to OFF.
passkeyRelyingPartyIdoptionalstringpasskey_relying_party_idoptionalstrpasskeyRelyingPartyIdoptionalStringPasskeyRelyingPartyIdoptionalstringPasskeyRelyingPartyIdoptional*string#Default: No authentication domain
notes
Under the following conditions, the passkey relying party ID must be the fully-qualified domain name of your custom domain:
- The user pool is configured for passkey authentication.
- The user pool has a custom domain, whether or not it also has a prefix domain.
- Your application performs authentication with managed login or the classic hosted UI.
passkeyUserVerificationoptionalPasskeyUserVerificationpasskey_user_verificationoptionalPasskeyUserVerificationpasskeyUserVerificationoptionalPasskeyUserVerificationPasskeyUserVerificationoptionalPasskeyUserVerificationPasskeyUserVerificationoptionalPasskeyUserVerification#Default: Cognito default setting is PasskeyUserVerification.PREFERRED
You can override other MFA options and require passkey MFA, or you can set it as preferred. When passkey MFA is preferred, the hosted UI encourages users to register a passkey at sign-in.
passwordPolicyoptionalPasswordPolicypassword_policyoptionalPasswordPolicypasswordPolicyoptionalPasswordPolicyPasswordPolicyoptionalPasswordPolicyPasswordPolicyoptionalPasswordPolicy#Default: see defaults on each property of PasswordPolicy.
removalPolicyoptionalRemovalPolicyremoval_policyoptionalRemovalPolicyremovalPolicyoptionalRemovalPolicyRemovalPolicyoptionalRemovalPolicyRemovalPolicyoptionalRemovalPolicy= RemovalPolicy.RETAIN#selfSignUpEnabledoptionalbooleanself_sign_up_enabledoptionalboolselfSignUpEnabledoptionalBooleanSelfSignUpEnabledoptionalboolSelfSignUpEnabledoptional*bool= false#To configure self sign-up configuration use the userVerification property.
signInAliasesoptionalSignInAliasessign_in_aliasesoptionalSignInAliasessignInAliasesoptionalSignInAliasesSignInAliasesoptionalSignInAliasesSignInAliasesoptionalSignInAliases#Default: { username: true }
notes
Allows either username with aliases OR sign in with email, phone, or both.
Read the sections on usernames and aliases to learn more - https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html
To match with 'Option 1' in the above link, with a verified email, this property 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 }.
signInCaseSensitiveoptionalbooleansign_in_case_sensitiveoptionalboolsignInCaseSensitiveoptionalBooleanSignInCaseSensitiveoptionalboolSignInCaseSensitiveoptional*bool= true#For example, when this option is set to false, users will be able to sign in using either MyUsername or myusername.
signInPolicyoptionalSignInPolicysign_in_policyoptionalSignInPolicysignInPolicyoptionalSignInPolicySignInPolicyoptionalSignInPolicySignInPolicyoptionalSignInPolicy#Default: see defaults on each property of SignInPolicy.
smsRoleoptionalIRoleRefsms_roleoptionalIRoleRefsmsRoleoptionalIRoleRefSmsRoleoptionalIRoleRefSmsRoleoptionalIRoleRef#Default: a new IAM role is created.
smsRoleExternalIdoptionalstringsms_role_external_idoptionalstrsmsRoleExternalIdoptionalStringSmsRoleExternalIdoptionalstringSmsRoleExternalIdoptional*string#Default: No external id will be configured.
Learn more about ExternalId here - https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html
This property will be ignored if smsRole is not specified.
snsRegionoptionalstringsns_regionoptionalstrsnsRegionoptionalStringSnsRegionoptionalstringSnsRegionoptional*string#Default: The same region as the user pool, with a few exceptions - https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sms-settings.html#user-pool-sms-settings-first-time
This property will do nothing if SMS configuration is not configured.
standardAttributesoptionalStandardAttributesstandard_attributesoptionalStandardAttributesstandardAttributesoptionalStandardAttributesStandardAttributesoptionalStandardAttributesStandardAttributesoptionalStandardAttributes#Default: All standard attributes are optional and mutable.
Read more on attributes here - https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html
standardThreatProtectionModeoptionalStandardThreatProtectionModestandard_threat_protection_modeoptionalStandardThreatProtectionModestandardThreatProtectionModeoptionalStandardThreatProtectionModeStandardThreatProtectionModeoptionalStandardThreatProtectionModeStandardThreatProtectionModeoptionalStandardThreatProtectionMode#Default: StandardThreatProtectionMode.NO_ENFORCEMENT
This feature only functions if your FeaturePlan is set to FeaturePlan.PLUS
userInvitationoptionalUserInvitationConfiguser_invitationoptionalUserInvitationConfiguserInvitationoptionalUserInvitationConfigUserInvitationoptionalUserInvitationConfigUserInvitationoptionalUserInvitationConfig#Default: see defaults in UserInvitationConfig.
userPoolNameoptionalstringuser_pool_nameoptionalstruserPoolNameoptionalStringUserPoolNameoptionalstringUserPoolNameoptional*string#Default: automatically generated name by CloudFormation at deploy time.
userVerificationoptionalUserVerificationConfiguser_verificationoptionalUserVerificationConfiguserVerificationoptionalUserVerificationConfigUserVerificationoptionalUserVerificationConfigUserVerificationoptionalUserVerificationConfig#Default: see defaults in UserVerificationConfig.
Enable or disable self sign-up via the selfSignUpEnabled property.
Properties
envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#notes
For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.
For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.
identityProvidersIUserPoolIdentityProvider[]identity_providerstyping.List[IUserPoolIdentityProvider]identityProvidersList<IUserPoolIdentityProvider>IdentityProvidersIUserPoolIdentityProvider[]IdentityProviders*[]IUserPoolIdentityProviderrequired#PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#userPoolProviderNamestringuser_pool_provider_namestruserPoolProviderNameStringUserPoolProviderNamestringUserPoolProviderName*stringrequired#userPoolProviderUrlstringuser_pool_provider_urlstruserPoolProviderUrlStringUserPoolProviderUrlstringUserPoolProviderUrl*stringrequired#userPoolRefUserPoolReferenceuser_pool_refUserPoolReferenceuserPoolRefUserPoolReferenceUserPoolRefUserPoolReferenceUserPoolRefUserPoolReferencerequired#Methods
addClient(id: string, options?: UserPoolClientOptions): UserPoolClientdef add_client(self, id: str, options: typing.Optional[UserPoolClientOptions] = None) -> UserPoolClientpublic UserPoolClient addClient(String id, UserPoolClientOptions options)public UserPoolClient AddClient(string id, UserPoolClientOptions? options = null)func AddClient(Id *string, Options UserPoolClientOptions) UserPoolClient#addDomain(id: string, options: UserPoolDomainOptions): UserPoolDomaindef add_domain(self, id: str, options: UserPoolDomainOptions) -> UserPoolDomainpublic UserPoolDomain addDomain(String id, UserPoolDomainOptions options)public UserPoolDomain AddDomain(string id, UserPoolDomainOptions options)func AddDomain(Id *string, Options UserPoolDomainOptions) UserPoolDomain#addGroup(id: string, options: UserPoolGroupOptions): UserPoolGroupdef add_group(self, id: str, options: UserPoolGroupOptions) -> UserPoolGrouppublic UserPoolGroup addGroup(String id, UserPoolGroupOptions options)public UserPoolGroup AddGroup(string id, UserPoolGroupOptions options)func AddGroup(Id *string, Options UserPoolGroupOptions) UserPoolGroup#addResourceServer(id: string, options: UserPoolResourceServerOptions): UserPoolResourceServerdef add_resource_server(self, id: str, options: UserPoolResourceServerOptions) -> UserPoolResourceServerpublic UserPoolResourceServer addResourceServer(String id, UserPoolResourceServerOptions options)public UserPoolResourceServer AddResourceServer(string id, UserPoolResourceServerOptions options)func AddResourceServer(Id *string, Options UserPoolResourceServerOptions) UserPoolResourceServer#addTrigger(operation: UserPoolOperation, fn: IFunction, lambdaVersion?: LambdaVersion): voiddef add_trigger(self, operation: UserPoolOperation, fn: IFunction, lambda_version: typing.Optional[LambdaVersion] = None) -> Nonepublic void addTrigger(UserPoolOperation operation, IFunction fn, LambdaVersion lambdaVersion)public void AddTrigger(UserPoolOperation operation, IFunction fn, LambdaVersion? lambdaVersion = null)func AddTrigger(Operation UserPoolOperation, Fn IFunction, LambdaVersion LambdaVersion)#applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.
Parameters
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.
The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).
fromUserPoolArn(scope: Construct, id: string, userPoolArn: string): IUserPool@staticmethod def from_user_pool_arn(scope: Construct, id: str, user_pool_arn: str) -> IUserPoolpublic static IUserPool fromUserPoolArn(Construct scope, String id, String userPoolArn)public static IUserPool FromUserPoolArn(Construct scope, string id, string userPoolArn)func FromUserPoolArn(Scope Construct, Id *string, UserPoolArn *string) IUserPoolstatic#fromUserPoolId(scope: Construct, id: string, userPoolId: string): IUserPool@staticmethod def from_user_pool_id(scope: Construct, id: str, user_pool_id: str) -> IUserPoolpublic static IUserPool fromUserPoolId(Construct scope, String id, String userPoolId)public static IUserPool FromUserPoolId(Construct scope, string id, string userPoolId)func FromUserPoolId(Scope Construct, Id *string, UserPoolId *string) IUserPoolstatic#grant(grantee: IGrantable, ...actions: string[]): Grantdef grant(self, grantee: IGrantable, actions: str) -> Grantpublic Grant grant(IGrantable grantee, String actions)public Grant Grant(IGrantable grantee, string actions)func Grant(Grantee IGrantable, Actions *string) Grant#isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.
Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.
Parameters
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#registerIdentityProvider(provider: IUserPoolIdentityProviderRef): voiddef register_identity_provider(self, provider: IUserPoolIdentityProviderRef) -> Nonepublic void registerIdentityProvider(IUserPoolIdentityProviderRef provider)public void RegisterIdentityProvider(IUserPoolIdentityProviderRef provider)func RegisterIdentityProvider(Provider IUserPoolIdentityProviderRef)#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.