aws-cdk.aws-cognito


Nameaws-cdk.aws-cognito JSON
Version 1.203.0 PyPI version JSON
download
home_pagehttps://github.com/aws/aws-cdk
SummaryThe CDK Construct Library for AWS::Cognito
upload_time2023-05-31 23:01:34
maintainer
docs_urlNone
authorAmazon Web Services
requires_python~=3.7
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Amazon Cognito Construct Library

<!--BEGIN STABILITY BANNER-->---


Features                                   | Stability
-------------------------------------------|--------------------------------------------------------
CFN Resources                              | ![Stable](https://img.shields.io/badge/stable-success.svg?style=for-the-badge)
Higher level constructs for User Pools     | ![Stable](https://img.shields.io/badge/stable-success.svg?style=for-the-badge)
Higher level constructs for Identity Pools | ![Not Implemented](https://img.shields.io/badge/not--implemented-black.svg?style=for-the-badge)

> **CFN Resources:** All classes with the `Cfn` prefix in this module ([CFN Resources](https://docs.aws.amazon.com/cdk/latest/guide/constructs.html#constructs_lib)) are always
> stable and safe to use.

<!-- -->

> **Stable:** Higher level constructs in this module that are marked stable will not undergo any
> breaking changes. They will strictly follow the [Semantic Versioning](https://semver.org/) model.

---
<!--END STABILITY BANNER-->

[Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) 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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) and [identity
pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html). 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](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cognito-identitypool-alpha-readme.html).

This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.

## Table of Contents

* [User Pools](#user-pools)

  * [Sign Up](#sign-up)
  * [Sign In](#sign-in)
  * [Attributes](#attributes)
  * [Security](#security)

    * [Multi-factor Authentication](#multi-factor-authentication-mfa)
    * [Account Recovery Settings](#account-recovery-settings)
  * [Emails](#emails)
  * [Device Tracking](#device-tracking)
  * [Lambda Triggers](#lambda-triggers)

    * [Trigger Permissions](#trigger-permissions)
  * [Import](#importing-user-pools)
  * [Identity Providers](#identity-providers)
  * [App Clients](#app-clients)
  * [Resource Servers](#resource-servers)
  * [Domains](#domains)

## 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.

```python
cognito.UserPool(self, "myuserpool",
    user_pool_name="myawesomeapp-userpool"
)
```

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.

```python
user_pool = cognito.UserPool(self, "myuserpool")
role = iam.Role(self, "role",
    assumed_by=iam.ServicePrincipal("foo")
)
user_pool.grant(role, "cognito-idp:AdminCreateUser")
```

### 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](https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html).

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 -

```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 {####}"
    )
)
```

By default, self sign up is disabled. Learn more about [email and SMS verification messages
here](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-customizations.html).

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 -

```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 {####}"
    )
)
```

All email subjects, bodies and SMS messages for both invitation and verification support Cognito's message templating.
Learn more about [message templates
here](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-templates.html).

### 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 -

```python
cognito.UserPool(self, "myuserpool",
    # ...
    # ...
    sign_in_aliases=cognito.SignInAliases(
        username=True,
        email=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](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases-settings).

⚠️ 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](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases).
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.

```python
cognito.UserPool(self, "myuserpool",
    # ...
    # ...
    sign_in_aliases=cognito.SignInAliases(username=True, email=True),
    auto_verify=cognito.AutoVerifiedAttrs(email=True, phone=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.

### 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](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html).

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

```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()
    }
)
```

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](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html).

### 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.

```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"
)
```

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](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html).

#### 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](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html) 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)](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-totp.html).

```python
cognito.UserPool(self, "myuserpool",
    # ...
    mfa=cognito.Mfa.REQUIRED,
    mfa_second_factor=cognito.MfaSecondFactor(
        sms=True,
        otp=True
    )
)
```

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.

The following code snippet configures these properties -

```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)
    )
)
```

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](https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-recover-a-user-account.html)

```python
cognito.UserPool(self, "UserPool",
    # ...
    account_recovery=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.

### 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](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html).

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.

```python
cognito.UserPool(self, "myuserpool",
    email=cognito.UserPoolEmail.with_cognito("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](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html#user-pool-email-developer)
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.

```python
cognito.UserPool(self, "myuserpool",
    email=cognito.UserPoolEmail.with_sES(
        from_email="noreply@myawesomeapp.com",
        from_name="Awesome App",
        reply_to="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.

```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"
    )
)
```

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.

```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"
    )
)
```

### Device Tracking

User pools can be configured to track devices that users have logged in to.
Read more at [Device Tracking](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html)

```python
cognito.UserPool(self, "myuserpool",
    # ...
    device_tracking=cognito.DeviceTracking(
        challenge_required_on_new_device=True,
        device_only_remembered_on_user_prompt=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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html).

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 -

```python
auth_challenge_fn = lambda_.Function(self, "authChallengeFn",
    runtime=lambda_.Runtime.NODEJS_14_X,
    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_14_X,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "path/to/asset"))
))
```

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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html).

#### 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](https://github.com/aws/aws-cdk/issues/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.

```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]
    )]
))
```

### 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`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html)
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.

```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")
```

### 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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html).

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

* [Login With Amazon](https://developer.amazon.com/apps-and-games/login-with-amazon)
* [Facebook Login](https://developers.facebook.com/docs/facebook-login/)
* [Google Login](https://developers.google.com/identity/sign-in/web/sign-in)
* [Sign In With Apple](https://developer.apple.com/sign-in-with-apple/get-started/)
* [OpenID Connect](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-oidc-idp.html)

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.

```python
userpool = cognito.UserPool(self, "Pool")

provider = cognito.UserPoolIdentityProviderAmazon(self, "Amazon",
    client_id="amzn-client-id",
    client_secret="amzn-client-secret",
    user_pool=userpool
)
```

Attribute mapping allows mapping attributes provided by the third-party identity providers to [standard and custom
attributes](#Attributes) of the user pool. Learn more about [Specifying Identity Provider Attribute Mappings for Your
User Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html).

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

```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
        }
    )
)
```

### 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](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html) to learn more.

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

```python
pool = cognito.UserPool(self, "pool")
client = pool.add_client("customer-app-client")
client_id = client.user_pool_client_id
```

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 -

```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
)
```

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](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html).

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

```python
pool = cognito.UserPool(self, "pool")
pool.add_client("app-client",
    auth_flows=cognito.AuthFlow(
        user_password=True,
        user_srp=True
    )
)
```

Custom authentication protocols can be configured by setting the `custom` property under `authFlow` and defining lambda
functions for the corresponding user pool [triggers](#lambda-triggers). Learn more at [Custom Authentication
Flow](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-custom-authentication-flow).

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](https://tools.ietf.org/html/rfc6749) and [Cognito user pool's
implementation of
OAuth2.0](https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/).

The following code configures an app client with the authorization code grant flow and registers the 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](https://tools.ietf.org/html/rfc6749).

```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"]
    )
)
```

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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-managing-errors.html)
for the full details on the behavior of this flag.

```python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    prevent_user_existence_errors=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 -

```python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    # ...
    supported_identity_providers=[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.

```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)
```

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](https://docs.aws.amazon.com/en_us/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html).
The expiration time for these tokens can be configured as shown below.

```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)
)
```

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](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-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.

```python
pool = cognito.UserPool(self, "Pool")

client_write_attributes = (cognito.ClientAttributes()).with_standard_attributes(fullname=True, email=True).with_custom_attributes("favouritePizza", "favouriteBeverage")

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
)
```

[Token revocation](https://docs.aws.amazon.com/cognito/latest/developerguide/token-revocation.html)
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.

```python
pool = cognito.UserPool(self, "Pool")
pool.add_client("app-client",
    # ...
    enable_token_revocation=True
)
```

### 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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html)
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.

```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)]
    )
)
```

### Domains

After setting up an [app client](#app-clients), 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' -

```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
    )
)
```

Read more about [Using the Amazon Cognito
Domain](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain-prefix.html) and [Using Your Own
Domain](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-add-custom-domain.html).

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](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-integration.html#cognito-user-pools-create-an-app-integration).

```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"
)
```

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

```python
my_user_pool_domain = cognito.UserPoolDomain.from_domain_name(self, "my-user-pool-domain", "domain-name")
```



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aws/aws-cdk",
    "name": "aws-cdk.aws-cognito",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "~=3.7",
    "maintainer_email": "",
    "keywords": "",
    "author": "Amazon Web Services",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/36/60/64d5836618e9c5ae5c45274f88d66e9ab6eea52ca8c393fa98dc567d7b48/aws-cdk.aws-cognito-1.203.0.tar.gz",
    "platform": null,
    "description": "# Amazon Cognito Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\nFeatures                                   | Stability\n-------------------------------------------|--------------------------------------------------------\nCFN Resources                              | ![Stable](https://img.shields.io/badge/stable-success.svg?style=for-the-badge)\nHigher level constructs for User Pools     | ![Stable](https://img.shields.io/badge/stable-success.svg?style=for-the-badge)\nHigher level constructs for Identity Pools | ![Not Implemented](https://img.shields.io/badge/not--implemented-black.svg?style=for-the-badge)\n\n> **CFN Resources:** All classes with the `Cfn` prefix in this module ([CFN Resources](https://docs.aws.amazon.com/cdk/latest/guide/constructs.html#constructs_lib)) are always\n> stable and safe to use.\n\n<!-- -->\n\n> **Stable:** Higher level constructs in this module that are marked stable will not undergo any\n> breaking changes. They will strictly follow the [Semantic Versioning](https://semver.org/) model.\n\n---\n<!--END STABILITY BANNER-->\n\n[Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) provides\nauthentication, authorization, and user management for your web and mobile apps. Your users can sign in directly with a\nuser name and password, or through a third party such as Facebook, Amazon, Google or Apple.\n\nThe two main components of Amazon Cognito are [user\npools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) and [identity\npools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html). User pools are user directories\nthat provide sign-up and sign-in options for your app users. Identity pools enable you to grant your users access to\nother AWS services. Identity Pool L2 Constructs can be found [here](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cognito-identitypool-alpha-readme.html).\n\nThis module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.\n\n## Table of Contents\n\n* [User Pools](#user-pools)\n\n  * [Sign Up](#sign-up)\n  * [Sign In](#sign-in)\n  * [Attributes](#attributes)\n  * [Security](#security)\n\n    * [Multi-factor Authentication](#multi-factor-authentication-mfa)\n    * [Account Recovery Settings](#account-recovery-settings)\n  * [Emails](#emails)\n  * [Device Tracking](#device-tracking)\n  * [Lambda Triggers](#lambda-triggers)\n\n    * [Trigger Permissions](#trigger-permissions)\n  * [Import](#importing-user-pools)\n  * [Identity Providers](#identity-providers)\n  * [App Clients](#app-clients)\n  * [Resource Servers](#resource-servers)\n  * [Domains](#domains)\n\n## User Pools\n\nUser pools allow creating and managing your own directory of users that can sign up and sign in. They enable easy\nintegration with social identity providers such as Facebook, Google, Amazon, Microsoft Active Directory, etc. through\nSAML.\n\nUsing the CDK, a new user pool can be created as part of the stack using the construct's constructor. You may specify\nthe `userPoolName` to give your own identifier to the user pool. If not, CloudFormation will generate a name.\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    user_pool_name=\"myawesomeapp-userpool\"\n)\n```\n\nThe default set up for the user pool is configured such that only administrators will be allowed\nto create users. Features such as Multi-factor authentication (MFAs) and Lambda Triggers are not\nconfigured by default.\n\nUse the `grant()` method to add an IAM policy statement associated with the user pool to an\nIAM principal's policy.\n\n```python\nuser_pool = cognito.UserPool(self, \"myuserpool\")\nrole = iam.Role(self, \"role\",\n    assumed_by=iam.ServicePrincipal(\"foo\")\n)\nuser_pool.grant(role, \"cognito-idp:AdminCreateUser\")\n```\n\n### Sign Up\n\nUsers can either be signed up by the app's administrators or can sign themselves up. Once a user has signed up, their\naccount needs to be confirmed. Cognito provides several ways to sign users up and confirm their accounts. Learn more\nabout [user sign up here](https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html).\n\nWhen a user signs up, email and SMS messages are used to verify their account and contact methods. The following code\nsnippet configures a user pool with properties relevant to these verification messages -\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    self_sign_up_enabled=True,\n    user_verification=cognito.UserVerificationConfig(\n        email_subject=\"Verify your email for our awesome app!\",\n        email_body=\"Thanks for signing up to our awesome app! Your verification code is {####}\",\n        email_style=cognito.VerificationEmailStyle.CODE,\n        sms_message=\"Thanks for signing up to our awesome app! Your verification code is {####}\"\n    )\n)\n```\n\nBy default, self sign up is disabled. Learn more about [email and SMS verification messages\nhere](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-customizations.html).\n\nBesides users signing themselves up, an administrator of any user pool can sign users up. The user then receives an\ninvitation to join the user pool. The following code snippet configures a user pool with properties relevant to the\ninvitation messages -\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    user_invitation=cognito.UserInvitationConfig(\n        email_subject=\"Invite to join our awesome app!\",\n        email_body=\"Hello {username}, you have been invited to join our awesome app! Your temporary password is {####}\",\n        sms_message=\"Hello {username}, your temporary password for our awesome app is {####}\"\n    )\n)\n```\n\nAll email subjects, bodies and SMS messages for both invitation and verification support Cognito's message templating.\nLearn more about [message templates\nhere](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-templates.html).\n\n### Sign In\n\nUsers registering or signing in into your application can do so with multiple identifiers. There are 4 options\navailable:\n\n* `username`: Allow signing in using the one time immutable user name that the user chose at the time of sign up.\n* `email`: Allow signing in using the email address that is associated with the account.\n* `phone`: Allow signing in using the phone number that is associated with the account.\n* `preferredUsername`: Allow signing in with an alternate user name that the user can change at any time. However, this\n  is not available if the `username` option is not chosen.\n\nThe following code sets up a user pool so that the user can sign in with either their username or their email address -\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    # ...\n    sign_in_aliases=cognito.SignInAliases(\n        username=True,\n        email=True\n    )\n)\n```\n\nUser pools can either be configured so that user name is primary sign in form, but also allows for the other three to be\nused additionally; or it can be configured so that email and/or phone numbers are the only ways a user can register and\nsign in. Read more about this\n[here](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases-settings).\n\n\u26a0\ufe0f The Cognito service prevents changing the `signInAlias` property for an existing user pool.\n\nTo match with 'Option 1' in the above link, with a verified email, `signInAliases` should be set to\n`{ username: true, email: true }`. To match with 'Option 2' in the above link with both a verified\nemail and phone number, this property should be set to `{ email: true, phone: true }`.\n\nCognito recommends that email and phone number be automatically verified, if they are one of the sign in methods for\nthe user pool. Read more about that\n[here](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases).\nThe CDK does this by default, when email and/or phone number are specified as part of `signInAliases`. This can be\noverridden by specifying the `autoVerify` property.\n\nThe following code snippet sets up only email as a sign in alias, but both email and phone number to be auto-verified.\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    # ...\n    sign_in_aliases=cognito.SignInAliases(username=True, email=True),\n    auto_verify=cognito.AutoVerifiedAttrs(email=True, phone=True)\n)\n```\n\nA user pool can optionally ignore case when evaluating sign-ins. When `signInCaseSensitive` is false, Cognito will not\ncheck the capitalization of the alias when signing in. Default is true.\n\n### Attributes\n\nAttributes represent the various properties of each user that's collected and stored in the user pool. Cognito\nprovides a set of standard attributes that are available for all user pools. Users are allowed to select any of these\nstandard attributes to be required. Users will not be able to sign up to the user pool without providing the required\nattributes. Besides these, additional attributes can be further defined, and are known as custom attributes.\n\nLearn more on [attributes in Cognito's\ndocumentation](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html).\n\nThe following code configures a user pool with two standard attributes (name and address) as required and mutable, and adds\nfour custom attributes.\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    standard_attributes=cognito.StandardAttributes(\n        fullname=cognito.StandardAttribute(\n            required=True,\n            mutable=False\n        ),\n        address=cognito.StandardAttribute(\n            required=False,\n            mutable=True\n        )\n    ),\n    custom_attributes={\n        \"myappid\": cognito.StringAttribute(min_len=5, max_len=15, mutable=False),\n        \"callingcode\": cognito.NumberAttribute(min=1, max=3, mutable=True),\n        \"isEmployee\": cognito.BooleanAttribute(mutable=True),\n        \"joinedOn\": cognito.DateTimeAttribute()\n    }\n)\n```\n\nAs shown in the code snippet, there are data types that are available for custom attributes. The 'String' and 'Number'\ndata types allow for further constraints on their length and values, respectively.\n\nCustom attributes cannot be marked as required.\n\nAll custom attributes share the property `mutable` that specifies whether the value of the attribute can be changed.\nThe default value is `false`.\n\nUser pools come with two 'built-in' attributes - `email_verified` and `phone_number_verified`. These cannot be\nconfigured (required-ness or mutability) as part of user pool creation. However, user pool administrators can modify\nthem for specific users using the [AdminUpdateUserAttributes API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html).\n\n### Security\n\nCognito sends various messages to its users via SMS, for different actions, ranging from account verification to\nmarketing. In order to send SMS messages, Cognito needs an IAM role that it can assume, with permissions that allow it\nto send SMS messages.\n\nBy default, the CDK looks at all of the specified properties (and their defaults when not explicitly specified) and\nautomatically creates an SMS role, when needed. For example, if MFA second factor by SMS is enabled, the CDK will\ncreate a new role. The `smsRole` property can be used to specify the user supplied role that should be used instead.\nAdditionally, the property `enableSmsRole` can be used to override the CDK's default behaviour to either enable or\nsuppress automatic role creation.\n\n```python\npool_sms_role = iam.Role(self, \"userpoolsmsrole\",\n    assumed_by=iam.ServicePrincipal(\"foo\")\n)\n\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    sms_role=pool_sms_role,\n    sms_role_external_id=\"c87467be-4f34-11ea-b77f-2e728ce88125\"\n)\n```\n\nWhen the `smsRole` property is specified, the `smsRoleExternalId` may also be specified. The value of\n`smsRoleExternalId` will be used as the `sts:ExternalId` when the Cognito service assumes the role. In turn, the role's\nassume role policy should be configured to accept this value as the ExternalId. Learn more about [ExternalId\nhere](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html).\n\n#### Multi-factor Authentication (MFA)\n\nUser pools can be configured to enable multi-factor authentication (MFA). It can either be turned off, set to optional\nor made required. Setting MFA to optional means that individual users can choose to enable it.\nAdditionally, the MFA code can be sent either via SMS text message or via a time-based software token.\nSee the [documentation on MFA](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html) to\nlearn more.\n\nThe following code snippet marks MFA for the user pool as required. This means that all users are required to\nconfigure an MFA token and use it for sign in. It also allows for the users to use both SMS based MFA, as well,\n[time-based one time password\n(TOTP)](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-totp.html).\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    mfa=cognito.Mfa.REQUIRED,\n    mfa_second_factor=cognito.MfaSecondFactor(\n        sms=True,\n        otp=True\n    )\n)\n```\n\nUser pools can be configured with policies around a user's password. This includes the password length and the\ncharacter sets that they must contain.\n\nFurther to this, it can also be configured with the validity of the auto-generated temporary password. A temporary\npassword is generated by the user pool either when an admin signs up a user or when a password reset is requested.\nThe validity of this password dictates how long to give the user to use this password before expiring it.\n\nThe following code snippet configures these properties -\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    password_policy=cognito.PasswordPolicy(\n        min_length=12,\n        require_lowercase=True,\n        require_uppercase=True,\n        require_digits=True,\n        require_symbols=True,\n        temp_password_validity=Duration.days(3)\n    )\n)\n```\n\nNote that, `tempPasswordValidity` can be specified only in whole days. Specifying fractional days would throw an error.\n\n#### Account Recovery Settings\n\nUser pools can be configured on which method a user should use when recovering the password for their account. This\ncan either be email and/or SMS. Read more at [Recovering User Accounts](https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-recover-a-user-account.html)\n\n```python\ncognito.UserPool(self, \"UserPool\",\n    # ...\n    account_recovery=cognito.AccountRecovery.EMAIL_ONLY\n)\n```\n\nThe default for account recovery is by phone if available and by email otherwise.\nA user will not be allowed to reset their password via phone if they are also using it for MFA.\n\n### Emails\n\nCognito sends emails to users in the user pool, when particular actions take place, such as welcome emails, invitation\nemails, password resets, etc. The address from which these emails are sent can be configured on the user pool.\nRead more at [Email settings for User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html).\n\nBy default, user pools are configured to use Cognito's built in email capability, which will send emails\nfrom `no-reply@verificationemail.com`. If you want to use a custom email address you can configure\nCognito to send emails through Amazon SES, which is detailed below.\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    email=cognito.UserPoolEmail.with_cognito(\"support@myawesomeapp.com\")\n)\n```\n\nFor typical production environments, the default email limit is below the required delivery volume.\nTo enable a higher delivery volume, you can configure the UserPool to send emails through Amazon SES. To do\nso, follow the steps in the [Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html#user-pool-email-developer)\nto verify an email address, move the account out of the SES sandbox, and grant Cognito email permissions via an\nauthorization policy.\n\nOnce the SES setup is complete, the UserPool can be configured to use the SES email.\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    email=cognito.UserPoolEmail.with_sES(\n        from_email=\"noreply@myawesomeapp.com\",\n        from_name=\"Awesome App\",\n        reply_to=\"support@myawesomeapp.com\"\n    )\n)\n```\n\nSending emails through SES requires that SES be configured (as described above) in a valid SES region.\nIf the UserPool is being created in a different region, `sesRegion` must be used to specify the correct SES region.\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    email=cognito.UserPoolEmail.with_sES(\n        ses_region=\"us-east-1\",\n        from_email=\"noreply@myawesomeapp.com\",\n        from_name=\"Awesome App\",\n        reply_to=\"support@myawesomeapp.com\"\n    )\n)\n```\n\nWhen sending emails from an SES verified domain, `sesVerifiedDomain` can be used to specify the domain.\nThe 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.\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    email=cognito.UserPoolEmail.with_sES(\n        ses_region=\"us-east-1\",\n        from_email=\"noreply@myawesomeapp.com\",\n        from_name=\"Awesome App\",\n        reply_to=\"support@myawesomeapp.com\",\n        ses_verified_domain=\"myawesomeapp.com\"\n    )\n)\n```\n\n### Device Tracking\n\nUser pools can be configured to track devices that users have logged in to.\nRead more at [Device Tracking](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html)\n\n```python\ncognito.UserPool(self, \"myuserpool\",\n    # ...\n    device_tracking=cognito.DeviceTracking(\n        challenge_required_on_new_device=True,\n        device_only_remembered_on_user_prompt=True\n    )\n)\n```\n\nThe default is to not track devices.\n\n### Lambda Triggers\n\nUser pools can be configured such that AWS Lambda functions can be triggered when certain user operations or actions\noccur, such as, sign up, user confirmation, sign in, etc. They can also be used to add custom authentication\nchallenges, user migrations and custom verification messages. Learn more about triggers at [User Pool Workflows with\nTriggers](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html).\n\nLambda triggers can either be specified as part of the `UserPool` initialization, or it can be added later, via methods\non the construct, as so -\n\n```python\nauth_challenge_fn = lambda_.Function(self, \"authChallengeFn\",\n    runtime=lambda_.Runtime.NODEJS_14_X,\n    handler=\"index.handler\",\n    code=lambda_.Code.from_asset(path.join(__dirname, \"path/to/asset\"))\n)\n\nuserpool = cognito.UserPool(self, \"myuserpool\",\n    # ...\n    lambda_triggers=cognito.UserPoolTriggers(\n        create_auth_challenge=auth_challenge_fn\n    )\n)\n\nuserpool.add_trigger(cognito.UserPoolOperation.USER_MIGRATION, lambda_.Function(self, \"userMigrationFn\",\n    runtime=lambda_.Runtime.NODEJS_14_X,\n    handler=\"index.handler\",\n    code=lambda_.Code.from_asset(path.join(__dirname, \"path/to/asset\"))\n))\n```\n\nThe following table lists the set of triggers available, and their corresponding method to add it to the user pool.\nFor more information on the function of these triggers and how to configure them, read [User Pool Workflows with\nTriggers](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html).\n\n#### Trigger Permissions\n\nThe `function.attachToRolePolicy()` API can be used to add additional IAM permissions to the lambda trigger\nas necessary.\n\n\u26a0\ufe0f Using the `attachToRolePolicy` API to provide permissions to your user pool will result in a circular dependency. See [aws/aws-cdk#7016](https://github.com/aws/aws-cdk/issues/7016).\nError message when running `cdk synth` or `cdk deploy`:\n\n> Circular dependency between resources: [pool056F3F7E, fnPostAuthFnCognitoA630A2B1, ...]\n\nTo work around the circular dependency issue, use the `attachInlinePolicy()` API instead, as shown below.\n\n```python\n# post_auth_fn: lambda.Function\n\n\nuserpool = cognito.UserPool(self, \"myuserpool\",\n    lambda_triggers=cognito.UserPoolTriggers(\n        post_authentication=post_auth_fn\n    )\n)\n\n# provide permissions to describe the user pool scoped to the ARN the user pool\npost_auth_fn.role.attach_inline_policy(iam.Policy(self, \"userpool-policy\",\n    statements=[iam.PolicyStatement(\n        actions=[\"cognito-idp:DescribeUserPool\"],\n        resources=[userpool.user_pool_arn]\n    )]\n))\n```\n\n### Importing User Pools\n\nAny user pool that has been created outside of this stack, can be imported into the CDK app. Importing a user pool\nallows for it to be used in other parts of the CDK app that reference an `IUserPool`. However, imported user pools have\nlimited configurability. As a rule of thumb, none of the properties that are part of the\n[`AWS::Cognito::UserPool`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html)\nCloudFormation resource can be configured.\n\nUser pools can be imported either using their id via the `UserPool.fromUserPoolId()`, or by using their ARN, via the\n`UserPool.fromUserPoolArn()` API.\n\n```python\nawesome_pool = cognito.UserPool.from_user_pool_id(self, \"awesome-user-pool\", \"us-east-1_oiuR12Abd\")\n\nother_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\")\n```\n\n### Identity Providers\n\nUsers that are part of a user pool can sign in either directly through a user pool, or federate through a third-party\nidentity provider. Once configured, the Cognito backend will take care of integrating with the third-party provider.\nRead more about [Adding User Pool Sign-in Through a Third\nParty](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html).\n\nThe following third-party identity providers are currently supported in the CDK -\n\n* [Login With Amazon](https://developer.amazon.com/apps-and-games/login-with-amazon)\n* [Facebook Login](https://developers.facebook.com/docs/facebook-login/)\n* [Google Login](https://developers.google.com/identity/sign-in/web/sign-in)\n* [Sign In With Apple](https://developer.apple.com/sign-in-with-apple/get-started/)\n* [OpenID Connect](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-oidc-idp.html)\n\nThe following code configures a user pool to federate with the third party provider, 'Login with Amazon'. The identity\nprovider needs to be configured with a set of credentials that the Cognito backend can use to federate with the\nthird-party identity provider.\n\n```python\nuserpool = cognito.UserPool(self, \"Pool\")\n\nprovider = cognito.UserPoolIdentityProviderAmazon(self, \"Amazon\",\n    client_id=\"amzn-client-id\",\n    client_secret=\"amzn-client-secret\",\n    user_pool=userpool\n)\n```\n\nAttribute mapping allows mapping attributes provided by the third-party identity providers to [standard and custom\nattributes](#Attributes) of the user pool. Learn more about [Specifying Identity Provider Attribute Mappings for Your\nUser Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html).\n\nThe following code shows how different attributes provided by 'Login With Amazon' can be mapped to standard and custom\nuser pool attributes.\n\n```python\nuserpool = cognito.UserPool(self, \"Pool\")\n\ncognito.UserPoolIdentityProviderAmazon(self, \"Amazon\",\n    client_id=\"amzn-client-id\",\n    client_secret=\"amzn-client-secret\",\n    user_pool=userpool,\n    attribute_mapping=cognito.AttributeMapping(\n        email=cognito.ProviderAttribute.AMAZON_EMAIL,\n        website=cognito.ProviderAttribute.other(\"url\"),  # use other() when an attribute is not pre-defined in the CDK\n        custom={\n            # custom user pool attributes go here\n            \"unique_id\": cognito.ProviderAttribute.AMAZON_USER_ID\n        }\n    )\n)\n```\n\n### App Clients\n\nAn app is an entity within a user pool that has permission to call unauthenticated APIs (APIs that do not have an\nauthenticated user), such as APIs to register, sign in, and handle forgotten passwords. To call these APIs, you need an\napp client ID and an optional client secret. Read [Configuring a User Pool App\nClient](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html) to learn more.\n\nThe following code creates an app client and retrieves the client id -\n\n```python\npool = cognito.UserPool(self, \"pool\")\nclient = pool.add_client(\"customer-app-client\")\nclient_id = client.user_pool_client_id\n```\n\nExisting app clients can be imported into the CDK app using the `UserPoolClient.fromUserPoolClientId()` API. For new\nand imported user pools, clients can also be created via the `UserPoolClient` constructor, as so -\n\n```python\nimported_pool = cognito.UserPool.from_user_pool_id(self, \"imported-pool\", \"us-east-1_oiuR12Abd\")\ncognito.UserPoolClient(self, \"customer-app-client\",\n    user_pool=imported_pool\n)\n```\n\nClients can be configured with authentication flows. Authentication flows allow users on a client to be authenticated\nwith a user pool. Cognito user pools provide several different types of authentication, such as, SRP (Secure\nRemote Password) authentication, username-and-password authentication, etc. Learn more about this at [UserPool Authentication\nFlow](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html).\n\nThe following code configures a client to use both SRP and username-and-password authentication -\n\n```python\npool = cognito.UserPool(self, \"pool\")\npool.add_client(\"app-client\",\n    auth_flows=cognito.AuthFlow(\n        user_password=True,\n        user_srp=True\n    )\n)\n```\n\nCustom authentication protocols can be configured by setting the `custom` property under `authFlow` and defining lambda\nfunctions for the corresponding user pool [triggers](#lambda-triggers). Learn more at [Custom Authentication\nFlow](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-custom-authentication-flow).\n\nIn addition to these authentication mechanisms, Cognito user pools also support using OAuth 2.0 framework for\nauthenticating users. User pool clients can be configured with OAuth 2.0 authorization flows and scopes. Learn more\nabout the [OAuth 2.0 authorization framework](https://tools.ietf.org/html/rfc6749) and [Cognito user pool's\nimplementation of\nOAuth2.0](https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/).\n\nThe following code configures an app client with the authorization code grant flow and registers the the app's welcome\npage as a callback (or redirect) URL. It also configures the access token scope to 'openid'. All of these concepts can\nbe found in the [OAuth 2.0 RFC](https://tools.ietf.org/html/rfc6749).\n\n```python\npool = cognito.UserPool(self, \"Pool\")\npool.add_client(\"app-client\",\n    o_auth=cognito.OAuthSettings(\n        flows=cognito.OAuthFlows(\n            authorization_code_grant=True\n        ),\n        scopes=[cognito.OAuthScope.OPENID],\n        callback_urls=[\"https://my-app-domain.com/welcome\"],\n        logout_urls=[\"https://my-app-domain.com/signin\"]\n    )\n)\n```\n\nAn app client can be configured to prevent user existence errors. This\ninstructs the Cognito authentication API to return generic authentication\nfailure responses instead of an UserNotFoundException. By default, the flag\nis not set, which means the CloudFormation default (false) will be used. See the\n[documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-managing-errors.html)\nfor the full details on the behavior of this flag.\n\n```python\npool = cognito.UserPool(self, \"Pool\")\npool.add_client(\"app-client\",\n    prevent_user_existence_errors=True\n)\n```\n\nAll identity providers created in the CDK app are automatically registered into the corresponding user pool. All app\nclients created in the CDK have all of the identity providers enabled by default. The 'Cognito' identity provider,\nthat allows users to register and sign in directly with the Cognito user pool, is also enabled by default.\nAlternatively, the list of supported identity providers for a client can be explicitly specified -\n\n```python\npool = cognito.UserPool(self, \"Pool\")\npool.add_client(\"app-client\",\n    # ...\n    supported_identity_providers=[cognito.UserPoolClientIdentityProvider.AMAZON, cognito.UserPoolClientIdentityProvider.COGNITO\n    ]\n)\n```\n\nIf the identity provider and the app client are created in the same stack, specify the dependency between both constructs to\nmake sure that the identity provider already exists when the app client will be created. The app client cannot handle the\ndependency to the identity provider automatically because the client does not have access to the provider's construct.\n\n```python\npool = cognito.UserPool(self, \"Pool\")\nprovider = cognito.UserPoolIdentityProviderAmazon(self, \"Amazon\",\n    user_pool=pool,\n    client_id=\"amzn-client-id\",\n    client_secret=\"amzn-client-secret\"\n)\n\nclient = pool.add_client(\"app-client\",\n    # ...\n    supported_identity_providers=[cognito.UserPoolClientIdentityProvider.AMAZON\n    ]\n)\n\nclient.node.add_dependency(provider)\n```\n\nIn accordance with the OIDC open standard, Cognito user pool clients provide access tokens, ID tokens and refresh tokens.\nMore information is available at [Using Tokens with User Pools](https://docs.aws.amazon.com/en_us/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html).\nThe expiration time for these tokens can be configured as shown below.\n\n```python\npool = cognito.UserPool(self, \"Pool\")\npool.add_client(\"app-client\",\n    # ...\n    access_token_validity=Duration.minutes(60),\n    id_token_validity=Duration.minutes(60),\n    refresh_token_validity=Duration.days(30)\n)\n```\n\nClients can (and should) be allowed to read and write relevant user attributes only. Usually every client can be allowed to\nread the `given_name` attribute but not every client should be allowed to set the `email_verified` attribute.\nThe same criteria applies for both standard and custom attributes, more info is available at\n[Attribute Permissions and Scopes](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-attribute-permissions-and-scopes).\nThe default behaviour is to allow read and write permissions on all attributes. The following code shows how this can be\nconfigured for a client.\n\n```python\npool = cognito.UserPool(self, \"Pool\")\n\nclient_write_attributes = (cognito.ClientAttributes()).with_standard_attributes(fullname=True, email=True).with_custom_attributes(\"favouritePizza\", \"favouriteBeverage\")\n\nclient_read_attributes = client_write_attributes.with_standard_attributes(email_verified=True).with_custom_attributes(\"pointsEarned\")\n\npool.add_client(\"app-client\",\n    # ...\n    read_attributes=client_read_attributes,\n    write_attributes=client_write_attributes\n)\n```\n\n[Token revocation](https://docs.aws.amazon.com/cognito/latest/developerguide/token-revocation.html)\ncan be configured to be able to revoke refresh tokens in app clients. By default, token revocation is enabled for new user\npools. The property can be used to enable the token revocation in existing app clients or to change the default behavior.\n\n```python\npool = cognito.UserPool(self, \"Pool\")\npool.add_client(\"app-client\",\n    # ...\n    enable_token_revocation=True\n)\n```\n\n### Resource Servers\n\nA resource server is a server for access-protected resources. It handles authenticated requests from an app that has an\naccess token. See [Defining Resource\nServers](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html)\nfor more information.\n\nAn application may choose to model custom permissions via OAuth. Resource Servers provide this capability via custom scopes\nthat are attached to an app client. The following example sets up a resource server for the 'users' resource for two different\napp clients and configures the clients to use these scopes.\n\n```python\npool = cognito.UserPool(self, \"Pool\")\n\nread_only_scope = cognito.ResourceServerScope(scope_name=\"read\", scope_description=\"Read-only access\")\nfull_access_scope = cognito.ResourceServerScope(scope_name=\"*\", scope_description=\"Full access\")\n\nuser_server = pool.add_resource_server(\"ResourceServer\",\n    identifier=\"users\",\n    scopes=[read_only_scope, full_access_scope]\n)\n\nread_only_client = pool.add_client(\"read-only-client\",\n    # ...\n    o_auth=cognito.OAuthSettings(\n        # ...\n        scopes=[cognito.OAuthScope.resource_server(user_server, read_only_scope)]\n    )\n)\n\nfull_access_client = pool.add_client(\"full-access-client\",\n    # ...\n    o_auth=cognito.OAuthSettings(\n        # ...\n        scopes=[cognito.OAuthScope.resource_server(user_server, full_access_scope)]\n    )\n)\n```\n\n### Domains\n\nAfter setting up an [app client](#app-clients), the address for the user pool's sign-up and sign-in webpages can be\nconfigured using domains. There are two ways to set up a domain - either the Amazon Cognito hosted domain can be chosen\nwith an available domain prefix, or a custom domain name can be chosen. The custom domain must be one that is already\nowned, and whose certificate is registered in AWS Certificate Manager.\n\nThe following code sets up a user pool domain in Amazon Cognito hosted domain with the prefix 'my-awesome-app', and\nanother domain with the custom domain 'user.myapp.com' -\n\n```python\npool = cognito.UserPool(self, \"Pool\")\n\npool.add_domain(\"CognitoDomain\",\n    cognito_domain=cognito.CognitoDomainOptions(\n        domain_prefix=\"my-awesome-app\"\n    )\n)\n\ncertificate_arn = \"arn:aws:acm:us-east-1:123456789012:certificate/11-3336f1-44483d-adc7-9cd375c5169d\"\n\ndomain_cert = certificatemanager.Certificate.from_certificate_arn(self, \"domainCert\", certificate_arn)\npool.add_domain(\"CustomDomain\",\n    custom_domain=cognito.CustomDomainOptions(\n        domain_name=\"user.myapp.com\",\n        certificate=domain_cert\n    )\n)\n```\n\nRead more about [Using the Amazon Cognito\nDomain](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain-prefix.html) and [Using Your Own\nDomain](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-add-custom-domain.html).\n\nThe `signInUrl()` methods returns the fully qualified URL to the login page for the user pool. This page comes from the\nhosted UI configured with Cognito. Learn more at [Hosted UI with the Amazon Cognito\nConsole](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-integration.html#cognito-user-pools-create-an-app-integration).\n\n```python\nuserpool = cognito.UserPool(self, \"UserPool\")\nclient = userpool.add_client(\"Client\",\n    # ...\n    o_auth=cognito.OAuthSettings(\n        flows=cognito.OAuthFlows(\n            implicit_code_grant=True\n        ),\n        callback_urls=[\"https://myapp.com/home\", \"https://myapp.com/users\"\n        ]\n    )\n)\ndomain = userpool.add_domain(\"Domain\")\nsign_in_url = domain.sign_in_url(client,\n    redirect_uri=\"https://myapp.com/home\"\n)\n```\n\nExisting domains can be imported into CDK apps using `UserPoolDomain.fromDomainName()` API\n\n```python\nmy_user_pool_domain = cognito.UserPoolDomain.from_domain_name(self, \"my-user-pool-domain\", \"domain-name\")\n```\n\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "The CDK Construct Library for AWS::Cognito",
    "version": "1.203.0",
    "project_urls": {
        "Homepage": "https://github.com/aws/aws-cdk",
        "Source": "https://github.com/aws/aws-cdk.git"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "85e0bde673dba72c008035fafba9ead1f1af2bf866a76458730646f133d09cff",
                "md5": "e3c599521c45a8b7247f10814e92491a",
                "sha256": "c631cdb199eaaf149bcc18b8ce2b36ae39f9a8e9fa07b95fb0c5ce1274522af5"
            },
            "downloads": -1,
            "filename": "aws_cdk.aws_cognito-1.203.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e3c599521c45a8b7247f10814e92491a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.7",
            "size": 602793,
            "upload_time": "2023-05-31T22:53:52",
            "upload_time_iso_8601": "2023-05-31T22:53:52.448474Z",
            "url": "https://files.pythonhosted.org/packages/85/e0/bde673dba72c008035fafba9ead1f1af2bf866a76458730646f133d09cff/aws_cdk.aws_cognito-1.203.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "366064d5836618e9c5ae5c45274f88d66e9ab6eea52ca8c393fa98dc567d7b48",
                "md5": "d610fbd6ccb18ff2659e58a1b4f9913f",
                "sha256": "09ab6ecfc77293666d2cdbb96b800c144fe43750237c07fd15acab2db0671ae8"
            },
            "downloads": -1,
            "filename": "aws-cdk.aws-cognito-1.203.0.tar.gz",
            "has_sig": false,
            "md5_digest": "d610fbd6ccb18ff2659e58a1b4f9913f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.7",
            "size": 622042,
            "upload_time": "2023-05-31T23:01:34",
            "upload_time_iso_8601": "2023-05-31T23:01:34.753621Z",
            "url": "https://files.pythonhosted.org/packages/36/60/64d5836618e9c5ae5c45274f88d66e9ab6eea52ca8c393fa98dc567d7b48/aws-cdk.aws-cognito-1.203.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-31 23:01:34",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aws",
    "github_project": "aws-cdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aws-cdk.aws-cognito"
}
        
Elapsed time: 0.39404s