

# Amazon Cognito user pools
<a name="cognito-user-pools"></a>

An Amazon Cognito user pool is a user directory for web and mobile app authentication and authorization. From the perspective of your app, an Amazon Cognito user pool is an OpenID Connect (OIDC) identity provider (IdP). A user pool adds layers of additional features for security, identity federation, app integration, and customization of the user experience.

You can, for example, verify that your users’ sessions are from trusted sources. You can combine the Amazon Cognito directory with an external identity provider. With your preferred AWS SDK, you can choose the API authorization model that works best for your app. And you can add AWS Lambda functions that modify or overhaul the default behavior of Amazon Cognito.

![\[A diagram with a high-level overview of how user pools work. Clients can sign in with applications build using an AWS SDK or with the OIDC IdP built in to user pools. User pools also unify sign-in processes for multiple social, OpenID Connect, and SAML 2.0 identity providers.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-cup.png)


**Topics**
+ [

## Features
](#cognito-user-pools-features)
+ [

# User pool feature plans
](cognito-sign-in-feature-plans.md)
+ [

# Security best practices for Amazon Cognito user pools
](user-pool-security-best-practices.md)
+ [

# Authentication with Amazon Cognito user pools
](authentication.md)
+ [

# User pool sign-in with third party identity providers
](cognito-user-pools-identity-federation.md)
+ [

# User pool managed login
](cognito-user-pools-managed-login.md)
+ [

# Customizing user pool workflows with Lambda triggers
](cognito-user-pools-working-with-lambda-triggers.md)
+ [

# Managing users in your user pool
](managing-users.md)
+ [

# Understanding user pool JSON web tokens (JWTs)
](amazon-cognito-user-pools-using-tokens-with-identity-providers.md)
+ [

# Accessing resources after successful sign-in
](accessing-resources.md)
+ [

# Scopes, M2M, and resource servers
](cognito-user-pools-define-resource-servers.md)
+ [

# Configure user pool features
](user-pools-configure-features.md)
+ [

# Using Amazon Cognito user pools security features
](managing-security.md)
+ [

# User pool endpoints and managed login reference
](cognito-userpools-server-contract-reference.md)

## Features
<a name="cognito-user-pools-features"></a>

Amazon Cognito user pools have the following features.

### Sign-up
<a name="cognito-user-pools-sign-up"></a>

Amazon Cognito user pools have user-driven, administrator-driven, and programmatic methods to add user profiles to your user pool. Amazon Cognito user pools supports the following sign-up models. You can use any combination of these models in your app.

**Important**  
If you activate user sign-up in your user pool, anyone on the internet can sign up for an account and sign into your apps. Don't enable self-registration in your user pool unless you want to open your app to public sign-up. To change this setting, update **Self-service sign-up** in the **Sign-up** menu under **Authentication** in the user pool console, or update the value of [ AllowAdminCreateUserOnly](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUserConfigType.html#CognitoUserPools-Type-AdminCreateUserConfigType-AllowAdminCreateUserOnly) in a [ CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [ UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request.  
For information about security features that you can set up in your user pools, see [Using Amazon Cognito user pools security features](managing-security.md).

1. Your users can enter their information in your app and create a user profile that’s native to your user pool. You can call API sign-up operations to register users in your user pool. You can open these sign-up operations to anyone, or you can authorize them with a client secret or AWS credentials.

1. You can redirect users to a third-party IdP that they can authorize to pass their information to Amazon Cognito. Amazon Cognito processes OIDC id tokens, OAuth 2.0 `userInfo` data, and SAML 2.0 assertions into user profiles in your user pool. You control the attributes that you want Amazon Cognito to receive based on attribute-mapping rules.

1. You can skip public or federated sign-up, and create users based on your own data source and schema. Add users directly in the Amazon Cognito console or API. Import users from a CSV file. Run a just-in-time AWS Lambda function that looks up your new user in an existing directory, and populates their user profile from existing data.

After your users sign up, you can add them to groups that Amazon Cognito lists in the access and ID tokens. You can also link user pool groups to IAM roles when you pass the ID token to an identity pool.

**Related topics**
+ [Managing users in your user pool](managing-users.md)
+ [Understanding API, OIDC, and managed login pages authentication](authentication-flows-public-server-side.md#user-pools-API-operations)
+ [Code examples for Amazon Cognito Identity Provider using AWS SDKs](service_code_examples_cognito-identity-provider.md)

### Sign-in
<a name="cognito-user-pools-sign-in"></a>

Amazon Cognito can be a standalone user directory and identity provider (IdP) to your app. Your users can sign in with managed login pages that are hosted by Amazon Cognito, or with a custom-built user authentication service through the Amazon Cognito user pools API. The application tier behind your custom-built front end can authorize requests on the back end with any of several methods to confirm legitimate requests.

Users can set up and sign with usernames and passwords, passkeys, and email and SMS message one-time passwords. You can offer consolidate sign in with external user directories, multi-factor authentication (MFA) after sign-in, trust remembered devices, and custom authentication flows that you design.

To sign in users with an external directory, optionally combined with the user directory built in to Amazon Cognito, you can add the following integrations.

1. Sign in and import customer user data with OAuth 2.0 social sign-in. Amazon Cognito supports sign-in with Google, Facebook, Amazon, and Apple through OAuth 2.0. 

1. Sign in and import work and school user data with SAML and OIDC sign-in. You can also configure Amazon Cognito to accept claims from any SAML or OpenID Connect (OIDC) identity provider (IdP). 

1.  Link external user profiles to native user profiles. A linked user can sign in with a third-party user identity and receive access that you assign to a user in the built-in directory.

**Related topics**
+ [User pool sign-in with third party identity providers](cognito-user-pools-identity-federation.md)
+ [Linking federated users to an existing user profile](cognito-user-pools-identity-federation-consolidate-users.md)

**Machine-to-machine authorization**  
Some sessions aren’t a human-to-machine interaction. You might need a service account that can authorize a request to an API by an automated process. To generate access tokens for machine-to-machine authorization with OAuth 2.0 scopes, you can add an app client that generates [client-credentials grants](https://www.rfc-editor.org/rfc/rfc6749#section-4.4).

**Related topics**
+ [Scopes, M2M, and resource servers](cognito-user-pools-define-resource-servers.md)

### Managed login
<a name="cognito-user-pools-hosted-ui"></a>

When you don’t want to build a user interface, you can present your users with a customized managed login pages. Managed login is a set of web pages for sign-up, sign-in, multi-factor authentication (MFA), and password reset. You can add managed login to your existing domain, or use a prefix identifier in an AWS subdomain.

**Related topics**
+ [User pool managed login](cognito-user-pools-managed-login.md)
+ [Configuring a user pool domain](cognito-user-pools-assign-domain.md)

### Security
<a name="cognito-user-pools-security"></a>

Your local users can provide an additional authentication factor with a code from an SMS or email message, or an app that generates multi-factor authentication (MFA) codes. You can build mechanisms to set up and process MFA in your application, or you can let managed login manage it. Amazon Cognito user pools can bypass MFA when your users sign in from trusted devices.

If you don’t want to initially require MFA from your users, you can require it conditionally. With adaptive authentication, Amazon Cognito can detect potential malicious activity and require your user to set up MFA, or block sign-in.

If network traffic to your user pool might be malicious, you can monitor it and take action with AWS WAF web ACLs.

**Related topics**
+ [Adding MFA to a user pool](user-pool-settings-mfa.md)
+ [Advanced security with threat protection](cognito-user-pool-settings-threat-protection.md)
+ [Associate an AWS WAF web ACL with a user pool](user-pool-waf.md)

### Custom user experience
<a name="cognito-user-pools-custom-user-experience"></a>

At most stages of a user’s sign-up, sign-in, or profile update, you can customize how Amazon Cognito handles the request. With Lambda triggers, you can modify an ID token or reject a sign-up request based on custom conditions. You can create your own custom authentication flow.

You can upload custom CSS and logos to give managed login a familiar look and feel to your users.

**Related topics**
+ [Customizing user pool workflows with Lambda triggers](cognito-user-pools-working-with-lambda-triggers.md)
+ [Custom authentication challenge Lambda triggers](user-pool-lambda-challenge.md)
+ [Apply branding to managed login pages](managed-login-branding.md)

### Monitoring and analytics
<a name="cognito-user-pools-monitoring-and-analytics"></a>

Amazon Cognito user pools log API requests, including requests to managed login, to AWS CloudTrail. You can review performance metrics in Amazon CloudWatch Logs, push custom logs to CloudWatch with Lambda triggers, monitor email and SMS message delivery, and monitor API request volume in the Service Quotas console.

With the Plus [feature plan](cognito-sign-in-feature-plans.md), you can monitor user authentication attempts for indicators of compromise with automated-learning technology and immediately remediate risks. These advanced security features also log user activity to your user pool and optionally, to Amazon S3, CloudWatch Logs, or Amazon Data Firehose.

You can also log device and session data from your API requests to an Amazon Pinpoint campaign. With Amazon Pinpoint, you can send push notifications from your app based on your analysis of user activity.

**Related topics**
+ [Amazon Cognito logging in AWS CloudTrail](logging-using-cloudtrail.md)
+ [Tracking quotas and usage in CloudWatch and Service Quotas](tracking-quotas-and-usage-in-cloud-watch-and-service-quotas.md)
+ [Exporting logs from Amazon Cognito user pools](exporting-quotas-and-usage.md)
+ [Using Amazon Pinpoint for user pool analytics](cognito-user-pools-pinpoint-integration.md)

### Amazon Cognito identity pools integration
<a name="cognito-user-pools-identity-pools-integration"></a>

The other half of Amazon Cognito is identity pools. Identity pools provide credentials that authorize and monitor API requests to AWS services, for example Amazon DynamoDB or Amazon S3, from your users. You can build identity-based access policies that protect your data based on how you classify the users in your user pool. Identity pools can also accept tokens and SAML 2.0 assertions from a variety of identity providers, independently of user pool authentication.

**Related topics**
+ [Accessing AWS services using an identity pool after sign-in](amazon-cognito-integrating-user-pools-with-identity-pools.md)
+ [Amazon Cognito identity pools](cognito-identity.md)

# User pool feature plans
<a name="cognito-sign-in-feature-plans"></a>

Understanding the cost is a crucial step in preparing to implement Amazon Cognito user pools authentication. Amazon Cognito has feature plans for user pools. Each plan has a set of features and a monthly cost per active user. Each feature plan unlocks access to more features than the one before it.

User pools have a variety of features that you can turn on and off. For example, you can turn on multi-factor authentication (MFA) and turn off sign-in with third-party identity providers (IdPs). Some changes require you to switch your feature plan. The following characteristics of your user pool determine the cost that AWS bills you monthly for usage.
+ The features that you choose
+ The requests per second that your application makes to the user pools API
+ The number of users with authentication, update, or query activity in a month, also called [monthly active users](quotas.md#monthly-active-users) or MAUs
+ The number of monthly active users from third-party SAML 2.0 or OpenID Connect (OIDC) IdPs
+ The number of app clients and user pools that do client-credentials grants for machine-to-machine authorization

For the most current information about user pool pricing, see [Amazon Cognito pricing](https://aws.amazon.com/cognito/pricing).

Feature-plan selections apply to one user pool. Different user pools in the same AWS account can have different plan selections. You can't apply separate feature plans to app clients within a user pool. The default plan selection for new user pools is Essentials.

You can switch between feature plans at any time to fit the requirements of your applications. Some changes between plans require that you turn off active features. For more information, see [Turning off features to change feature plans](feature-plans-deactivate.md).User pool feature plans

**Lite**  
Lite is a low-cost feature plan for user pools with lower numbers of monthly active users. This plan is sufficient for user directories with basic authentication features. It includes sign-in features and the classic hosted UI, a slimmer, less-customizable predecessor to managed login. Many newer features, like access-token customization and passkey authentication, aren't included in the Lite plan.

**Essentials**  
Essentials has all of the latest user pool authentication features. This plan adds new options to your applications, whether your login pages are managed login or custom-built. Essentials has advanced authentication features like [choice-based sign-in](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) and [email MFA](user-pool-settings-mfa-sms-email-message.md).

**Plus**  
Plus includes everything in the Essentials plan and adds advanced security features that protect your users. Monitor user sign-in, sign-up, and password-management requests for indicators of compromise. For example, user pools can detect whether users are signing in from an unexpected location or using a password that's been part of a public breach.  
User pools with the Plus plan generate logs of user activity details and risk evaluations. You can apply your own usage and security analysis to these logs when you export them to external services.

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

**Topics**
+ [

## Select a feature plan
](#cognito-sign-in-feature-plans-choose)
+ [

## Features by plan
](#cognito-sign-in-feature-plans-list)
+ [

# Essentials plan features
](feature-plans-features-essentials.md)
+ [

# Plus plan features
](feature-plans-features-plus.md)
+ [

# Turning off features to change feature plans
](feature-plans-deactivate.md)

## Select a feature plan
<a name="cognito-sign-in-feature-plans-choose"></a>

------
#### [ AWS Management Console ]

To choose a feature plan

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or create a user pool.

1. Select the **Settings** menu and review the **Feature plans** tab.

1. Review the features available to you in the Lite, Esssentials, and Plus plans.

1. To change your plan, select **Switch to Essentials**, or **Switch to Plus**. To switch to the **Lite** plan, choose **Other plans**, then **Compare with Lite**.

1. On the next screen, review your choice and select **Confirm**.

------
#### [ CLI/API/SDK ]

The [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) and [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) operations set your feature plan in the `UserPoolTier` parameter. When you don't specify a value for `UserPoolTier`, your user pool defaults to `Essentials`. If you set `AdvancedSecurityMode` to `AUDIT` or `ENFORCED`, your user pool tier must be `PLUS` and default to `PLUS` when not specified.

See [Examples in CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#API_CreateUserPool_Examples) for syntax. See [See Also in CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#API_CreateUserPool_SeeAlso) for links to this function in of AWS SDKs for a variety of programming languages.

```
"UserPoolTier": "PLUS"
```

In the AWS CLI, this option is `--user-pool-tier` argument.

```
--user-pool-tier PLUS
```

See [create-user-pool](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool.html) and [update-user-pool](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool.html) in the AWS CLI command reference for more information.

------

## Features by plan
<a name="cognito-sign-in-feature-plans-list"></a>


**Features and plans in user pools**  

| Feature | Description | Feature plan | 
| --- | --- | --- | 
| Protect against unsafe passwords | Check plaintext passwords for indicators of compromise at runtime | Plus | 
| Protect against malicious sign-in attempts | Check session properties for indicators of compromise at runtime | Plus | 
| Log and analyze user activity | Generate logs of user authentication session properties and risk scores | Plus | 
| Export user activity logs | Push user session and risk logs to an external AWS service | Plus | 
| Customize managed login pages with a visual editor | Use a visual editor in the Amazon Cognito console to apply branding and style to your managed login pages | Essentials \$1 Plus | 
| MFA with email one-time codes | Request or require local users to provide an additional email message sign-in factor after username authentication | Essentials \$1 Plus | 
| Customize access token scopes and claims at runtime | Use a Lambda trigger to extend the authorization capabilities of user pool access tokens | Essentials \$1 Plus | 
| Passwordless sign-in with one-time codes | Permit users to receive a one-time password by email or SMS as their first authentication factor | Essentials \$1 Plus | 
| Passkey sign-in with hardware or software FIDO2 authenticators | Permit users to use a cryptographic key stored on a FIDO2 authenticator as their first authentication factor | Essentials \$1 Plus | 
| Sign-up and sign-in | Perform authentication operations and let new users register for an account in your application. | Lite \$1 Essentials \$1 Plus | 
| User groups | Create logical groupings of users and assign default IAM roles for identity pool operations. | Lite \$1 Essentials \$1 Plus | 
| Sign-in with social, SAML, and OIDC providers | Provide users with the options to sign in directly or with their preferred provider. | Lite \$1 Essentials \$1 Plus | 
| OAuth 2.0/OIDC authorization server | Act as a OIDC issuer. | Lite \$1 Essentials \$1 Plus | 
| Login pages | A hosted collection of webpages for authentication. Managed login is available in the Essentials and Plus tiers. The classic hosted UI is available in all feature tiers. | Lite \$1 Essentials \$1 Plus | 
| Password, custom, refresh-token, and SRP authentication | Prompt users for a username and password in your application. | Lite \$1 Essentials \$1 Plus | 
| Machine-to-machine (M2M) with client credentials | Issue access tokens for authorization of non-human entities. | Lite \$1 Essentials \$1 Plus | 
| API authorization with resource servers | Issue access tokens with custom scopes that authorize access to external systems. | Lite \$1 Essentials \$1 Plus | 
| User import | Set up import jobs from CSV files and perform just-in-time migration of users as they sign in. | Lite \$1 Essentials \$1 Plus | 
| MFA with authenticator apps and SMS one-time codes | Request or require local users to provide an additional SMS message or authenticator app sign-in factor after username authentication | Lite \$1 Essentials \$1 Plus | 
| Customize ID token scopes and claims at runtime | Use a Lambda trigger to extend the authentication capabilities of user pool identity (ID) tokens | Lite \$1 Essentials \$1 Plus | 
| Custom runtime actions with Lambda triggers | Customize the sign-in process at runtime with Lambda functions that perform external actions and influence authentication | Lite \$1 Essentials \$1 Plus | 
| Customize managed login pages with CSS | Download a CSS template and change some styles in your managed login pages | Lite \$1 Essentials \$1 Plus | 

# Essentials plan features
<a name="feature-plans-features-essentials"></a>

The Essentials feature plan has most of the best and latest features of Amazon Cognito user pools. When you switch from the Lite to the Essentials plan, you get new features for your managed login pages, multi-factor authentication with email-message one-time passwords, an enhanced password policy, and custom access tokens. To stay up-to-date with new user pool features, choose the Essentials plan for your user pools.

The sections that follows present a brief overview of the features that you can add to your application with the Essentials plan. For detailed information, see the following pages.

**Additional resources**
+ Access token customization: [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md)
+ Email MFA: [SMS and email message MFA](user-pool-settings-mfa-sms-email-message.md)
+ Password history: [Passwords, account recovery, and password policies](managing-users-passwords.md)
+ Enhanced UI: [Apply branding to managed login pages](managed-login-branding.md)

**Topics**
+ [

## Access token customization
](#features-access-token-customization)
+ [

## Email MFA
](#features-email-mfa)
+ [

## Password reuse prevention
](#features-password-reuse)
+ [

## Managed login hosted sign-in and authorization server
](#features-enhanced-ui)
+ [

## Choice-based authentication
](#features-user-auth)

## Access token customization
<a name="features-access-token-customization"></a>

User pool [access tokens](https://datatracker.ietf.org/doc/html/rfc6749#section-1.4) grant permissions to applications: to [access an API](cognito-user-pools-define-resource-servers.md), to retrieve user attributes from the [userInfo endpoint](userinfo-endpoint.md), or to establish [group membership](cognito-user-pools-user-groups.md) for an external system. In advanced scenarios, you might want to add to the default access-token data from the user pool directory with additional temporary parameters that your application determines at runtime. For example, you might want to verify a user's API permissions with [Amazon Verified Permissions](amazon-cognito-authorization-with-avp.md) and adjust the scopes in the access token accordingly.

The Essentials plan adds to the existing functions of a [pre token generation trigger](user-pool-lambda-pre-token-generation.md). With lower-tier plans, you can customize ID tokens with additional claims, roles, and group membership. Essentials adds new versions of the trigger input event that customize access token claims, roles, group membership, and scopes. Access token customization is available to machine-to-machine (M2M) [client credentials grants](federation-endpoints-oauth-grants.md) with event version three.

**To customize access tokens**

1. Select the Essentials or Plus feature plan.

1. Create a Lambda function for your trigger. To use our example function, [configure it for Node.js](https://docs.aws.amazon.com/lambda/latest/dg/lambda-nodejs.html).

1. Populate your Lambda function with our [example code](user-pool-lambda-pre-token-generation.md#aws-lambda-triggers-pre-token-generation-example-version-2-overview) or compose your own. You function must process a request object from Amazon Cognito and return the changes that you want to include.

1. Assign your new function as a [version two or three](user-pool-lambda-pre-token-generation.md#user-pool-lambda-pre-token-generation-event-versions) pre token generation trigger. Version two events customize access tokens for user identities. Version three customizes access tokens for user and machine identities.

**Learn more**
+ [Customizing the access token](user-pool-lambda-pre-token-generation.md#user-pool-lambda-pre-token-generation-accesstoken)
+ [How to customize access tokens in Amazon Cognito user pools](https://aws.amazon.com/blogs/security/how-to-customize-access-tokens-in-amazon-cognito-user-pools/)

## Email MFA
<a name="features-email-mfa"></a>

Amazon Cognito user pools can be configured to use email as the second factor in multi-factor authentication (MFA). With email MFA, Amazon Cognito can send users an email with a verification code that they must enter to complete the authentication process. This adds an important extra layer of security to the user login flow. To enable email-based MFA, the user pool must be configured to use the [Amazon SES email-sending configuration](user-pool-email.md#user-pool-email-developer) instead of the default email configuration.

When your user selects MFA by email message, Amazon Cognito will send a one-time verification code to the user's registered email address whenever they attempt to sign in. The user must then provide this code back to your user pool to complete the authentication flow and gain access. This ensures that even if a user's username and password are compromised, they must provide an additional factor—the emailed code—before they can access your application resources.

For more information, see [SMS and email message MFA](user-pool-settings-mfa-sms-email-message.md). The following is an overview of how to set up your user pool and users for email MFA.

**To set up email MFA in the Amazon Cognito console**

1. Select the Essentials or Plus feature plan.

1. In the **Sign-in** menu of your user pool, edit **Multi-factor authentication**.

1. Choose the level of **MFA enforcement** that you want to set up. With **Require MFA**, users in the API automatically receive a challenge to set up, confirm, and sign in with MFA. In user pools that require MFA, managed login prompts them to choose and set up an MFA factor. With **Optional MFA**, your application must offer users the option to set up MFA and set the user's preference for email MFA.

1. Under **MFA methods**, select **Email message** as one of the options.

**Learn more**
+ [SMS and email message MFA](user-pool-settings-mfa-sms-email-message.md)

## Password reuse prevention
<a name="features-password-reuse"></a>

By default, a Amazon Cognito user pools password policy sets password length and character-type requirements, and temporary-password expiration. The Essentials plan adds the capability to enforce password history. When a user attempts to reset their password, your user pool can prevent them from setting it to a previous password. For more information about configuring the password policy, see [Adding user pool password requirements](managing-users-passwords.md#user-pool-settings-policies). The following is an overview of how to set up your user pool with a password-history policy.

**To set up password history in the Amazon Cognito console**

1. Select the Essentials or Plus feature plan.

1. In the **Authentication methods** menu of your user pool, locate **Password policy** and select **Edit**.

1. Configure other available options and set a value for **Prevent use of previous passwords**.

**Learn more**
+ [Passwords, account recovery, and password policies](managing-users-passwords.md)

## Managed login hosted sign-in and authorization server
<a name="features-enhanced-ui"></a>

Amazon Cognito user pools have optional webpages that support the following functions: an OpenID Connect (OIDC) IdP, a service provider or relying party to third-party IdPs, and public user-interactive pages for sign-up and sign-in. These pages are collectively called *managed login*. When you choose a domain for your user pool, Amazon Cognito automatically activates these pages. Where the Lite plan has the hosted UI, the Essentials plan opens up this advanced version of sign-up and sign-in pages.

Managed login pages have a clean, up-to-date interface with more features and options for customizing your branding and styles. The Essentials plan is the lowest plan level that unlocks access to managed login.

**To set up managed login in the Amazon Cognito console**

1. From the **Settings** menu, select the Essentials or Plus feature plan.

1. From the **Domain** menu, [Assign a domain](cognito-user-pools-assign-domain.md) to your user pool and select a **Branding version** of **Managed login**.

1. From the **Managed login** menu, under **Styles** tab, choose **Create a style** and assign the style to an app client, or create a new app client.

**Learn more**
+ [User pool managed login](cognito-user-pools-managed-login.md)

## Choice-based authentication
<a name="features-user-auth"></a>

The Essentials tier introduces a new *authentication flow* for authentication operations in the enhanced UI and SDK-based API operations.This flow is *choice-based authentication*. Choice-based authentication is a method where your users' authentication starts not with an application-side declaration of a sign-in method, but a query of possible sign-in methods followed by a choice. You can configure your user pool to support choice-based authentication and unlock username-password, passwordless, and passkey authentication. In the API, this is the `USER_AUTH` flow.

**To set up choice-based authentication in the Amazon Cognito console**

1. Select the Essentials or Plus feature plan.

1. In the **Sign-in** menu of your user pool, edit **Options for choice-based sign-in**. Select and configure the authentication methods you want to enable in choice-based authentication.

1. In the **Authentication methods** menu of your user pool, edit the configuration of sign-in operations.

**Learn more**
+ [Authentication with Amazon Cognito user pools](authentication.md)

# Plus plan features
<a name="feature-plans-features-plus"></a>

The Plus feature plan has advanced security features for Amazon Cognito user pools. These features log and analyze user context at runtime for potential security issues in devices, locations, request data, and passwords. They then mitigate potential risks with automatic responses that block or add security safeguards to user accounts. You can also export your security logs to Amazon S3, Amazon Data Firehose, or Amazon CloudWatch Logs for further analysis.

When you switch from the Essentials to the Plus plan, you get all the features in Essentials and the additional features that follow. These include the threat protection set of security options also known as *advanced security features*. To configure your user pools to automatically adapt to threats in your authentication front end, choose the Plus plan for your user pools.

The sections that follows present a brief overview of the features that you can add to your application with the Plus plan. For detailed information, see the following pages.

**Additional resources**
+ Adaptive authentication: [Working with adaptive authentication](cognito-user-pool-settings-adaptive-authentication.md)
+ Compromised credentials: [Working with compromised-credentials detection](cognito-user-pool-settings-compromised-credentials.md)
+ Log export: [Exporting logs from Amazon Cognito user pools](exporting-quotas-and-usage.md)

**Topics**
+ [

## Threat protection: adaptive authentication
](#features-adaptive-authentication)
+ [

## Threat protection: compromised-credentials detection
](#features-compromised-credentials)
+ [

## Threat protection: user activity logging
](#features-user-logs)

## Threat protection: adaptive authentication
<a name="features-adaptive-authentication"></a>

The Plus plan includes an *adaptive authentication* feature. When you activate this feature, your user pool makes a risk assessment of every user authentication session. From the resulting risk ratings, you can block authentication or push MFA for users who sign in with a risk level above a threshhold that you determine. With adaptive authentication, your user pool and application automatically block or set up MFA for users whose accounts you suspect are being attacked. You can also provide feedback on the risk ratings from your user pool to adjust future ratings.

**To set up adaptive authentication in the Amazon Cognito console**

1. Select the Plus feature plan.

1. From the **Threat protection** menu of your user pool, edit **Standard and custom authentication** under **Threat protection**.

1. Set the **enforcement mode** for standard or custom authentication to **Full-function**.

1. Under **Adaptive authentication**, configure automatic risk responses for different levels of risk.

**Learn more**
+ [Working with adaptive authentication](cognito-user-pool-settings-adaptive-authentication.md)
+ [Collecting data for threat protection in applications](user-pool-settings-viewing-threat-protection-app.md)

## Threat protection: compromised-credentials detection
<a name="features-compromised-credentials"></a>

The Plus plan includes a *compromised-credentials detection* feature. This feature guards against the use of insecure passwords and the threat of unintended application access that this practice creates. When you permit your users to sign in with username and password, they might reuse a password that they've used elsewhere. That password might have been leaked, or just be commonly guessed. With compromised-credentials detection, your user pool reads the passwords your users submit and compares them to password databases. If the operation results in a decision that the password is likely compromised, you can configure your user pool to block sign-in and then initiate a password reset for the user in your application.

Compromised-credentials detection can react to insecure passwords when new users sign up, when existing users sign in, and when users attempt to reset their passwords. With this feature, your user pool can prevent or warn about sign-in with insecure passwords wherever users enter them.

**To set up compromised-credentials detection in the Amazon Cognito console**

1. Select the Plus feature plan.

1. From the **Threat protection** menu of your user pool, edit **Standard and custom authentication** under **Threat protection**.

1. Set the **enforcement mode** for standard or custom authentication to **Full-function**.

1. Under **Compromised credentials**, configure the types of authentication operations that you want to check, and the automated response that you want from your user pool.

**Learn more**
+ [Working with compromised-credentials detection](cognito-user-pool-settings-compromised-credentials.md)

## Threat protection: user activity logging
<a name="features-user-logs"></a>

The Plus plan adds a logging feature that gives security analysis and details of user authentication attempts. You can see risk assessments, user IP addresses, user agents, and other information about the device that connected to your application. You can act on this information with the built-in threat protection features, or you can analyze your logs in your own systems and take appropriate action. You can export the logs from threat protection to Amazon S3, CloudWatch Logs, or Amazon DynamoDB.

**To set up user activity logging in the Amazon Cognito console**

1. Select the Plus feature plan.

1. From the **Threat protection** menu of your user pool, edit **Standard and custom authentication** under **Threat protection**.

1. Set the **enforcement mode** for standard or custom authentication to **Audit-only**. This is the minimum setting for logs. You can also activate it in **Full-function** mode and configure other threat protection features.

1. To export your logs to another AWS service for third-party analysis, go to the **Log streaming** menu of your user pool and set up an export destination.

**Learn more**
+ [Exporting user authentication events](cognito-user-pool-settings-adaptive-authentication.md#user-pool-settings-adaptive-authentication-event-user-history-exporting)
+ [Exporting logs from Amazon Cognito user pools](exporting-quotas-and-usage.md)

# Turning off features to change feature plans
<a name="feature-plans-deactivate"></a>

Feature plans add configuration options to your user pool. You can configure and use these features only when the related feature plan is active. For example, you can configure access token customization in the Plus and Essentials plans, but not in the Lite plan. To deactivate these features, you must deactivate each active component. The **Switch to** option in the **Settings** menu in the Amazon Cognito console notifies you of the features you must deactivate before you can change your feature plan. With this chapter, you can learn the changes that deactivation makes to your user pool configuration, and how to turn off these features individually.

**Access token customization**  
To switch to a plan that doesn't include access token customization, you must remove the [pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md#user-pool-lambda-pre-token-generation-accesstoken) from your user pool. To add a new pre token generation trigger without access token customization, assign a new function to the trigger and configure it for `V1_0` events. These version one trigger events can process changes to ID tokens only.  
To manually deactivate access token customization, remove your pre token generation trigger and add a new version one trigger.

**Threat protection**  
To switch to a plan without threat protection, deactivate all features from the **Threat protection** menu of your user pool.

**Log export**  
To switch to a plan without log export, deactivate it from the **Log streaming** menu of your user pool. Your user pool no longer generates local or exported user-activity logs. You can also send a [SetLogDeliveryConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetLogDeliveryConfiguration.html) API request that removes any configuration with an `EventSource` value of `UserActivity`.

**Email MFA**  
To switch to a plan without email MFA, go to the **Sign-in** menu of your user pool. Edit **Multi-factor authentication** and deselect **Email message** as one of the available **MFA methods**.

# Security best practices for Amazon Cognito user pools
<a name="user-pool-security-best-practices"></a>

This page describes security best practices that you can implement when you want to guard against common threats. The configuration that you choose will depend on the use case of each application. We recommend that at a minimum, you apply least privilege to administrative operations and take action to guard application and user secrets. Another advanced but effective step that you can take is to configure and apply AWS WAF web ACLs to your user pools.

## Protect your user pool at the network level
<a name="user-pool-security-best-practices-network"></a>

AWS WAF web ACLs can protect the performance and cost of the authentication mechanisms that you build with Amazon Cognito. With web ACLs, you can implement guardrails in front of API and managed login requests. Web ACLs create network- and application-layer filters that can drop traffic or require a CAPTCHA based on rules that you devise. Requests aren’t passed to your Amazon Cognito resources until they meet the qualifications in your web ACL rules. For more information, see [AWS WAF web ACLs](user-pool-waf.md).

## Protect against SMS message abuse
<a name="user-pool-security-best-practices-sms"></a>

When you permit public sign-up in your user pool, you can configure account verification with codes that Amazon Cognito sends in SMS text messages. SMS messages can be associated with unwanted activity and increase your AWS bill. Configure your infrastructure to be resilient against sending SMS messages under circumstances of fraud. For more information, review the following posts from AWS Blogs.
+ [Reduce risks of user sign-up fraud and SMS pumping with Amazon Cognito user pools](https://aws.amazon.com/blogs/security/reduce-risks-of-user-sign-up-fraud-and-sms-pumping-with-amazon-cognito-user-pools/)
+ [Defending Against SMS Pumping: New AWS Features to Help Combat Artificially Inflated Traffic](https://aws.amazon.com/blogs/messaging-and-targeting/defending-against-sms-pumping-new-aws-features-to-help-combat-artificially-inflated-traffic/)

## Understand public authentication
<a name="user-pool-security-best-practices-public-operations"></a>

Amazon Cognito user pools have customer identity and access management (CIAM) features that support use cases where members of the general public can sign up for a user account and access your applications. When a user pool permits self-service sign-up, it’s open to requests for user accounts from the public internet. Self-service requests come in from API operations like [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html), and from user interaction with managed login. You can configure user pools to mitigate abuse that might come in from public requests, or disable public authentication operations entirely. 

The following settings are some of the ways that you can manage public and internal authentication requests in your user pools and app clients.


**Examples of user pool settings that affect public user pool access**  

| Setting | Available options | Configured on | Effect on public authentication | Console setting | API operation and parameter | 
| --- | --- | --- | --- | --- | --- | 
| [Self-service sign-up](user-pool-settings-admin-create-user-policy.md) | Permit users to sign up for an account or create user accounts as an administrator. | User pool | Prevent public sign-up | Sign-up – Self-service sign-up |  [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-AdminCreateUserConfig), [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html#CognitoUserPools-UpdateUserPool-request-AdminCreateUserConfig) `AdminCreateUserConfig` – `AllowAdminCreateUserOnly`  | 
| [Administrator confirmation](signing-up-users-in-your-app.md#signing-up-users-in-your-app-and-confirming-them-as-admin) | Send confirmation codes to new users or require administrators to confirm them. | User pool | Prevent confirmation of sign-up without administrator action | Sign-up – Cognito-assisted verification and confirmation |  [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-AccountRecoverySetting), [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html#CognitoUserPools-UpdateUserPool-request-AccountRecoverySetting) `AccountRecoverySettings` – `admin_only`  | 
| [User disclosure](cognito-user-pool-managing-errors.md) | Deliver "user not found" messages at sign-in and password reset or prevent disclosure. | App client | Guard against guessing sign-in name, email address, or phone numbers | App clients – Prevent user existence errors |  [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-PreventUserExistenceErrors), [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html#CognitoUserPools-UpdateUserPoolClient-request-PreventUserExistenceErrors) `PreventUserExistenceErrors`  | 
| [Client secret](user-pool-settings-client-apps.md#user-pool-settings-client-app-client-types) | Require or don't require a secret hash at sign-up, sign-in, password reset | App client | Guard against authentication requests from unauthorized sources | App clients – Client secret |  [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-GenerateSecret) `GenerateSecret`  | 
| [Web ACLs](user-pool-waf.md) | Enable or don't enable a network firewall for authentication requests | User pool | Limit or prevent access based on administrator-defined request characteristics and IP address rules | AWS WAF – WAF settings |  [AssociateWebACL](https://docs.aws.amazon.com/waf/latest/APIReference/API_AssociateWebACL.html#WAF-AssociateWebACL-request-ResourceArn) `ResourceArn`  | 
| [External IdP](cognito-user-pools-identity-provider.md) | Permit sign-in by users in third-party IdPs, the user pool directory, or both | App client | Exclude [local users](cognito-terms.md#terms-localuser) or [federated users](cognito-terms.md#terms-federateduser) from sign-up & sign-in. | App clients – Identity providers |  [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-SupportedIdentityProviders), [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html#CognitoUserPools-UpdateUserPoolClient-request-SupportedIdentityProviders) `SupportedIdentityProviders`  | 
| [Authorization server](cognito-user-pools-assign-domain.md) | Host or don't host public webpages for authentication | User pool | Turn off public webpages and allow only SDK-based authentication | Domain |  [CreateUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolDomain.html) Creation of any user pool domain makes public webpages available.  | 
| [Threat protection](cognito-user-pool-settings-threat-protection.md) | Enable or disable monitoring for signs of malicious activity or unsafe passwords | User pool or app client | Can automatically block sign-in or require MFA when users show indicators of compromise | Threat protection – Protection settings |  [SetRiskConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetRiskConfiguration.html) The parameters of `SetRiskConfiguration` define your threat protection settings.  | 

## Protect confidential clients with client secrets
<a name="user-pool-security-best-practices-client-secret"></a>

The client secret is an optional string that’s associated with an [app client](user-pool-settings-client-apps.md). All authentication requests to app clients with client secrets must include a [secret hash](signing-up-users-in-your-app.md#cognito-user-pools-computing-secret-hash) that’s generated from the username, client ID, and client secret. Those who don’t know the client secret are shut out of your application from the beginning.

However, client secrets have limitations. If you embed a client secret in public client software, your client secret is open to inspection. This opens the ability to create users, submit password-reset requests, and perform other operations in your app client. Client secrets must be implemented only when an application is the only entity that has access to the secret. Typically, this is possible in server-side confidential client applications. This is also true of [M2M applications](cognito-user-pools-define-resource-servers.md), where a client secret is required. Store the client secret in encrypted local storage or AWS Secrets Manager. Never let your client secret be visible on the public internet.

## Protect other secrets
<a name="user-pool-security-best-practices-manage-secrets"></a>

You authentication system with Amazon Cognito user pools might handle private data, passwords, and AWS credentials. The following are some best practices for handling secrets that your application might access.

**Passwords**  
Users might enter passwords when they sign in to your application. Amazon Cognito has refresh tokens that your application can employ to continue expired user sessions without a new password prompt. Don’t place any passwords or password hashes in local storage. Design your application to treat passwords as opaque and only pass them through to your user pool.  
As a best practice, implement passwordless authentication with [WebAuthn passkeys](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passkey). If you must implement passwords, use the [Secure Remote Password (SRP) authentication flow](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-srp) and [multi-factor authentication (MFA)](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-mfa).

**AWS credentials**  
Administrative authentication and user pool administrative operations require authentication with AWS credentials. To implement these operations in an application, grant secure access to [temporary AWS credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). Grant credentials access only to applications that run on a server component that you control. Don’t put applications that have AWS credentials in them on public version-control systems like GitHub. Don’t encode AWS credentials in public client-side applications.

**PKCE code verifier**  
[Proof Key for Code Exchange, or PKCE](using-pkce-in-authorization-code.md), is for OpenID Connect (OIDC) authorization-code grants with your user pool authorization server. Applications share code verifier secrets with your user pool when they request authorization codes. To exchange authorization codes for tokens, clients must reaffirm that they know the code verifier. This practice guards against issuing tokens with intercepted authorization codes.  
Clients must generate a new random code verifier with each authorization request. The use of a static or predictable code verifier means that an attacker is only then required to intercept the hardcoded verifier and the authorization code. Design your application so that it doesn’t expose code verifier values to users.

## User pool administration least privilege
<a name="user-pool-security-best-practices-least-privilege"></a>

IAM policies can define the level of access that principals have to Amazon Cognito user pool administration and administrative authentication operations. For example:
+ To a webserver, grant permissions for authentication with administrative API operations. 
+ To an AWS IAM Identity Center user who manages a user pool in your AWS account, grant permissions for user pool maintenance and reporting.

The level of resource granularity in Amazon Cognito is limited to [two resource types](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncognitoidentity.html#amazoncognitoidentity-resources-for-iam-policies) for IAM policy purposes: user pool and identity pool. Note that you can’t apply permissions to manage individual app clients. Configure user pools with the knowledge that permissions that you grant are effective across all app clients. When your organization has multiple application tenants and your security model requires separation of administrative responsibilities between tenants, implement [multi-tenancy with one tenant per user pool](bp_user-pool-based-multi-tenancy.md).

Although you can create IAM policies with permissions for user authentication operations like `InitiateAuth`, those permissions have no effect. [Public and token-authorized API operations](authentication-flows-public-server-side.md) aren’t subject to IAM permissions. Of the available user pool authentication operations, you can only grant permissions to *administrative* server-side operations like `AdminInitiateAuth`.

You can limit levels of user pool administration with least-privilege `Action` lists. The following example policy is for an administrator who can manage IdPs, resource servers, app clients, and the user pool domain, but not users or the user pool.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "UserPoolClientAdministrator",
      "Action": [
        "cognito-idp:CreateIdentityProvider",
        "cognito-idp:CreateManagedLoginBranding",
        "cognito-idp:CreateResourceServer",
        "cognito-idp:CreateUserPoolDomain",
        "cognito-idp:DeleteIdentityProvider",
        "cognito-idp:DeleteResourceServer",
        "cognito-idp:DeleteUserPoolDomain",
        "cognito-idp:DescribeIdentityProvider",
        "cognito-idp:DescribeManagedLoginBranding",
        "cognito-idp:DescribeManagedLoginBrandingByClient",
        "cognito-idp:DescribeResourceServer",
        "cognito-idp:DescribeUserPool",
        "cognito-idp:DescribeUserPoolClient",
        "cognito-idp:DescribeUserPoolDomain",
        "cognito-idp:GetIdentityProviderByIdentifier",
        "cognito-idp:GetUICustomization",
        "cognito-idp:ListIdentityProviders",
        "cognito-idp:ListResourceServers",
        "cognito-idp:ListUserPoolClients",
        "cognito-idp:ListUserPools",
        "cognito-idp:SetUICustomization",
        "cognito-idp:UpdateIdentityProvider",
        "cognito-idp:UpdateManagedLoginBranding",
        "cognito-idp:UpdateResourceServer",
        "cognito-idp:UpdateUserPoolClient",
        "cognito-idp:UpdateUserPoolDomain"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_EXAMPLE"
    }
  ]
}
```

------

The following example policy grants user and group management and authentication to a server-side application.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "UserAdminAuthN",
      "Action": [
        "cognito-idp:AdminAddUserToGroup",
        "cognito-idp:AdminConfirmSignUp",
        "cognito-idp:AdminCreateUser",
        "cognito-idp:AdminDeleteUser",
        "cognito-idp:AdminDeleteUserAttributes",
        "cognito-idp:AdminDisableProviderForUser",
        "cognito-idp:AdminDisableUser",
        "cognito-idp:AdminEnableUser",
        "cognito-idp:AdminForgetDevice",
        "cognito-idp:AdminGetDevice",
        "cognito-idp:AdminGetUser",
        "cognito-idp:AdminInitiateAuth",
        "cognito-idp:AdminLinkProviderForUser",
        "cognito-idp:AdminListDevices",
        "cognito-idp:AdminListGroupsForUser",
        "cognito-idp:AdminListUserAuthEvents",
        "cognito-idp:AdminRemoveUserFromGroup",
        "cognito-idp:AdminResetUserPassword",
        "cognito-idp:AdminRespondToAuthChallenge",
        "cognito-idp:AdminSetUserMFAPreference",
        "cognito-idp:AdminSetUserPassword",
        "cognito-idp:AdminSetUserSettings",
        "cognito-idp:AdminUpdateAuthEventFeedback",
        "cognito-idp:AdminUpdateDeviceStatus",
        "cognito-idp:AdminUpdateUserAttributes",
        "cognito-idp:AdminUserGlobalSignOut",
        "cognito-idp:AssociateSoftwareToken",
        "cognito-idp:ListGroups",
        "cognito-idp:ListUsers",
        "cognito-idp:ListUsersInGroup",
        "cognito-idp:RevokeToken",
        "cognito-idp:UpdateGroup",
        "cognito-idp:VerifySoftwareToken"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_EXAMPLE"
    }
  ]
}
```

------

## Secure and verify tokens
<a name="user-pool-security-best-practices-secure-tokens"></a>

Tokens can contain internal references to group membership and user attributes that you might not want to disclose to the end user. Don’t store ID and access tokens in local storage. Refresh tokens are encrypted with a key that only your user pool can access, and are opaque to users and applications. [Revoke refresh tokens](token-revocation.md) when users sign out or when you determine that persisting a users' session is undesired for security reasons.

Use access tokens to authorize access only to systems that independently verify that the token is valid and unexpired. For verification resources, see [Verifying a JSON web token](amazon-cognito-user-pools-using-tokens-verifying-a-jwt.md).

## Determine the identity providers that you want to trust
<a name="user-pool-security-best-practices-trusted-idps"></a>

When you configure your user pool with [SAML](cognito-user-pools-saml-idp.md) or [OIDC](cognito-user-pools-oidc-idp.md) identity providers (IdPs), your IdPs can create new users, set user attributes, and access your application resources. SAML and OIDC providers are typically used in business-to-business (B2B) or enterprise scenarios where you or your immediate customer controls membership and configuration of the provider.

[Social providers](cognito-user-pools-social-idp.md) offer user accounts to anyone on the internet and are less under your control than enterprise providers. Only activate social IdPs in your app client when you’re ready to allow public customers to sign in and access resources in your application.

## Understand the effect of scopes on access to user profiles
<a name="user-pool-security-best-practices-scopes"></a>

You can request access-control scopes in your authentication requests to the user pool authorization server. These scopes can grant your users access to external resources, and they can grant users access to view and modify their own user profiles. Configure your app clients to support the minimum scopes necessary for the operation of your application.

The `aws.cognito.signin.user.admin` scope is present in all access tokens issued by SDK authentication with operations like [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html). It’s designated for user profile self-service operations in your application. You can also request this scope from your authorization server. This scope is required for token-authorized operations like [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html) and [GetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html). The effect of these operations is limited by the read and write permissions of your app client.

The `openid`, `profile`, `email`, and `phone` scopes authorize requests to the [userInfo endpoint](userinfo-endpoint.md) on your user pool authorization server. They define the attributes that the endpoint can return. The `openid` scope, when requested without other scopes, returns all available attributes, but when you request more scopes in the request, the response is narrowed down to the attributes represented by the additional scopes. The `openid` scope also indicates a request for an ID token; when you omit this scope from your request to your [Authorize endpoint](authorization-endpoint.md), Amazon Cognito only issues an access token and, when applicable, a refresh token. For more information, see **OpenID Connect scopes** at [App client terms](user-pool-settings-client-apps.md#cognito-user-pools-app-idp-settings-about).

## Sanitize inputs for user attributes
<a name="user-pool-security-best-practices-sanitize-inputs"></a>

User attributes that might end up as delivery methods and usernames, for example `email`, have [format restrictions](user-pool-settings-attributes.md#cognito-user-pools-standard-attributes). Other attributes can have string, boolean, or number data types. String attribute values support a variety of inputs. Configure your application to guard against attempts to write unwanted data to your user directory or the messages that Amazon Cognito delivers to users. Perform client-side validation of user-submitted string attribute values in your application before submitting them to Amazon Cognito.

User pools map attributes from IdPs to your user pool based on an [attribute mapping](cognito-user-pools-specifying-attribute-mapping.md) that you specify. Only map secure and predictable IdP attributes to user pool string attributes.

# Authentication with Amazon Cognito user pools
<a name="authentication"></a>

Amazon Cognito includes several methods to authenticate your users. Users can sign in with passwords and WebAuthn passkeys. Amazon Cognito can send them a one-time password in an email or SMS message. You can implement Lambda functions that orchestrate your own sequence of challenges and responses. These are *authentication flows*. In authentication flows, users provide a secret and Amazon Cognito verifies the secret, then issues JSON web tokens (JWTs) for applications to process with OIDC libraries. In this chapter, we'll talk about how to configure your user pools and app clients for various authentication flows in various application environments. You'll learn about options for the use of the hosted sign-in pages of managed login, and for building your own logic and front end in an AWS SDK.

All user pools, whether you have a domain or not, can authenticate users in the user pools API. If you add a domain to your user pool, you can use the [user pool endpoints](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html). The user pools API supports a variety of authorization models and request flows for API requests.

To verify the identity of users, Amazon Cognito supports authentication flows that incorporate challenge types in addition to passwords like email and SMS message one-time passwords and passkeys.

**Topics**
+ [

## Implement authentication flows
](#authentication-implement)
+ [

## Things to know about authentication with user pools
](#authentication-flow-things-to-know)
+ [

## An example authentication session
](#amazon-cognito-user-pools-authentication-flow)
+ [

# Configure authentication methods for managed login
](authentication-flows-selection-managedlogin.md)
+ [

# Manage authentication methods in AWS SDKs
](authentication-flows-selection-sdk.md)
+ [

# Authentication flows
](amazon-cognito-user-pools-authentication-flow-methods.md)
+ [

# Authorization models for API and SDK authentication
](authentication-flows-public-server-side.md)

## Implement authentication flows
<a name="authentication-implement"></a>

Whether you're implementing [managed login](authentication-flows-selection-managedlogin.md) or a [custom-built application front end](authentication-flows-selection-sdk.md) with an AWS SDK for authentication, you must configure your app client for the types of authentication that you want to implement. The following information describes setup for authentication flows in your [app clients](user-pool-settings-client-apps.md) and your application.

------
#### [ App client supported flows ]

You can configure supported flows for your app clients in the Amazon Cognito console or with the API in an AWS SDK. After you configure your app client to support these flows, you can deploy them in your application.

The following procedure configures available authentication flows for an app client with the Amazon Cognito console.

**To configure an app client for authentication flows (console)**

1. Sign in to AWS and navigate to the [Amazon Cognito user pools console](https://console.aws.amazon.com/cognito/v2/idp). Choose a user pool or create a new one.

1. In your user pool configuration, select the **App clients** menu. Choose an app client or create a new one.

1. Under **App client information**, select **Edit**.

1. Under **App client flows**, choose the authentication flows that you want to support.

**To configure an app client for authentication flows (API/SDK)**  
To configure available authentication flows for an app client with the Amazon Cognito API, set the value of `ExplicitAuthFlows` in a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-ExplicitAuthFlows) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html#CognitoUserPools-UpdateUserPoolClient-request-ExplicitAuthFlows) request. The following is an example that provisions secure remote password (SRP) and choice-based authentication to a client.

```
"ExplicitAuthFlows": [ 
   "ALLOW_USER_AUTH",
   "ALLOW_USER_SRP_AUTH
]
```

When you configure app client supported flows, you can specify the following options and API values.


**App client flow support**  

| Authentication flow | Compatibility | Console | API  | 
| --- | --- | --- | --- | 
| [Choice-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) | Server-side, client-side | Select an authentication type at sign-in | ALLOW\$1USER\$1AUTH | 
| [Sign-in with persistent passwords](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-password) | Client-side | Sign in with username and password | ALLOW\$1USER\$1PASSWORD\$1AUTH | 
| [Sign-in with persistent passwords and secure payload](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-srp) | Server-side, client-side | Sign in with secure remote password (SRP) | ALLOW\$1USER\$1SRP\$1AUTH | 
| [Refresh tokens](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-refresh) | Server-side, client-side | Get new user tokens from existing authenticated sessions | ALLOW\$1REFRESH\$1TOKEN\$1AUTH | 
| [Server-side authentication](authentication-flows-public-server-side.md#amazon-cognito-user-pools-server-side-authentication-flow) | Server-side | Sign in with server-side administrative credentials | ALLOW\$1ADMIN\$1USER\$1PASSWORD\$1AUTH | 
| [Custom authentication](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-custom) | Server-side and client-side custom-built applications. Not compatible with managed login. | Sign in with custom authentication flows from Lambda triggers | ALLOW\$1CUSTOM\$1AUTH | 

------
#### [ Implement flows in your application ]

Managed login automatically makes your configured authentication options available in your sign-pages. In custom-built applications, start authentication with a declaration of the initial flow.
+ To choose from a list of flow options for a user, declare [choice-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) with the `USER_AUTH` flow. This flow has available authentication methods that aren't available in client-based authentication flows, for example [passkey](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passkey) and [passwordless](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless) authentication.
+ To choose your authentication flow up front, declare [client-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-client) with any other flow that's available in your app client.

When you sign users in, the body of your [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-request-AuthFlow) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html#CognitoUserPools-AdminInitiateAuth-request-AuthFlow) request must include an `AuthFlow` parameter.

Choice-based authentication:

```
"AuthFlow": "USER_AUTH"
```

Client-based authentication with SRP:

```
"AuthFlow": "USER_SRP_AUTH"
```

------

## Things to know about authentication with user pools
<a name="authentication-flow-things-to-know"></a>

Consider the following information in the design of your authentication model with Amazon Cognito user pools.

**Authentication flows in managed login and the hosted UI**  
[Managed login](cognito-user-pools-managed-login.md) has more options for authentication than the classic hosted UI. For example, users can do passwordless and passkey authentication only in managed login.

**Custom authentication flows only available in AWS SDK authentication**  
You can't do *custom authentication flows*, or [custom authentication with Lambda triggers](user-pool-lambda-challenge.md), with managed login or the classic hosted UI. Custom authentication is available in [authentication with AWS SDKs](authentication-flows-selection-sdk.md).

**Managed login for external identity provider (IdP) sign-in**  
You can't sign users in through [third-party IdPs](cognito-user-pools-identity-federation.md) in [authentication with AWS SDKs](authentication-flows-selection-sdk.md). You must implement managed login or the classic hosted UI, redirect to IdPs, and then process the resulting authentication object with OIDC libraries in your application. For more information about managed login, see [User pool managed login](cognito-user-pools-managed-login.md).

**Passwordless authentication effect on other user features**  
Activation of passwordless sign-in with [one-time passwords](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless) or [passkeys](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passkey) in your user pool and app client has an effect on user creation and migration. When passwordless sign-in is active:  

1. Administrators can create users without passwords. The default invitation message template changes to no longer include the `{###}` password placeholder. For more information, see [Creating user accounts as administrator](how-to-create-user-accounts.md).

1. For SDK-based [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) operations, users aren't required to supply a password when they sign up. Managed login and the hosted UI require a password in the sign-up page, even if passwordless authentication is permitted. For more information, see [Signing up and confirming user accounts](signing-up-users-in-your-app.md).

1. Users imported from a CSV file can sign in immediatelywith passwordless options, without a password reset, if their attributes include an email address or phone number for an available passwordless sign-in option. For more information, see [Importing users into user pools from a CSV file](cognito-user-pools-using-import-tool.md).

1. Passwordless authentication doesn't invoke the [user migration Lambda trigger](user-pool-lambda-migrate-user.md).

1. Users who sign in with a one-time password (OTP) first factor can't add a [multi-factor authentication (MFA)](user-pool-settings-mfa.md) factor to their session. Passkeys with user verification can satisfy MFA requirements when configured with `MULTI_FACTOR_WITH_USER_VERIFICATION`.

**Passkey relying party URLs can't be on the public suffix list**  
You can use domain names that you own, like `www.example.com`, as the relying party (RP) ID in your passkey configuration. This configuration is intended to support custom-built applications that run on domains that you own. The [public suffix list](https://publicsuffix.org/), or PSL, contains protected high-level domains. Amazon Cognito returns an error when you attempt to set your RP URL to a domain on the PSL.

**Topics**
+ [

### Authentication session flow duration
](#authentication-flow-session-duration)
+ [

### Lockout behavior for failed sign-in attempts
](#authentication-flow-lockout-behavior)

### Authentication session flow duration
<a name="authentication-flow-session-duration"></a>

Depending on the features of your user pool, you can end up responding to several challenges to `InitiateAuth` and `RespondToAuthChallenge` before your app retrieves tokens from Amazon Cognito. Amazon Cognito includes a session string in the response to each request. To combine your API requests into an authentication flow, include the session string from the response to the previous request in each subsequent request. By default, your users have three minutes to complete each challenge before the session string expires. To adjust this period, change your app client **Authentication flow session duration**. The following procedure describes how to change this setting in your app client configuration.

**Note**  
**Authentication flow session duration** settings apply to authentication with the Amazon Cognito user pools API. Managed login sets session duration to 3 minutes for multi-factor authentication and 8 minutes for password-reset codes.

------
#### [ Amazon Cognito console ]

**To configure app client authentication flow session duration (AWS Management Console)**

1. From the **App integration** tab in your user pool, select the name of your app client from the **App clients and analytics** container.

1. Choose **Edit** in the **App client information** container.

1. Change the value of **Authentication flow session duration** to the validity duration that you want, in minutes, for SMS and email MFA codes. This also changes the amount of time that any user has to complete any authentication challenge in your app client.

1. Choose **Save changes**.

------
#### [ User pools API ]

**To configure app client authentication flow session duration (Amazon Cognito API)**

1. Prepare an `UpdateUserPoolClient` request with your existing user pool settings from a `DescribeUserPoolClient` request. Your `UpdateUserPoolClient` request must include all existing app client properties.

1. Change the value of `AuthSessionValidity` to the validity duration that you want, in minutes, for SMS MFA codes. This also changes the amount of time that any user has to complete any authentication challenge in your app client.

------

For more information about app clients, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).

### Lockout behavior for failed sign-in attempts
<a name="authentication-flow-lockout-behavior"></a>

After five failed sign-in attempts with a user's password, regardless of whether those are requested with unauthenticated or IAM-authorized API operations, Amazon Cognito locks out your user for one second. The lockout duration then doubles after each additional one failed attempt, up to a maximum of approximately 15 minutes.

Attempts made during a lockout period generate a `Password attempts exceeded` exception, and don't affect the duration of subsequent lockout periods. For a cumulative number of failed sign-in attempts *n*, not including `Password attempts exceeded` exceptions, Amazon Cognito locks out your user for *2^(n-5)* seconds. To reset the lockout to its *n=0* initial state, your user must either sign in successfully after a lockout period expires, or not initiate any sign-in attempts for 15 consecutive minutes at any time after a lockout. This behavior is subject to change. This behavior doesn't apply to custom challenges unless they also perform password-based authentication.

## An example authentication session
<a name="amazon-cognito-user-pools-authentication-flow"></a>

The following diagram and step-by-step guide illustrate a typical scenario where a user signs in to an application. The example application presents a user with several sign-in options. They select one by entering their credentials, provide an additional authentication factor, and sign in.

![\[A flowchart that shows an application that prompts a user for input and signs them in with an AWS SDK.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/authentication-api-userauth.png)


Picture an application with a sign-in page where users can sign in with a username and password, request a one-time code in an email message, or choose a fingerprint option.

1. **Sign-in prompt**: Your application shows a home screen with a *Log in* button.

1. **Request sign-in**: The user selects *Log in*. From a cookie or a cache, your application retrieves their username, or prompts them to enter it.

1. **Request options**: Your application requests the user's sign-in options with an `InitiateAuth` API request with the `USER_AUTH` flow, requesting the available sign-in methods for the user.

1. **Send sign-in options**: Amazon Cognito responds with `PASSWORD`, `EMAIL_OTP`, and `WEB_AUTHN`. The response includes a session identifier for you to replay back in the next response.

1. **Display options**: Your application shows UI elements for the user to enter their username and password, get a one-time code, or scan their fingerprint.

1. **Choose option/Enter credentials**: The user enters their username and password.

1. **Initiate authentication**: Your application provides the user's sign-in information with a `RespondToAuthChallenge` API request that confirms username-password sign-in and provides the username and the password.

1. **Validate credentials**: Amazon Cognito confirms the user's credentials.

1. **Additional challenge**: The user has multi-factor authentication configured with an authenticator app. Amazon Cognito returns a `SOFTWARE_TOKEN_MFA` challenge.

1. **Challenge prompt**: Your application displays a form requesting a time-based one-time password (TOTP) from the user's authenticator app.

1. **Answer challenge**: The user submits the TOTP.

1. **Respond to challenge**: In another `RespondToAuthChallenge` request, your application provides the user's TOTP.

1. **Validate challenge response**: Amazon Cognito confirms the user's code and determines that your user pool is configured to issue no additional challenges to the current user.

1. **Issue tokens**: Amazon Cognito returns ID, access, and refresh JSON web tokens (JWTs). The user's initial authentication is complete.

1. **Store tokens**: Your application caches the user's tokens so that it can reference user data, authorize access to resources, and update tokens when they expire.

1. **Render authorized content**: Your application makes a determination of the user's access to resources based on their identity and roles, and delivers application content.

1. **Access content**: The user is signed in and begins using the application.

1. **Request content with expired token**: Later, the user requests a resource that requires authorization. The user's cached token has expired.

1. **Refresh tokens**: Your application makes an `InitiateAuth` request with the user's saved refresh token.

1. **Issue tokens**: Amazon Cognito returns new ID and access JWTs. The user's session is securely refreshed without additional prompts for credentials.

You can use [AWS Lambda triggers](cognito-user-pools-working-with-lambda-triggers.md) to customize the way users authenticate. These triggers issue and verify their own challenges as part of the authentication flow.

You can also use the admin authentication flow for secure backend servers. You can use the [user migration authentication flow](cognito-user-pools-using-import-tool.md) to make user migration possible without the requirement that your users to reset their passwords.

# Configure authentication methods for managed login
<a name="authentication-flows-selection-managedlogin"></a>

You can invoke [managed login pages](cognito-user-pools-managed-login.md), a web front end for user pool authentication, when you want users to sign in, sign out, or reset their password. In this model, your application imports OIDC libraries to process browser-based authentication attempts with user pool managed login pages. The forms of authentication that are available to your users are dependent on the configuration of your user pool and your app client. Implement the `ALLOW_USER_AUTH` flow in your app client, and Amazon Cognito prompts users to select a sign-in method from the available options. Implement `ALLOW_USER_PASSWORD_AUTH` and assign a SAML provider, and your login pages prompt users with the option to enter their username and password or to connect with their IdP.

The Amazon Cognito user pools console can get you started with setting up managed login authentication for your application. When you create a new user pool, specify the platform you're developing for and the console gives you examples for implementation of OIDC and OAuth libraries with starter code to implement sign-in and sign-out flows. You can build managed login with many OIDC relying-party implementations. We recommend that you work with [certified OIDC relying party libraries](https://openid.net/developers/certified-openid-connect-implementations/) where possible. For more information, see [Getting started with user pools](getting-started-user-pools.md).

Typically, OIDC relying party libraries periodically check the `.well-known/openid-configuration` endpoint of your user pool to determine issuer URLs like the token endpoint and authorization endpoint. As a best practice, implement this automatic-discovery behavior where you have to option to. Manual configuration of issuer endpoints introduces potential for error. For example, you might change your user pool domain. The path to `openid-configuration` isn't linked to your user pool domain, so applications that autodiscover service endpoints will automatically pick up your domain change.

## User pool settings for managed login
<a name="authentication-flows-selection-managedlogin-settings"></a>

You might want to allow sign in with multiple providers for your application, or you might want to use Amazon Cognito as an independent user directory. You might also want to collect user attributes, set up and prompt for MFA, or require email addresses as usernames. You can't directly edit the fields in managed login and the hosted UI. Instead, the configuration of your user pool automatically sets the handling of managed-login authentication flows.

The following user pool configuration items determine the authentication methods that Amazon Cognito presents to users in managed login and the hosted UI.

------
#### [ User pool options (Sign-in menu) ]

The following options are in the **Sign-in** menu of a user pool in the Amazon Cognito console.

**Cognito user pool sign-in options**  
Has options for usernames. Your managed login and hosted UI pages only accept usernames in the formats that you select. When you, for example, set up a user pool with **Email** as the only sign-in option, your managed login pages only accept usernames in an email format.

**Required attributes**  
When you set an attribute as required in your user pool, managed login prompts users for a value for that attribute when they sign up.

**Options for choice-based sign-in**  
Has settings for authentication methods in [Choice-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-choice). Here, you can turn on or off authentication methods like [passkey](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passkey) and [passwordless](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless). These methods are only available to user pools with [managed login domains](managed-login-branding.md) and [feature plans](cognito-sign-in-feature-plans.md) above the **Lite** tier.

**Multi-factor authentication**  
Managed login and the hosted UI handle registration and authentication operations for [MFA](user-pool-settings-mfa.md). When MFA is required in your user pool, your sign-in pages automatically prompt users to set up their additional factor. They also prompt users who have an MFA configuration to complete authentication with an MFA code. When MFA is off or optional in your user pool, your sign-in pages don't prompt to set up MFA.

**User account recovery**  
The self-service [account recovery]() setting of your user pool determines whether your sign-in pages display a link where users can reset their password.

------
#### [ User pool options (Domain menu) ]

The following options are in the **Domain** menu of a user pool in the Amazon Cognito console.

**Domain**  
Your choice of a user pool domain sets the path for the link that users open when you invoke their browsers for authentication.

**Branding version**  
Your choice of a branding version determines whether your user pool domain displays managed login or the hosted UI.

------
#### [ User pool options (Social and external providers menu) ]

The following option is in the **Social and external providers** menu of a user pool in the Amazon Cognito console.

**Providers**  
The identity providers (IdPs) that you add to your user pool can be left active or inactive for each app client in the user pool.

------
#### [ App client options ]

The following options are in the **App clients** menu of a user pool in the Amazon Cognito console. To review these options, select an app client from the list.

**Quick setup guide**  
The quick setup guide has code examples for a variety of developer environments. They contain the libraries necessary to integrate managed login authentication with your application.

**App client information**  
Edit this configuration to set assigned IdPs for the application that's represented by the current app client. On the managed login pages, Amazon Cognito displays choices for users. These choices are determined from the assigned methods and IdP. For example, if you assign a SAML 2.0 IdP named `MySAML` and local user pool login, your managed login pages display authentication-method prompts and a button for `MySAML`.

**Authentication settings**  
Edit this configuration to set authentication methods for your application. On the managed login pages, Amazon Cognito displays choices for users. These choices are determined from the availability of the user pool as an IdP, and from the methods that you assign. For example, if you assign choice-based `ALLOW_USER_AUTH` authentication, your managed login pages display available choices like entering an email address and signing in with a passkey. Managed login pages also render buttons for the assigned IdPs.

**Login pages**  
Set the visual effect of your managed login or hosted UI user-interactive pages with the options available in this tab. For more information, see [Apply branding to managed login pages](managed-login-branding.md).

------

# Manage authentication methods in AWS SDKs
<a name="authentication-flows-selection-sdk"></a>

Users in Amazon Cognito user pools can sign in with a variety of initial sign-in options, or *factors*. For some factors, users can follow up with multi-factor authentication (MFA). These first factors include username and password, one-time password, passkey, and custom authentication. For more information, see [Authentication flows](amazon-cognito-user-pools-authentication-flow-methods.md). When your application has built-in UI components and imports an AWS SDK module, you must build application logic for authentication. You must choose one of two primary methods and from that method, the authentication mechanisms that you want to implement.

You can implement *client-based authentication* where your application, or client, declares the type of authentication up front. Your other option is *choice-based authentication*, where your app collects a username and requests the available authentication types for users. You can implement these models together in the same application or split between app clients, according to your requirements. Each method has features that are unique to it, for example custom authentication in client-based and passwordless authentication in choice-based.

In custom-built applications that perform authentication with AWS SDK implementation of the users pools API, you must structure your API requests to align with user pool configuration, app client configuration, and client-side preferences. An `InitiateAuth` session that begins with an `AuthFlow` of `USER_AUTH` begins choice-based authentication. Amazon Cognito responds to your API with a challenge of either a preferred authentication method or a list of choices. A session that begins with `AuthFlow` of `CUSTOM_AUTH` goes right into custom authentication with Lambda triggers.

Some authentication methods are fixed to one of the two flow types, and some methods are available in both.

**Topics**
+ [

## Choice-based authentication
](#authentication-flows-selection-choice)
+ [

## Client-based authentication
](#authentication-flows-selection-client)

## Choice-based authentication
<a name="authentication-flows-selection-choice"></a>

Your application can request the following authentication methods in choice-based authentication. Declare these options in the `PREFERRED_CHALLENGE` parameter of [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-request-AuthParameters) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html#CognitoUserPools-AdminInitiateAuth-request-AuthParameters), or in the `ChallengeName` parameter of [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html#CognitoUserPools-RespondToAuthChallenge-request-ChallengeName) or [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html#CognitoUserPools-AdminRespondToAuthChallenge-request-ChallengeName).

1. `EMAIL_OTP` and `SMS_OTP`

   [Passwordless sign-in with one-time passwords](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless)

1. `WEB_AUTHN`

   [Passwordless sign-in with WebAuthn passkeys](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passkey)

1. `PASSWORD`

   [Sign-in with persistent passwords](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-password)

   [Sign-in with persistent passwords and secure payload](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-srp)

   [MFA after sign-in](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-mfa)

To review these options in their API context, see `ChallengeName` in [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html#CognitoUserPools-RespondToAuthChallenge-request-ChallengeName).

Choice-based sign-in issues a challenge in response to your initial request. This challenge either verifies that a requested option is available, or provides a list of available choices. Your application can display these choices to users, who then enter credentials for their preferred sign-in method and proceed with authentication in challenge responses.

You have the following choice-based options in your authentication flow. All requests of this type require that your app first collect a username or retrieve it from a cache.

1. Request options with `AuthParameters` of `USERNAME` only. Amazon Cognito returns a `SELECT_CHALLENGE` challenge. From there, your application can prompt the user to select a challenge and return this response to your user pool.

1. Request a preferred challenge with `AuthParameters` of `PREFERRED_CHALLENGE` and the parameters of your preferred challenge, if any. For example, if you request a `PREFERRED_CHALLENGE` of `PASSWORD_SRP`, you must also include `SRP_A`. If your user, user pool, and app client are all configured for the preferred challenge, Amazon Cognito responds with the next step in that challenge, for example `PASSWORD_VERIFIER` in the `PASSWORD_SRP` flow or [CodeDeliveryDetails](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CodeDeliveryDetailsType.html) in the `EMAIL_OTP` and `SMS_OTP` flows. If the preferred challenge isn't available, Amazon Cognito responds with `SELECT_CHALLENGE` and a list of available challenges.

1. Sign users in first, then request their choice-based authentication options. A [GetUserAuthFactors](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAuthFactors.html) request with the access token of a signed-in user returns their available choice-based authentication factors and their MFA settings. With this option, a user can sign in with username and password first, then activate a different form of authentication. You can also use this operation to check additional options for a user who has signed in with a preferred challenge.

To [configure your app client](authentication.md#authentication-implement) for choice-based authentication, add `ALLOW_USER_AUTH` to the allowed authentication flows. You must also choose the choice-based factors that you want to permit in your user pool configuration. The following process illustrates how to choose choice-based authentication factors.

------
#### [ Amazon Cognito console ]

**To configure choice-based authentication options in a user pool**

1. Sign in to AWS and navigate to the [Amazon Cognito user pools console](https://console.aws.amazon.com/cognito/v2/idp). Choose a user pool or create a new one.

1. In your user pool configuration, select the **Sign-in** menu. Locate **Options for choice-based sign-in** and choose **Edit**.

1. The **Password** option is always available. This includes the `PASSWORD` and `PASSWORD_SRP` flows. Select the **Additional choices** that you want to add to your users' options. You can add **Passkey** for `WEB_AUTHN`, **Email message one-time password** for `EMAIL_OTP`, and **SMS message one-time password** for `SMS_OTP`.

1. Choose **Save changes**.

------
#### [ API/SDK ]

The following partial [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) request body configures all available options for choice-based authentication.

```
"Policies": {
    "SignInPolicy": {
        "AllowedFirstAuthFactors": [
            "PASSWORD",
            "WEB_AUTHN",
            "EMAIL_OTP",
            "SMS_OTP"
        ]
    }
},
```

------

## Client-based authentication
<a name="authentication-flows-selection-client"></a>

Client-based authentication supports the following authentication flows. Declare these options in the `AuthFlow` parameter of [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-request-AuthFlow) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html#CognitoUserPools-AdminInitiateAuth-request-AuthFlow).

1. `USER_PASSWORD_AUTH` and `ADMIN_USER_PASSWORD_AUTH`

   [Sign-in with persistent passwords](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-password)

   [MFA after sign-in](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-mfa)

   This authentication flow is equivalent to `PASSWORD` in choice-based authentication.

1. `USER_SRP_AUTH`

   [Sign-in with persistent passwords and secure payload](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-srp)

   [MFA after sign-in](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-mfa)

   This authentication flow is equivalent to `PASSWORD_SRP` in choice-based authentication.

1. `REFRESH_TOKEN_AUTH`

   [Refresh tokens](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-refresh)

   This authentication flow is only available in client-based authentication.

1. `CUSTOM_AUTH`

   [Custom authentication](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-custom)

   This authentication flow is only available in client-based authentication.

With client-based authentication, Amazon Cognito assumes that you have determined how your user wants to authenticate before they begin authentication flows. The logic of determining the sign-in factor that a user wants to provide must be determined with default settings or custom prompts, then declared in the first request to your user pool. The `InitiateAuth` request declares a sign-in `AuthFlow` that directly corresponds to one of the listed options, for example `USER_SRP_AUTH`. With this declaration, the request also includes the parameters to begin authentication, for example `USERNAME`, `SECRET_HASH`, and `SRP_A`. Amazon Cognito might follow up this request with additional challenges like `PASSWORD_VERIFIER` for SRP or `SOFTWARE_TOKEN_MFA` for password sign-in with TOTP MFA.

To [configure your app client](authentication.md#authentication-implement) for client-based authentication, add any authentication flows other than `ALLOW_USER_AUTH` to the allowed authentication flows. Examples are `ALLOW_USER_PASSWORD_AUTH`, `ALLOW_CUSTOM_AUTH`, `ALLOW_REFRESH_TOKEN_AUTH`. To permit client-based authentication flows, no additional user pool configuration is required.

# Authentication flows
<a name="amazon-cognito-user-pools-authentication-flow-methods"></a>

The process of authentication with Amazon Cognito user pools can best be described as a *flow* where users make an initial choice, submit credentials, and respond to additional challenges. When you implement managed login authentication in your application, Amazon Cognito manages the flow of these prompts and challenges. When you implement flows with an AWS SDK in your application back end, you must construct the logic of requests, prompt users for input, and respond to challenges.

As an application administrator, your user characteristics, security requirements, and authorization model help determine how you want to permit users to sign in. Ask yourself the following questions.
+ Do I want to permit users to sign in with credentials from [other identity providers (IdPs)](#amazon-cognito-user-pools-authentication-flow-methods-federated)?
+ Is a [username and password](#amazon-cognito-user-pools-authentication-flow-methods-password) enough proof of identity?
+ Could my authentication requests for username-password authentication be intercepted? Do I want my application to transmit passwords, or to [negotiate authentication using hashes and salts](#amazon-cognito-user-pools-authentication-flow-methods-srp)?
+ Do I want to permit users to skip password entry and [receive a one-time password](#amazon-cognito-user-pools-authentication-flow-methods-passwordless) that signs them in?
+ Do I want to permit users to sign in with a [thumbprint, face, or a hardware security key](#amazon-cognito-user-pools-authentication-flow-methods-passkey)?
+ When do I want to require [multi-factor authentication (MFA)](#amazon-cognito-user-pools-authentication-flow-methods-mfa), if at all?
+ Do I want to [persist user sessions without re-prompting for credentials](#amazon-cognito-user-pools-authentication-flow-methods-refresh)?
+ Do I want to [extend my authorization model](#amazon-cognito-user-pools-authentication-flow-methods-custom) beyond the built-in capabilities of Amazon Cognito?

When you have the answers to these questions, you can learn how to activate the relevant features and implement them in the authentication requests that your application makes.

After you set up sign-in flows for a user, you can check their current status for MFA and [choice-based](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) authentication factors with requests to the [GetUserAuthFactors](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAuthFactors.html) API operation. This operation requires authorization with the access token of a signed-in user. It returns user authentication factors and MFA settings.

**Topics**
+ [

## Sign-in with third-party IdPs
](#amazon-cognito-user-pools-authentication-flow-methods-federated)
+ [

## Sign-in with persistent passwords
](#amazon-cognito-user-pools-authentication-flow-methods-password)
+ [

## Sign-in with persistent passwords and secure payload
](#amazon-cognito-user-pools-authentication-flow-methods-srp)
+ [

## Passwordless sign-in with one-time passwords
](#amazon-cognito-user-pools-authentication-flow-methods-passwordless)
+ [

## Passwordless sign-in with WebAuthn passkeys
](#amazon-cognito-user-pools-authentication-flow-methods-passkey)
+ [

## MFA after sign-in
](#amazon-cognito-user-pools-authentication-flow-methods-mfa)
+ [

## Refresh tokens
](#amazon-cognito-user-pools-authentication-flow-methods-refresh)
+ [

## Custom authentication
](#amazon-cognito-user-pools-authentication-flow-methods-custom)
+ [

## User migration authentication flow
](#amazon-cognito-user-pools-user-migration-authentication-flow)

## Sign-in with third-party IdPs
<a name="amazon-cognito-user-pools-authentication-flow-methods-federated"></a>

Amazon Cognito user pools serve as an intermediate broker of authentication sessions between IdPs like Sign in with Apple, Login with Amazon, and OpenID Connect (OIDC) services. This process is also called *federated sign-in* or *federated authentication*. Federated authentication doesn't make use of any of the authentication flows that you can build into your app client. Instead, you assign configured user pool IdPs to your app client. Federated sign-in happens when users select their IdP in managed login or your application invokes a session with a redirect to their IdP sign-in page.

With federated sign-in, you delegate primary and MFA authentication factors to the user's IdP. Amazon Cognito doesn't add the other advanced flows in this section to a federated user unless you [link them to a local user](cognito-user-pools-identity-federation-consolidate-users.md). Unlinked federated users have usernames, but they are a store of mapped attribute data that's not typically used for sign-in independent of the browser-based flow.

**Implementation resources**
+ [User pool sign-in with third party identity providers](cognito-user-pools-identity-federation.md)

## Sign-in with persistent passwords
<a name="amazon-cognito-user-pools-authentication-flow-methods-password"></a>

In Amazon Cognito user pools, every user has a username. This might be a phone number, an email address, or a chosen or administrator-provided identifier. Users of this type can sign in with their username and their password, and optionally provide MFA. User pools can perform username-password sign-in with public or IAM-authorized API operations and SDK methods. Your application can directly send the password to your user pool for authentication. Your user pool responds with additional challenges or the JSON web tokens (JWTs) that are the result of successful authentication.

------
#### [ Activate password sign-in ]

To activate [client-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-client) with username and password, configure your app client to permit it. In the Amazon Cognito console, navigate to the **App clients** menu under **Applications** in your user pool configuration. To permit plain-password sign-in for a client-side mobile or native app, edit an app client and choose **Sign in with username and password: ALLOW\$1USER\$1PASSWORD\$1AUTH** under **Authentication flows**. To permit plain-password sign-in for a server-side app, edit an app client and choose **Sign in with server-side administrative credentials: ALLOW\$1ADMIN\$1USER\$1PASSWORD\$1AUTH**.

To activate [choice-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) with username and password, configure your app client to permit it. Edit your app client and choose **Choice-based sign-in: ALLOW\$1USER\$1AUTH**.

![\[A screenshot from the Amazon Cognito console that illustrates the choice of plain password authentication flows for an app client. The options ALLOW_USER_PASSWORD_AUTH, ALLOW_ADMIN_USER_PASSWORD_AUTH, and ALLOW_USER_AUTH have been selected.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/screenshot-choose-password-admin-password-and-user-auth.png)


To verify that password authentication is available in choice-based authentication flows, navigate to the **Sign-in menu** and review the section under **Options for choice-based sign-in**. You can sign in with plain-password authentication if **Password** is visible under **Available choices**. The **Password** option includes the plain and SRP username-password authentication variants.

![\[A screenshot from the Amazon Cognito console that illustrates the choice of password authentication in USER_AUTH choice-based sign-in configuration for a user pool. The Password option is displayed as active.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/screenshot-password-flow-in-user-auth.png)


Configure `ExplicitAuthFlows` with your preferred username-and-password authentication options in a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) request.

```
"ExplicitAuthFlows": [ 
   "ALLOW_USER_PASSWORD_AUTH",
   "ALLOW_ADMIN_USER_PASSWORD_AUTH",
   "ALLOW_USER_AUTH"
]
```

In a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) request, configure `Policies` with the choice-based authentication flows that you want to support. The `PASSWORD` value in `AllowedFirstAuthFactors` includes both the plain-password and SRP authentication flow options.

```
"Policies": {
   "SignInPolicy": {
      "AllowedFirstAuthFactors": [
         "PASSWORD",
         "EMAIL_OTP",
         "WEB_AUTHN"
      ]
   }
}
```

------
#### [ Choice-based sign-in with a password ]

To sign a user in to an application with username-password authentication, configure the body of your [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) or [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) request as follows. This sign-in request succeeds or continues to the next challenge if the current user is eligible for username-password authentication. Otherwise, it responds with a list of available primary-factor authentication challenges. This set of parameters is the minimum required for sign-in. Additional parameters are available.

```
{
   "AuthFlow": "USER_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser",
      "PREFERRED_CHALLENGE" : "PASSWORD",
      "PASSWORD" : "[User's password]"
   },
   "ClientId": "1example23456789"
}
```

You can also omit the `PREFERRED_CHALLENGE` value and receive a response that contains a list of eligible sign-in factors for the user.

```
{
   "AuthFlow": "USER_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser"
   },
   "ClientId": "1example23456789"
}
```

If you didn't submit a preferred challenge or the submitted user isn't eligible for their preferred challenge, Amazon Cognito returns a list of options in `AvailableChallenges`. When `AvailableChallenges` includes a `ChallengeName` of `PASSWORD`, you can continue authentication with a [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) or [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) challenge response in the format that follows. You must pass a `Session` parameter that associates the challenge response with the API response to your initial sign-in request. This set of parameters is the minimum required for sign-in. Additional parameters are available.

```
{
   "ChallengeName": "PASSWORD",
   "ChallengeResponses": { 
      "USERNAME" : "testuser",
      "PASSWORD" : "[User's Password]"
   },
   "ClientId": "1example23456789",
   "Session": "[Session ID from the previous response"
}
```

Amazon Cognito responds to eligible and successful preferred-challenge requests and `PASSWORD` challenge responses with tokens or an additional required challenge like multi-factor authentication (MFA).

------
#### [ Client-based sign-in with a password ]

To sign a user in to a client-side app with username-password authentication, configure the body of your [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) request as follows. This set of parameters is the minimum required for sign-in. Additional parameters are available.

```
{
   "AuthFlow": "USER_PASSWORD_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser",
      "PASSWORD" : "[User's password]"
   },
   "ClientId": "1example23456789"
}
```

To sign a user in to a server-side app with username-password authentication, configure the body of your [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) request as follows. Your application must sign this request with AWS credentials. This set of parameters is the minimum required for sign-in. Additional parameters are available.

```
{
   "AuthFlow": "ADMIN_USER_PASSWORD_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser",
      "PASSWORD" : "[User's password]"
   },
   "ClientId": "1example23456789"
}
```

Amazon Cognito responds to successful requests with tokens or an additional required challenge like multi-factor authentication (MFA).

------

## Sign-in with persistent passwords and secure payload
<a name="amazon-cognito-user-pools-authentication-flow-methods-srp"></a>

Another form of the username-password sign-in methods in user pools is with the Secure Remote Password (SRP) protocol. This option sends proof of knowledge of a password—a password hash and a salt—that your user pool can verify. With no readable secret information in the request to Amazon Cognito, your application is the only entity that processes the passwords that users enter. SRP authentication involves mathematical calculations that are best done by an existing component that you can import in your SDK. SRP is typically implemented in client-side applications like mobile apps. For more information about the protocol, see [The Stanford SRP Homepage](http://srp.stanford.edu/). [Wikipedia](https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol) also has resources and examples. [A variety of public libraries](https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol#Implementations) are available to perform the SRP calculations for your authentication flows.

The initiate-challenge-respond sequence of Amazon Cognito authentication validates users and their passwords with SRP. You must configure your user pool and app client to support SRP authentication, then implement the logic of sign-in requests and challenge responses in your application. Your SRP libraries can generate the random numbers and calculated values that demonstrate to your user pool that you are in possession of a user's password. Your application fills in these calculated values to the JSON-formatted `AuthParameters` and `ChallengeParameters` fields in the Amazon Cognito user pools API operations and SDK methods for authentication.

------
#### [ Activate SRP sign-in ]

To activate [client-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-client) with username and SRP, configure your app client to permit it. In the Amazon Cognito console, navigate to the **App clients** menu under **Applications** in your user pool configuration. To permit SRP sign-in for a client-side mobile or native app, edit an app client and choose **Sign in with secure remote password (SRP): ALLOW\$1USER\$1SRP\$1AUTH** under **Authentication flows**.

To activate [choice-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) with username and SRP, edit your app client and choose **Choice-based sign-in: ALLOW\$1USER\$1AUTH**.

![\[A screenshot from the Amazon Cognito console that illustrates the choice of secure remote password authentication flows for an app client. The options ALLOW_USER_SRP_AUTH and ALLOW_USER_AUTH have been selected.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/screenshot-choose-SRP-and-user-auth.png)


To verify that SRP authentication is available in your choice-based authentication flows, navigate to the **Sign-in menu** and review the section under **Options for choice-based sign-in**. You can sign in with SRP authentication if **Password** is visible under **Available choices**. The **Password** option includes the plaintext and SRP username-password authentication variants.

![\[A screenshot from the Amazon Cognito console that illustrates the choice of password authentication in USER_AUTH choice-based sign-in configuration for a user pool. The Password option is displated as active.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/screenshot-password-flow-in-user-auth.png)


Configure `ExplicitAuthFlows` with your preferred username-and-password authentication options in a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) request.

```
"ExplicitAuthFlows": [ 
   "ALLOW_USER_SRP_AUTH",
   "ALLOW_USER_AUTH"
]
```

In a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) request, configure `Policies` with the choice-based authentication flows that you want to support. The `PASSWORD` value in `AllowedFirstAuthFactors` includes both the plaintext-password and SRP authentication flow options.

```
"Policies": {
   "SignInPolicy": {
      "AllowedFirstAuthFactors": [
         "PASSWORD",
         "EMAIL_OTP",
         "WEB_AUTHN"
      ]
   }
}
```

------
#### [ Choice-based sign-in with SRP ]

To sign a user in to an application with username-password authentication with SRP, configure the body of your [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) or [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) request as follows. This sign-in request succeeds or continues to the next challenge if the current user is eligible for username-password authentication. Otherwise, it responds with a list of available primary-factor authentication challenges. This set of parameters is the minimum required for sign-in. Additional parameters are available.

```
{
   "AuthFlow": "USER_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser",
      "PREFERRED_CHALLENGE" : "PASSWORD_SRP",
      "SRP_A" : "[g^a % N]"
   },
   "ClientId": "1example23456789"
}
```

You can also omit the `PREFERRED_CHALLENGE` value and receive a response that contains a list of eligible sign-in factors for the user.

```
{
   "AuthFlow": "USER_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser"
   },
   "ClientId": "1example23456789"
}
```

If you didn't submit a preferred challenge or the submitted user isn't eligible for their preferred challenge, Amazon Cognito returns a list of options in `AvailableChallenges`. When `AvailableChallenges` includes a `ChallengeName` of `PASSWORD_SRP`, you can continue authentication with a [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) or [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) challenge response in the format that follows. You must pass a `Session` parameter that associates the challenge response with the API response to your initial sign-in request. This set of parameters is the minimum required for sign-in. Additional parameters are available.

```
{
   "ChallengeName": "PASSWORD_SRP",
   "ChallengeResponses": { 
      "USERNAME" : "testuser",
      "SRP_A" : "[g^a % N]"
   },
   "ClientId": "1example23456789",
   "Session": "[Session ID from the previous response"
}
```

Amazon Cognito responds to eligible preferred-challenge requests and `PASSWORD_SRP` challenge responses with a `PASSWORD_VERIFIER` challenge. Your client must complete SRP calculations and respond to the challenge in a [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) or [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) request.

```
{
   "ChallengeName": "PASSWORD_VERIFIER",
   "ChallengeResponses": { 
      "PASSWORD_CLAIM_SIGNATURE" : "string",
      "PASSWORD_CLAIM_SECRET_BLOCK" : "string",
      "TIMESTAMP" : "string"
   },
   "ClientId": "1example23456789",
   "Session": "[Session ID from the previous response]"
}
```

On a successful `PASSWORD_VERIFIER` challenge response, Amazon Cognito issues tokens or another required challenge like multi-factor authentication (MFA).

------
#### [ Client-based sign-in with SRP ]

SRP authentication is more common to client-side authentication than to server-side. However, you can use SRP authentication with [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html). To sign a user in to an application, configure the body of your `InitiateAuth` or `AdminInitiateAuth` request as follows. This set of parameters is the minimum required for sign-in. Additional parameters are available.

The client generates `SRP_A` from a generator modulo N *g* raised to the power of a secret random integer *a*.

```
{
   "AuthFlow": "USER_SRP_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser",
      "SRP_A" : "[g^a % N]"
   },
   "ClientId": "1example23456789"
}
```

Amazon Cognito responds with a `PASSWORD_VERIFIER` challenge. Your client must complete SRP calculations and respond to the challenge in a [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) or [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) request.

```
{
   "ChallengeName": "PASSWORD_VERIFIER",
   "ChallengeResponses": { 
      "PASSWORD_CLAIM_SIGNATURE" : "string",
      "PASSWORD_CLAIM_SECRET_BLOCK" : "string",
      "TIMESTAMP" : "string"
   },
   "ClientId": "1example23456789",
   "Session": "[Session ID from the previous response]"
}
```

On a successful `PASSWORD_VERIFIER` challenge response, Amazon Cognito issues tokens or another required challenge like multi-factor authentication (MFA).

------

## Passwordless sign-in with one-time passwords
<a name="amazon-cognito-user-pools-authentication-flow-methods-passwordless"></a>

Passwords can be lost or stolen. You might want to verify only that your users have access to a verified email address, phone number, or authenticator app. The solution to this is *passwordless* sign-in. Your application can prompt users to enter their username, email address, or phone number. Amazon Cognito then generates a one-time password (OTP), a code that they must confirm. A successful code completes authentication.

One-time password (OTP) authentication flows aren't compatible with required multi-factor authentication (MFA) in your user pool. Passkey authentication with user verification can satisfy MFA requirements when you set `FactorConfiguration` to `MULTI_FACTOR_WITH_USER_VERIFICATION`. If MFA is optional in your user pool, users who have activated MFA can't sign in with an OTP first factor. Users who don't have an MFA preference in an MFA-optional user pool can sign in with passwordless factors. For more information, see [Things to know about user pool MFA](user-pool-settings-mfa.md#user-pool-settings-mfa-prerequisites).

When a user correctly enters a code they received in an SMS or email message as part of passwordless authentication, in addition to authenticating the user, your user pool marks the user’s unverified email address or phone number attribute as verified. The user status also changed from `UNCONFIRMED` to `CONFIRMED`, regardless of whether you configured your user pool to [automatically verify](signing-up-users-in-your-app.md) email addresses or phone numbers.

**New options with passwordless sign-in**  
When you activate passwordless authentication in your user pool, it changes how some user flows work.

1. Users can sign up without a password and choose a passwordless factor when they sign in. You can also create users without passwords as an administrator.

1. Users who you [import with a CSV file](cognito-user-pools-using-import-tool.md) can sign in immediately with a passwordless factor. They aren't required to set a password before sign-in.

1. Users who don't have a password can submit [ChangePassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ChangePassword.html) API requests without the `PreviousPassword` parameter.

**Automatic sign-in with OTPs**  
Users who sign up and confirm their user accounts with email or SMS message OTPs can automatically sign in with the passwordless factor that matches their confirmation message. In the managed login UI, users who confirm their accounts and are eligible for OTP sign-in with the confirmation-code delivery method automatically proceed through to their first sign-in after they provide the confirmation code. In your custom-built application with an AWS SDK, pass the following parameters to an [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) operation.
+ The `Session` parameter from the [ConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html) API response as the `Session` request parameter.
+ An [AuthFlow](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-request-AuthFlow) of `USER_AUTH`.

You can pass a [PREFERRED\$1CHALLENGE](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-request-AuthParameters) of `EMAIL_OTP` or `SMS_OTP`, but it's not required. The `Session` parameter provides proof of authentication and Amazon Cognito ignores the `AuthParameters` when you pass a valid session code.

The sign-in operation returns the response that indicates successful authentication, [AuthenticationResult](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AuthenticationResultType.html), with no additional challenges if the following conditions are true.
+ The `Session` code is valid and not expired.
+ The user is eligible for the OTP authentication method.

------
#### [ Activate passwordless sign-in ]

**Console**  
To activate passwordless sign-in, configure your user pool to permit primary sign-in with one or more passwordless types, then configure your app client to permit the `USER_AUTH` flow. In the Amazon Cognito console, navigate to the **Sign-in** menu under **Authentication** in your user pool configuration. Edit **Options for choice-based sign-in** and choose **Email message one-time password** or **SMS message one-time password**. You can activate both options. Save your changes.

Navigate to the **App clients** menu and choose an app client or create a new one. Select **Edit** and choose **Select an authentication type at sign-in: ALLOW\$1USER\$1AUTH**.

**API/SDK**  
In the user pools API, configure `SignInPolicy` with the appropriate passwordless options in a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) request.

```
"SignInPolicy": { 
    "AllowedFirstAuthFactors": [ 
        "EMAIL_OTP",
        "SMS_OTP"
    ]
}
```

Configure your app client `ExplicitAuthFlows` with the required option in a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) request.

```
"ExplicitAuthFlows": [ 
   "ALLOW_USER_AUTH"
]
```

------
#### [ Sign in with passwordless ]

Passwordless sign-in doesn't have a [client-based](authentication-flows-selection-sdk.md#authentication-flows-selection-client) `AuthFlow` that you can specify in [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html). OTP authentication is only available in the [choice-based](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) `AuthFlow` of `USER_AUTH`, where you can request a preferred sign-in option or choose the passwordless option from a user's [AvailableChallenges](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-response-AvailableChallenges). To sign a user in to an application, configure the body of your `InitiateAuth` or `AdminInitiateAuth` request as follows. This set of parameters is the minimum required for sign-in. Additional parameters are available.

In this example, we don't know which way the user wants to sign in. If we add a `PREFERRED_CHALLENGE` parameter and the preferred challenge is available to the user, Amazon Cognito responds with that challenge.

```
{
   "AuthFlow": "USER_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser"
   },
   "ClientId": "1example23456789"
}
```

You can instead add `"PREFERRED_CHALLENGE": "EMAIL_OTP"` or `"PREFERRED_CHALLENGE": "SMS_OTP"` to `AuthParameters` in this example. If the user is eligible for that preferred method, your user pool immediately sends a code to the user's email address or phone number and returns `"ChallengeName": "EMAIL_OTP"` or `"ChallengeName": "SMS_OTP"`.

If you don't specify a preferred challenge, Amazon Cognito responds with an `AvailableChallenges` parameter.

```
{
   "AvailableChallenges": [ 
      "EMAIL_OTP", 
      "SMS_OTP",
      "PASSWORD"
    ],
   "Session": "[Session ID]"
}
```

This user is eligible for passwordless sign-in with email message OTP, SMS message OTP, and username-password. Your application can prompt the user for their selection, or make a selection based on internal logic. It then proceeds with a [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) or [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) request that selects the challenge. Suppose the user wants to complete passwordless authentication with an email-message OTP.

```
{
   "ChallengeName": "SELECT_CHALLENGE",
   "ChallengeResponses": { 
      "USERNAME" : "testuser",
      "ANSWER" : "EMAIL_OTP" 
   },
   "ClientId": "1example23456789",
   "Session": "[Session ID from the previous response]"
}
```

Amazon Cognito responds with an `EMAIL_OTP` challenge and sends a code to your user's verified email address. Your application then must respond again to this challenge.

This would also be the next challenge response if you requested `EMAIL_OTP` as a `PREFERRED_CHALLENGE`.

```
{
   "ChallengeName": "EMAIL_OTP",
   "ChallengeResponses": {
      "USERNAME" : "testuser", 
      "EMAIL_OTP_CODE" : "123456" 
   },
   "ClientId": "1example23456789",
   "Session": "[Session ID from the previous response]"
}
```

------

## Passwordless sign-in with WebAuthn passkeys
<a name="amazon-cognito-user-pools-authentication-flow-methods-passkey"></a>

Passkeys are secure and impose a relatively low effort level on users. Passkey sign-in makes use of *authenticators*, external devices that users can authenticate with. Regular passwords expose users to vulnerabilities like phishing, password guessing, and credential theft. With passkeys, your application can benefit from advanced security measures on mobile phones and other devices attached to or built in to information systems. A common passkey sign-in workflow starts with a call to your device that invokes your password or *credentials* manager, for example the iOS keychain or the Google Chrome password manager. The on-device credentials manager prompts them to select a passkey and authorize it with an existing credential or device-unlock mechanism. Modern phones have face scanners, fingerprint scanners, unlock patterns and other mechanisms, some that simultaneously satisfy the *something you know* and *something you have* principles of strong authentication. In the case of passkey authentication with biometrics, passkeys represent a *something you are*.

You might want to replace passwords with the thumbprint, face, or security-key authentication. This is *passkey* or *WebAuthn* authentication. It's common for application developers to permit users to enroll a biometric device after they first sign in with a password. With Amazon Cognito user pools, your application can configure this sign-in option for users. Passkey authentication can satisfy multi-factor authentication (MFA) requirements when your user pool has `FactorConfiguration` set to `MULTI_FACTOR_WITH_USER_VERIFICATION`. In this configuration, passkey authentication with user verification counts as multi-factor authentication.

One-time password (OTP) authentication flows aren't compatible with required multi-factor authentication (MFA) in your user pool. Passkey authentication with user verification can satisfy MFA requirements when you set `FactorConfiguration` to `MULTI_FACTOR_WITH_USER_VERIFICATION`. If MFA is optional in your user pool, users who have activated MFA can't sign in with an OTP first factor. Users who don't have an MFA preference in an MFA-optional user pool can sign in with passwordless factors. For more information, see [Things to know about user pool MFA](user-pool-settings-mfa.md#user-pool-settings-mfa-prerequisites).

### What are passkeys?
<a name="amazon-cognito-user-pools-authentication-flow-methods-passkey-what-are"></a>

Passkeys simplify the user experience by eliminating the need to remember complex passwords or enter OTPs. Passkeys are based on WebAuthn and CTAP2 standards drafted by the [World Wide Web Consortium](https://www.w3.org/TR/webauthn-3/) (W3C) and FIDO (Fast Identity Online) Alliance. Browsers and platforms implement these standards, provide APIs for web or mobile applications to start a passkey registration or authentication process, and also UI for user to select and interact with a passkey *authenticator*.

When a user registers an authenticator with a website or an app, the authenticator creates a public-private key pair. WebAuthn browsers and platforms submit the public key to the application back end of the website or app. The authenticator keeps the private key, key IDs, and metadata about the user and application. When the user wants to authenticate in the registered application with their registered authenticator, the application generates a random challenge. The response to this challenge is the digital signature of the challenge generated with the private key of the authenticator for that application and user, and relevant metadata. The browser or application platform receives the digital signature and passes it to the application back end. The application then validates the signature with the stored public key.

**Note**  
Your application doesn't receive any authentication secrets that users provide to their authenticator, nor does it receive information about the private key.

The following are some examples and capabilities of authenticators currently on the market. An authenticator might meet any or all of these categories.
+ Some authenticators perform *user verification* with factors like a PIN, biometric input with a face or fingerprint, or a passcode before granting access, ensuring that only the legitimate user can authorize actions. Other authenticators don't have any user verification capabilities, and some can skip user verification when an application doesn't require it.
+ Some authenticators, for example YubiKey hardware tokens, are portable. They communicate with devices through USB, Bluetooth or NFC connections. Some authenticators are local and bound to a platform, for example Windows Hello on a PC or Face ID on an iPhone. A device-bound authenticator can be carried by user if small enough, like a mobile device. Sometimes users can connect their hardware authenticator with many different platforms with wireless communication. For example, users in desktop browsers can use their smart phone as a passkey authenticator when they scan a QR code.
+ Some platform-bound passkeys sync to the cloud so that they can be used from multiple locations. For example, Face ID passkeys on iPhones sync passkey metadata with users' Apple accounts in their iCloud Keychain. These passkeys grant seamless authentication across Apple devices, instead of requiring that users register each device independently. Software-based authenticator apps like 1Password, Dashlane, and Bitwarden sync passkeys across all platforms where the user has installed the app.

In WebAuthn terminology, websites and apps are *relying parties*. Each passkey is associated with a specific relying party ID, a unified identifier that represents the websites or apps that accept passkey authentication.. Developers must carefully select their relying party ID to have the right scope of authentication. A typical reliying party ID is the root domain name of a webserver. A passkey with this relying party ID specification can authenticate for that domain and subdomains. Browsers and platforms deny passkey authentication when the URL of the website a user want to access doesn't match the relying party ID. Similarly, for mobile apps, a passkey can only be used if the app path is present in the `.well-known` association files that the application makes available at the path indicated by the relying party ID.

Passkeys are *discoverable*. They can be automatically recognized and used by a browser or platform without requiring the user to input a username. When a user visits a website or app that supports passkey authentication, they can select from a list of passkeys that the browser or platform already knows, or they can scan a QR code.

### How does Amazon Cognito implement passkey authentication?
<a name="amazon-cognito-user-pools-authentication-flow-methods-passkey-cognito"></a>

Passkeys are an opt-in feature that's available in all [feature plans](cognito-sign-in-feature-plans.md) except for **Lite**. It is only available in the [choice-based authentication flow](authentication-flows-selection-sdk.md#authentication-flows-selection-choice). With [managed login](authentication-flows-selection-managedlogin.md), Amazon Cognito handles the logic of passkey authentication. You can also use the [Amazon Cognito user pools API in AWS SDKs](#amazon-cognito-user-pools-authentication-flow-methods) to do passkey authentication in your application back end.

Amazon Cognito recognizes passkeys created using either of two asymmetric cryptographic algorithms, ES256(-7) and RS256(-257). Most authenticators support both algorithms. By default, users can set up any type of authenticators, for example hardware tokens, mobile smart phones, and software authenticator apps. Amazon Cognito doesn't currently support [attestation](https://csrc.nist.gov/glossary/term/attestation) enforcement.

In your user pool, you can configure user verification to be preferred or required. This setting defaults to preferred in API requests that don't provide a value, and preferred is selected by default in the Amazon Cognito console. When you set user verification to preferred, users can set up authenticators that don't have the user verification capability, and registration and authentication operations can succeed without user verification. To mandate user verification in passkey registration and authentication, change this setting to required.

The relying party (RP) ID that you set in your passkey configuration is an important decision. When you don't specify otherwise and your [domain branding version](managed-login-branding.md) is managed login, your user pool defaults to expecting the name of your [custom domain](cognito-user-pools-add-custom-domain.md) as the RP ID. If you don't have a custom domain and don't specify otherwise, your user pool defaults to an RP ID of your [prefix domain](cognito-user-pools-assign-domain-prefix.md). You can also configure your RP ID to be any domain name not in the public suffix list (PSL). Your RP ID entry applies to passkey registration and authentication in managed login and in SDK authentication. Passkey is only functional in mobile applications with Amazon Cognito can locate a `.well-known` association file with your RP ID as the domain. As a best practice, determine and set the value of your relying party ID before your website or app is publicly available. If you change your RP ID, your users must register again with the new RP ID.

Each user can register up to 20 passkeys. They can only register a passkey after they have signed in to your user pool at least once. Managed login removes significant effort from passkey registration. When you enable passkey authentication for a user pool and app client, your user pool with a managed login domain reminds end users to register a passkey after they sign up for a new user account. You can also invoke users' browsers at any time to direct them to a managed login page for passkey registration. Users must provide a username before Amazon Cognito can initiate passkey authentication. Managed login handles this automatically. The sign-in page prompts for a username, validates that the user has at least one passkey registered, and then prompts for passkey sign-in. Similarly, SDK-based applications must prompt for a username and provide it in the authentication request.

When you set up user pool authentication with passkeys and you have a custom domain and a prefix domain, the RP ID defaults to the fully-qualified domain name (FQDN) of your custom domain. To set a prefix domain as the RP ID in the Amazon Cognito console, delete your custom domain or enter the FQDN of the prefix domain as a **Third-party domain**.

------
#### [ Activate passkey sign-in ]

**Console**  
To activate sign-in with passkeys, configure your user pool to permit primary sign-in with one or more passwordless types, then configure your app client to permit the `USER_AUTH` flow. In the Amazon Cognito console, navigate to the **Sign-in** menu under **Authentication** in your user pool configuration. Edit **Options for choice-based sign-in** and add **Passkey** to the list of **Available choices**.

Navigate to the **Authentication methods** menu and edit **Passkey**.
+ **User verification** is the setting for whether your user pool requires passkey devices that perform additional checks that the current user is authorized for a passkey. To encourage users to configure a device with user verification, but not require it, select **Preferred**. To only support devices with user verification, select **Required**. For more information, see [User verification](https://www.w3.org/TR/webauthn-2/#user-verification) at w3.org.
+ The **Domain for relying party ID** is the identifier that your application will pass in users' passkey registration requests. It sets the target of the trust relationship with the issuer of users' passkeys. Your relying party ID can be: the domain of your user pool if   
**Cognito domain**  
The Amazon Cognito [prefix domain](cognito-user-pools-assign-domain-prefix.md) of your user pool.  
**Custom domain**  
The [custom domain](cognito-user-pools-add-custom-domain.md) of your user pool.  
**Third-party domain**  
The domain for applications that don't use the user pools managed login pages. This setting is typically associated with user pools that don't have a [domain](cognito-user-pools-assign-domain.md) and perform authentication with an AWS SDK and the user pools API in the backend.

Navigate to the **App clients** menu and choose an app client or create a new one. Select **Edit** and under **Authentication flows**, choose **Select an authentication type at sign-in: ALLOW\$1USER\$1AUTH**.

**API/SDK**  
In the user pools API, configure `SignInPolicy` with the appropriate passkey options in a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) request. The `WEB_AUTHN` option for passkey authentication must be accompanied by at least one other option. Passkey registration requires an existing authentication session.

```
"SignInPolicy": { 
    "AllowedFirstAuthFactors": [ 
        "PASSWORD",
        "WEB_AUTHN"
    ]
}
```

Configure your user-verification preference and RP ID in the `WebAuthnConfiguration` parameter of a [SetUserPoolMfaConfig](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserPoolMfaConfig.html#CognitoUserPools-SetUserPoolMfaConfig-request-WebAuthnConfiguration) request. The `RelyingPartyId`, the intended target of passkey authentication outcomes, can be your user pool prefix or custom domain, or a domain of your own choosing.

```
"WebAuthnConfiguration": { 
   "RelyingPartyId": "example.auth.us-east-1.amazoncognito.com",
   "UserVerification": "preferred",
   "FactorConfiguration": "SINGLE_FACTOR"
}
```

Configure your app client `ExplicitAuthFlows` with the required option in a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) request.

```
"ExplicitAuthFlows": [ 
   "ALLOW_USER_AUTH"
]
```

------
#### [ Register a passkey (managed login) ]

Managed login handles user registration of passkeys. When passkey authentication is active in your user pool, Amazon Cognito prompts users to set up a passkey when the register for a new user account.

Amazon Cognito doesn't prompt users to set up a passkey when they have already signed up and not set up a passkey, or if you created their account as an administrator. Users in this state must sign in with another factor like a password or passwordless OTP before they can register a passkey.

**To register a passkey**

1. Direct the user to your [sign-in page](authorization-endpoint.md).

   ```
   https://auth.example.com/oauth2/authorize/?client_id=1example23456789&response_type=code&scope=email+openid+phone&redirect_uri=https%3A%2F%2Fwww.example.com
   ```

1. Process the authentication result from the user. In this example, Amazon Cognito redirects them to `www.example.com` with an authorization code that your application exchanges for tokens.

1. Direct the user to your register-passkey page. The user will have a browser cookie that maintains their signed-in session. The passkey URL takes `client_id` and `redirect_uri` parameters. Amazon Cognito only permits authenticated users to access this page. Sign in your user with a password, email OTP, or SMS OTP and then invoke a URL that matches the following pattern.

   You can also add other [Authorize endpoint](authorization-endpoint.md) parameters to this request, like `response_type` and `scope`.

   ```
   https://auth.example.com/passkeys/add?client_id=1example23456789&redirect_uri=https%3A%2F%2Fwww.example.com
   ```

------
#### [ Register a passkey (SDK) ]

You register passkey credentials with metadata in a [PublicKeyCreationOptions](https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialcreationoptions) object. You can generate this object with the credentials of a signed-in user and present them in an API request to their passkey issuer. The issuer will return a [RegistrationResponseJSON](https://www.w3.org/TR/webauthn-3/#dictdef-registrationresponsejson) object that confirms passkey registration.

To start the process of passkey registration, sign in a user with an existing sign-in option. Authorize the [token-authorized](authentication-flows-public-server-side.md#user-pool-apis-auth-unauth-token-auth) [StartWebAuthnRegistration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StartWebAuthnRegistration.html) API request with the current user's access token. The following is the body of an example `GetWebAuthnRegistrationOptions` request.

```
{
   "AccessToken": "eyJra456defEXAMPLE"
}
```

The response from your user pool contains the `PublicKeyCreationOptions` object. Present this object in an API request to the user's issuer. It provides information like the public key and relying party ID. The issuer will respond with a `RegistrationResponseJSON` object.

Present the registration response in a [CompleteWebAuthnRegistration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CompleteWebAuthnRegistration.html) API request, again authorized with the user's access token. When your user pool responds with an HTTP 200 response with an empty body, your user's passkey is registered.

------
#### [ Sign in with a passkey ]

Passwordless sign-in doesn't have an `AuthFlow` that you can specify in [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html). Instead, you must declare an `AuthFlow` of `USER_AUTH` and request a sign-in option or choose your passwordless option from the response from your user pool. To sign a user in to an application, configure the body of your `InitiateAuth` or `AdminInitiateAuth` request as follows. This set of parameters is the minimum required for sign-in. Additional parameters are available.

In this example, we know that the user wants to sign in with a passkey, and we add a `PREFERRED_CHALLENGE` parameter.

```
{
   "AuthFlow": "USER_AUTH",
   "AuthParameters": { 
      "USERNAME" : "testuser",
      "PREFERRED_CHALLENGE" : "WEB_AUTHN"
   },
   "ClientId": "1example23456789"
}
```

Amazon Cognito responds with a `WEB_AUTHN` challenge. Your application must respond to this challenge. Initiate a sign-in request with the user's passkey provider. It will return an [AuthenticationResponseJSON](https://www.w3.org/TR/webauthn-3/#dictdef-authenticationresponsejson) object.

```
{
   "ChallengeName": "WEB_AUTHN",
   "ChallengeResponses": {
      "USERNAME" : "testuser", 
      "CREDENTIAL" : "{AuthenticationResponseJSON}" 
   },
   "ClientId": "1example23456789",
   "Session": "[Session ID from the previous response]"
}
```

------

## MFA after sign-in
<a name="amazon-cognito-user-pools-authentication-flow-methods-mfa"></a>

You can set up users who complete sign-in with a username-password flow to be prompted for additional verification with a one-time password from an email message, SMS message, or code-generating application. MFA is distinct from passwordless sign-in with one-time passwords. However, passkeys with user verification can satisfy MFA requirements when you configure `FactorConfiguration` as `MULTI_FACTOR_WITH_USER_VERIFICATION` in your user pool `WebAuthnConfiguration`. For password-based flows, MFA in user pools is a challenge-response model where a user first demonstrates they know the password, then demonstrates that they have access to their registered second-factor device.

**Implementation resources**
+ [Adding MFA to a user pool](user-pool-settings-mfa.md)

## Refresh tokens
<a name="amazon-cognito-user-pools-authentication-flow-methods-refresh"></a>

When you want to keep users signed in without re-entering their credentials, *refresh tokens* are the tool that your application has to persist a user's session. Applications can present refresh tokens to your user pool and exchange them for new ID and access tokens. With token refresh, you can ensure that a signed-in user is still active, get updated attribute information, and update access-control entitlements without user intervention.

**Implementation resources**
+ [Refresh tokens](amazon-cognito-user-pools-using-the-refresh-token.md)

## Custom authentication
<a name="amazon-cognito-user-pools-authentication-flow-methods-custom"></a>

You might want to configure a method of authentication for your users that isn't listed here. You can do that with *custom authentication* with Lambda triggers. In a sequence of Lambda functions, Amazon Cognito issues a challenge, asks a question that users must answer, checks the answer for accuracy, then determines if another challenge should be issued. The questions and answers can include security questions, requests to a CAPTCHA service, requests to an external MFA service API, or all of these in sequence.

**Implementation resources**
+ [Custom authentication challenge Lambda triggers](user-pool-lambda-challenge.md)

### Custom authentication flow
<a name="amazon-cognito-user-pools-custom-authentication-flow"></a>

Amazon Cognito user pools also make it possible to use custom authentication flows, which can help you create a challenge/response-based authentication model using AWS Lambda triggers.

The custom authentication flow makes possible customized challenge and response cycles to meet different requirements. The flow starts with a call to the `InitiateAuth` API operation that indicates the type of authentication to use and provides any initial authentication parameters. Amazon Cognito responds to the `InitiateAuth` call with one of the following types of information: 
+ A challenge for the user, along with a session and parameters.
+ An error if the user fails to authenticate.
+ ID, access, and refresh tokens if the supplied parameters in the `InitiateAuth` call are sufficient to sign the user in. (Typically the user or app must first answer a challenge, but your custom code must determine this.)

 If Amazon Cognito responds to the `InitiateAuth` call with a challenge, the app gathers more input and calls the `RespondToAuthChallenge` operation. This call provides the challenge responses and passes it back the session. Amazon Cognito responds to the `RespondToAuthChallenge` call similarly to the `InitiateAuth` call. If the user has signed in, Amazon Cognito provides tokens, or if the user isn't signed in, Amazon Cognito provides another challenge, or an error. If Amazon Cognito returns another challenge, the sequence repeats and the app calls `RespondToAuthChallenge` until the user successfully signs in or an error is returned. For more details about the `InitiateAuth` and `RespondToAuthChallenge` API operations, see the [API documentation](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html). 

### Custom authentication flow and challenges
<a name="Custom-authentication-flow-and-challenges"></a>

An app can initiate a custom authentication flow by calling `InitiateAuth` with `CUSTOM_AUTH` as the `Authflow`. With a custom authentication flow, three Lambda triggers control challenges and verification of the responses.
+ The `DefineAuthChallenge` Lambda trigger uses a session array of previous challenges and responses as input. It then generates the next challenge name and Booleans that indicate whether the user is authenticated and can be granted tokens. This Lambda trigger is a state machine that controls the user’s path through the challenges.
+ The `CreateAuthChallenge` Lambda trigger takes a challenge name as input and generates the challenge and parameters to evaluate the response. When `DefineAuthChallenge` returns `CUSTOM_CHALLENGE` as the next challenge, the authentication flow calls `CreateAuthChallenge`. The `CreateAuthChallenge` Lambda trigger passes the next type of challenge in the challenge metadata parameter.
+ The `VerifyAuthChallengeResponse` Lambda function evaluates the response and returns a Boolean to indicate if the response was valid.

A custom authentication flow can also use a combination of built-in challenges, such as SRP password verification and MFA through SMS. It can use custom challenges such as CAPTCHA or secret questions.

### Use SRP password verification in custom authentication flow
<a name="Using-SRP-password-verification-in-custom-authentication-flow"></a>

If you want to include SRP in a custom authentication flow, you must begin with SRP.
+ To initiate SRP password verification in a custom flow, the app calls `InitiateAuth` with `CUSTOM_AUTH` as the `Authflow`. In the `AuthParameters` map, the request from your app includes `SRP_A:` (the SRP A value) and `CHALLENGE_NAME: SRP_A`.
+ The `CUSTOM_AUTH` flow invokes the `DefineAuthChallenge` Lambda trigger with an initial session of `challengeName: SRP_A` and `challengeResult: true`. Your Lambda function responds with `challengeName: PASSWORD_VERIFIER`, `issueTokens: false`, and `failAuthentication: false`.
+  The app next must call `RespondToAuthChallenge` with `challengeName: PASSWORD_VERIFIER` and the other parameters required for SRP in the `challengeResponses` map. 
+ If Amazon Cognito verifies the password, `RespondToAuthChallenge` invokes the `DefineAuthChallenge` Lambda trigger with a second session of `challengeName: PASSWORD_VERIFIER` and `challengeResult: true`. At that point, the `DefineAuthChallenge` Lambda trigger responds with `challengeName: CUSTOM_CHALLENGE` to start the custom challenge.
+ If MFA is enabled for a user, after Amazon Cognito verifies the password, your user is then challenged to set up or sign in with MFA.

**Note**  
The Amazon Cognito hosted sign-in webpage can't activate [Custom authentication challenge Lambda triggers](user-pool-lambda-challenge.md).

For more information about the Lambda triggers, including sample code, see [Customizing user pool workflows with Lambda triggers](cognito-user-pools-working-with-lambda-triggers.md).

## User migration authentication flow
<a name="amazon-cognito-user-pools-user-migration-authentication-flow"></a>

A user migration Lambda trigger helps migrate users from a legacy user management system into your user pool. If you choose the `USER_PASSWORD_AUTH` authentication flow, users don't have to reset their passwords during user migration. This flow sends your users' passwords to the service over an encrypted SSL connection during authentication.

When you have migrated all your users, switch flows to the more secure SRP flow. The SRP flow doesn't send any passwords over the network.

To learn more about Lambda triggers, see [Customizing user pool workflows with Lambda triggers](cognito-user-pools-working-with-lambda-triggers.md).

For more information about migrating users with a Lambda trigger, see [Importing users with a user migration Lambda trigger](cognito-user-pools-import-using-lambda.md).

# Authorization models for API and SDK authentication
<a name="authentication-flows-public-server-side"></a>

When you're starting development of your application with user pools authentication, you must decide on the API authorization model that fits your application type. An authorization model is a system for providing authorization to make requests with the authentication components in the Amazon Cognito user pools API and SDK integrations. Amazon Cognito has three authorization models: IAM-authorized, public, and token-authorized.

With IAM-authorized requests, the authorization comes from a signature by a set of AWS IAM credentials in the `Authorization` header of a request. For server-side applications, this practice protects authentication operations with IAM authorization. With public (unauthenticated) authentication requests, no authorization is required. This is suitable for client-side applications distributed to users. With token-authorized operations, typically implemented in combination with public operations, the authorization comes from a session token or an access token included in the `Authorization` header of the request. Amazon Cognito authentication typically requires that you implement two or more API operations in order, and the API operations you use depend on the characteristics of your application. Public clients, where the application is distributed to users, use public operations, where requests for sign-in don't require authorization. Token-authorized operations continue the session of users in public applications. Server-side clients, where the application logic is hosted on a remote system, protect authentication operations with IAM authorization for sign-in requests. The API operation pairs that follow, and their corresponding SDK methods, map to the available authorization models.

Each public authentication operation has some form of server-side equivalent, for example [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html) and [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html). While client-side operations are user-initiated and require confirmation, server-side operations assume the change was committed by a user pool administrator and changes take immediate effect. In this example, Amazon Cognito sends a message with a confirmation code to the user, and the user's access token authorizes a [VerifyUserAttribute](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html) request that submits the code. The server-side application can immediately set the value of any attribute, although [special considerations apply](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html#CognitoUserPools-AdminUpdateUserAttributes-request-UserAttributes) for changing the value of email addresses and phone numbers when they're used for sign-in.

To compare API authentication and see a full list of API operations and their authorization models, see [Understanding API, OIDC, and managed login pages authentication](#user-pools-API-operations).

------
#### [ Client-side (public) authentication ]

The following is a typical sequence of requests in a client-side application

1. The public [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) operation submits primary credentials like a username and password.

1. The token-authorized [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) operation submits a *session* token from the `InitiateAuth` response and the answer to a challenge, for example MFA. Session token authorization indicates requests that are part of not-yet-complete authentication cycles.

1. The token-authorized [ConfirmDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmDevice.html) operation submits an *access* token and performs the write operation of adding a remembered device to the user's profile. Access token authorization indicates requests that are for user self-service operations after they have completed authentication.

For more information, see [Client-side authentication options](#amazon-cognito-user-pools-client-side-authentication-flow) and [Understanding API, OIDC, and managed login pages authentication](#user-pools-API-operations).

------
#### [ Server-side authentication ]

The following is a typical sequence of requests from a server-side operation. Each request has an [AWS Signature Version 4](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html) authorization header signed with IAM machine credentials that were issued to the application server.

1. The [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) operation submits primary credentials like a username and password.

1. [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) operation submits the answer to a challenge, for example MFA.

1. The [AdminUpdateDeviceStatus](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateDeviceStatus.html) operation sets the device key from the `AdminInitiateAuth` [response](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html#API_AdminInitiateAuth_ResponseSyntax) as remembered.

For more information, see [Server-side authentication options](#amazon-cognito-user-pools-server-side-authentication-flow) and [Understanding API, OIDC, and managed login pages authentication](#user-pools-API-operations).

------

A user authenticates by answering successive challenges until authentication either fails or Amazon Cognito issues tokens to the user. You can repeat these steps with Amazon Cognito, in a process that includes different challenges, to support any custom authentication flow.

**Topics**
+ [

## Server-side authentication options
](#amazon-cognito-user-pools-server-side-authentication-flow)
+ [

## Client-side authentication options
](#amazon-cognito-user-pools-client-side-authentication-flow)
+ [

## Understanding API, OIDC, and managed login pages authentication
](#user-pools-API-operations)
+ [

## List of API operations grouped by authorization model
](#user-pool-apis-auth-unauth)

## Server-side authentication options
<a name="amazon-cognito-user-pools-server-side-authentication-flow"></a>

Web applications and other *server-side* applications implement authentication on a remote server that a client loads in a remote-display application like a browser or SSH session. Server-side applications typically have the following characteristics.
+ They're built in an application installed on a server in languages like Java, Ruby, or Node.js.
+ They connect to user pool [app clients](user-pool-settings-client-apps.md) that might have a client secret, called *confidential clients*.
+ They have access to AWS credentials.
+ They invoke [managed login](cognito-user-pools-managed-login.md) for authentication, or use IAM-authorized operations in the user pools API with an AWS SDK.
+ They serve internal customers and might serve public customers.

Server-side operations with the user pools API can use passwords, one-time passwords, or passkeys as the primary sign-in factor. For server-side apps, user pool authentication is similar to authentication for client-side apps, except for the following:
+ The server-side app makes an [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) API request. This operation requires AWS credentials with permissions that include `cognito-idp:AdminInitiateAuth` and `cognito-idp:AdminRespondToAuthChallenge`. The operation returns the required challenge or authentication outcome.
+ When the application receives a challenge, it makes an [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) API request. The `AdminRespondToAuthChallenge` API operation also requires AWS credentials.

For more information about signing Amazon Cognito API requests with AWS credentials, see [Signature Version 4 signing process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) in the *AWS General Reference*.

In the `AdminInitiateAuth` response `ChallengeParameters`, the `USER_ID_FOR_SRP` attribute, if present, contains the user's actual username, not an alias (such as email address or phone number). In your call to `AdminRespondToAuthChallenge`, in the `ChallengeResponses`, you must pass this username in the `USERNAME` parameter. 

**Note**  
Because backend admin implementations use the admin authentication flow, the flow doesn't support remembered devices. When you have turned on device tracking, admin authentication succeeds, but any call to refresh the access token fails.

## Client-side authentication options
<a name="amazon-cognito-user-pools-client-side-authentication-flow"></a>

Mobile apps and other *client-side* application types are installed on users' devices and perform the logic of authentication and user interface locally. They typically have the following characteristics.
+ They're built in languages like React native, Flutter, and Swift and deploy to user devices.
+ They connect to user pool [app clients](user-pool-settings-client-apps.md) that don't have a client secret, called *public clients*.
+ They don't have access to AWS credentials that would authorize IAM-authorized API requests.
+ They invoke [managed login](cognito-user-pools-managed-login.md) for authentication, or use public and token-authorized operations in the user pools API with an AWS SDK.
+ They serve public customers and permit anyone to sign up and sign in.

Client-side operations with the user pools API can use passwords, one-time passwords, or passkeys as the primary sign-in factor. The following process works for user client-side apps that you create with [AWS Amplify](https://docs.amplify.aws/javascript/start/getting-started/) or the [AWS SDKs](https://aws.amazon.com/developer/tools/).

1. The user enters their username and password into the app.

1. The app calls the `InitiateAuth` operation with the user's username and Secure Remote Password (SRP) details.

   This API operation returns the authentication parameters.
**Note**  
The app generates SRP details with the Amazon Cognito SRP features that are built in to AWS SDKs.

1. The app calls the `RespondToAuthChallenge` operation. If the call succeeds, Amazon Cognito returns the user's tokens, and the authentication flow is complete.

   If Amazon Cognito requires another challenge, the call to `RespondToAuthChallenge` returns no tokens. Instead, the call returns a session.

1. If `RespondToAuthChallenge` returns a session, the app calls `RespondToAuthChallenge` again, this time with the session and the challenge response (for example, MFA code).

## Understanding API, OIDC, and managed login pages authentication
<a name="user-pools-API-operations"></a>

Amazon Cognito user pools are a combination of several authentication technologies. They are relying parties to external identity providers (IdPs). They are IdPs to applications that implement authentication with OpenID Connect (OIDC) SDKs. They provide authentication as issuers of JSON web tokens (JWTs) similar to OIDC authentication, but in API methods that are part of AWS SDKs. They can also be secure points of entry to your applications.

When you want to sign up, sign in, and manage users in your user pool, you have two options. 

1. Your *managed login pages* and the classic *hosted UI* include the [managed login user-interactive endpoints](managed-login-endpoints.md) and the [federation endpoints](federation-endpoints.md) that handle IdP and relying-party roles. They make up a package of public webpages that Amazon Cognito activates when you [choose a domain](cognito-user-pools-assign-domain.md) for your user pool. For a quick start with the authentication and authorization features of Amazon Cognito user pools, including pages for sign-up, sign-in, password management, and multi-factor authentication (MFA), use the built-in user interface of managed login.

   The other user pool endpoints facilitate authentication with third-party identity providers (IdPs). The services that they perform include the following.

   1. Service-provider callback endpoints for authenticated claims from your IdPs, like `saml2/idpresponse` and `oauth2/idpresponse`. When Amazon Cognito is an intermediate service provider (SP) between your app and your IdP, the callback endpoints represent the service.

   1. Endpoints that provide information about your environment, like `oauth2/userInfo` and `/.well-known/jwks.json`. Your app uses these endpoints when it verifies tokens or retrieves user profile data with OIDC or OAuth 2.0 developer libraries.

1. The [Amazon Cognito user pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html) is a set of tools for your web or mobile app to authenticate users after it collects sign-in information in your own custom front end. User pools API authentication produces the following JSON web tokens.

   1. An identity token with verifiable attribute claims from your user.

   1. An access token that authorizes your user to create token-authorized API requests to an [AWS service endpoint](https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html).
**Note**  
By default, access tokens from user pools API authentication only contain the `aws.cognito.signin.user.admin` scope. To generate an access token with additional scopes, for example to authorize a request to a third-party API, request scopes during authentication through your user pool endpoints or add custom scopes in a [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md). Access token customization adds costs to your AWS bill.

   1. A refresh token that authorizes requests for new ID and access tokens, and refreshes user identity and access-control properties.

You can link a federated user, who would normally sign in through the user pools endpoints, with a user whose profile is *local* to your user pool. A local user exists exclusively in your user pool directory without federation through an external IdP. If you link their federated identity to a local user in an [AdminLinkProviderForUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminLinkProviderForUser.html) API request, they can sign in with the user pools API. For more information, see [Linking federated users to an existing user profile](cognito-user-pools-identity-federation-consolidate-users.md).

The Amazon Cognito user pools API is dual-purpose.

1. It creates and configures your Amazon Cognito user pools resources. For example, you can create user pools, add AWS Lambda triggers, and configure the user pool domain that hosts your managed login pages.

1. It performs sign-up, sign-in and other user operations for local and linked users.

**Example scenario with the Amazon Cognito user pools API**

1. Your user selects a "Create an account" button that you created in your app. They enter an email address and password.

1. Your app sends a [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) API request and creates a new user in your user pool.

1. Your app prompts your user for an email confirmation code. Your users enters the code they received in an email message.

1. Your app sends a [ConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html) API request with the user's confirmation code.

1. Your app prompts your user for their username and password, and they enter their information.

1. Your app sends an [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API request and stores an ID token, access token, and refresh token. Your app calls OIDC libraries to manage your user's tokens and maintain a persistent session for that user.

In the Amazon Cognito user pools API, you can't sign in users who federate through an IdP. You must authenticate these users through your user pool endpoints. For more information about the user pool endpoints that include managed login, see [User pool endpoints and managed login reference](cognito-userpools-server-contract-reference.md).

Your federated users can start in managed login and select their IdP, or you can skip managed login and send your users directly to your IdP to sign in. When your API request to the [Authorize endpoint](authorization-endpoint.md) includes an IdP parameter, Amazon Cognito silently redirects your user to the IdP sign-in page.

**Example scenario with managed login pages**

1. Your user selects a "Create an account" button that you created in your app.

1. Managed login presents your user with a list of the social identity providers where you have registered developer credentials. Your user chooses Apple.

1. Your app initiates a request to the [Authorize endpoint](authorization-endpoint.md) with provider name `SignInWithApple`.

1. Your user's browser opens the Apple authentication page. Your user signs in and chooses to authorize Amazon Cognito to read their profile information.

1. Amazon Cognito confirms the Apple access token and queries your user's Apple profile.

1. Your user presents an Amazon Cognito authorization code to your app.

1. The OIDC library in your application exchanges the authorization code with the [Token endpoint](token-endpoint.md) and stores an ID token, access token, and refresh token issued by the user pool. Your app uses OIDC libraries to manage your user's tokens and maintain a persistent session for that user.

The user pools API and managed login pages support a variety of scenarios, described throughout this guide. The following sections examine how the user pools API further divides into classes that support your sign-up, sign-in, and resource-management requirements.

## List of API operations grouped by authorization model
<a name="user-pool-apis-auth-unauth"></a>

The Amazon Cognito user pools API, both a resource-management interface and a user-facing authentication and authorization interface, combines the authorization models that follow in its operations. Depending on the API operation, you might have to provide authorization with IAM credentials, an access token, a session token, a client secret, or a combination of these. For many user authentication and authorization operations, you have a choice of authenticated and unauthenticated versions of the request. Unauthenticated operations are best security practice for apps that you distribute to your users, like mobile apps; you don't need to include any secrets in your code.

You can only assign permissions in IAM policies for [IAM-authorized management operations](#user-pool-apis-auth-unauth-sigv4-management) and [IAM-authorized user operations](#user-pool-apis-auth-unauth-sigv4-user).

### IAM-authorized management operations
<a name="user-pool-apis-auth-unauth-sigv4-management"></a>

IAM-authorized management operations modify and view your user pool and app client configuration, like you would do in the AWS Management Console. 

For example, to modify your user pool in an [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request, you must present AWS credentials and IAM permissions to update the resource.

To authorize these requests in the AWS Command Line Interface (AWS CLI) or an AWS SDK, configure your environment with environment variables or client configuration that adds IAM credentials to your request. For more information, see [Accessing AWS using your AWS credentials](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys) in the *AWS General Reference*. You can also send requests directly to the [service endpoints](https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html) for the Amazon Cognito user pools API. You must authorize, or *sign*, these requests with AWS credentials that you embed in the header of your request. For more information, see [Signing AWS API requests](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html).


| IAM-authorized management operations | 
| --- |
| [AddCustomAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AddCustomAttributes.html) | 
| [CreateGroup](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateGroup.html) | 
| [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html) | 
| [CreateResourceServer](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateResourceServer.html) | 
| [CreateUserImportJob](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserImportJob.html) | 
| [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) | 
| [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) | 
| [CreateUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolDomain.html) | 
| [DeleteGroup](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteGroup.html) | 
| [DeleteIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteIdentityProvider.html) | 
| [DeleteResourceServer](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteResourceServer.html) | 
| [DeleteUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPool.html) | 
| [DeleteUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPoolClient.html) | 
| [DeleteUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPoolDomain.html) | 
| [DescribeIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeIdentityProvider.html) | 
| [DescribeResourceServer](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeResourceServer.html) | 
| [DescribeRiskConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeRiskConfiguration.html) | 
| [DescribeUserImportJob](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserImportJob.html) | 
| [DescribeUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPool.html) | 
| [DescribeUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolClient.html) | 
| [DescribeUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolDomain.html) | 
| [GetCSVHeader](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetCSVHeader.html) | 
| [GetGroup](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetGroup.html) | 
| [GetIdentityProviderByIdentifier](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetIdentityProviderByIdentifier.html) | 
| [GetSigningCertificate](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetSigningCertificate.html) | 
| [GetUICustomization](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUICustomization.html) | 
| [GetUserPoolMfaConfig](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserPoolMfaConfig.html) | 
| [ListGroups](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListGroups.html) | 
| [ListIdentityProviders](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListIdentityProviders.html) | 
| [ListResourceServers](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListResourceServers.html) | 
| [ListTagsForResource](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListTagsForResource.html) | 
| [ListUserImportJobs](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUserImportJobs.html) | 
| [ListUserPoolClients](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUserPoolClients.html) | 
| [ListUserPools](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUserPools.html) | 
| [ListUsers](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html) | 
| [ListUsersInGroup](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsersInGroup.html) | 
| [SetRiskConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetRiskConfiguration.html) | 
| [SetUICustomization](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUICustomization.html) | 
| [SetUserPoolMfaConfig](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserPoolMfaConfig.html) | 
| [StartUserImportJob](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StartUserImportJob.html) | 
| [StopUserImportJob](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StopUserImportJob.html) | 
| [TagResource](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_TagResource.html) | 
| [UntagResource](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UntagResource.html) | 
| [UpdateGroup](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateGroup.html) | 
| [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html) | 
| [UpdateResourceServer](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateResourceServer.html) | 
| [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) | 
| [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) | 
| [UpdateUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolDomain.html) | 

### IAM-authorized user operations
<a name="user-pool-apis-auth-unauth-sigv4-user"></a>

IAM-authorized user operations sign up, sign in, manage credentials for, modify, and view your users. 

For example, you can have a server-side application tier that backs a web front end. Your server-side app is an OAuth confidential client that you trust with privileged access to your Amazon Cognito resources. To register a user in the app, your server can include AWS credentials in an [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) API request. For more information about OAuth client types, see [Client Types](https://www.rfc-editor.org/rfc/rfc6749#section-2.1) in *The OAuth 2.0 Authorization Framework*.

To authorize these requests in the AWS CLI or an AWS SDK, configure your server-side app environment with environment variables or client configuration that adds IAM credentials to your request. For more information, see [Accessing AWS using your AWS credentials](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys) in the *AWS General Reference*. You can also send requests directly to the [service endpoints](https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html) for the Amazon Cognito user pools API. You must authorize, or *sign*, these requests with AWS credentials that you embed in the header of your request. For more information, see [Signing AWS API requests](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html).

If your app client has a client secret, you must provide both your IAM credentials and, depending on the operation, either the `SecretHash` parameter or the `SECRET_HASH` value in `AuthParameters`. For more information, see [Computing secret hash values](signing-up-users-in-your-app.md#cognito-user-pools-computing-secret-hash).


| IAM-authorized user operations | 
| --- |
| [AdminAddUserToGroup](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminAddUserToGroup.html) | 
| [AdminConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminConfirmSignUp.html) | 
| [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) | 
| [AdminDeleteUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDeleteUser.html) | 
| [AdminDeleteUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDeleteUserAttributes.html) | 
| [AdminDisableProviderForUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDisableProviderForUser.html) | 
| [AdminDisableUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDisableUser.html) | 
| [AdminEnableUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminEnableUser.html) | 
| [AdminForgetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminForgetDevice.html) | 
| [AdminGetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetDevice.html) | 
| [AdminGetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetUser.html) | 
| [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) | 
| [AdminLinkProviderForUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminLinkProviderForUser.html) | 
| [AdminListDevices](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListDevices.html) | 
| [AdminListGroupsForUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListGroupsForUser.html) | 
| [AdminListUserAuthEvents](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListUserAuthEvents.html) | 
| [AdminRemoveUserFromGroup](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRemoveUserFromGroup.html) | 
| [AdminResetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html) | 
| [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) | 
| [AdminSetUserMFAPreference](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserMFAPreference.html) | 
| [AdminSetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html) | 
| [AdminSetUserSettings](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserSettings.html) | 
| [AdminUpdateAuthEventFeedback](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateAuthEventFeedback.html) | 
| [AdminUpdateDeviceStatus](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateDeviceStatus.html) | 
| [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) | 
| [AdminUserGlobalSignOut](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUserGlobalSignOut.html) | 

### Unauthenticated user operations
<a name="user-pool-apis-auth-unauth-unauth"></a>

Unauthenticated user operations sign up, sign in, and initiate password resets for your users. Use unauthenticated, or *public*, API operations when you want anyone on the internet to sign up and sign in to your app.

For example, to register a user in your app, you can distribute an OAuth public client that doesn't provide any privileged access to secrets. You can register this user with the unauthenticated API operation [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html).

To send these requests in a public client that you developed with an AWS SDK, you don't need to configure any credentials. You can also send requests directly to the [service endpoints](https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html) for the Amazon Cognito user pools API with no additional authorization.

If your app client has a client secret, you must provide, depending on the operation, either the `SecretHash` parameter or the `SECRET_HASH` value in `AuthParameters`. For more information, see [Computing secret hash values](signing-up-users-in-your-app.md#cognito-user-pools-computing-secret-hash).


| Unauthenticated user operations | 
| --- |
| [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) | 
| [ConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html) | 
| [ResendConfirmationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html) | 
| [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html) | 
| [ConfirmForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html) | 
| [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) | 

### Token-authorized user operations
<a name="user-pool-apis-auth-unauth-token-auth"></a>

Token-authorized user operations sign out, manage credentials for, modify, and view your users after they have signed in or begun the sign-in process. Use token-authorized API operations when you don't want to distribute secrets in your app, and you want to authorize requests with your user's own credentials. If your user has completed sign-in, you must authorize their token-authorized API request with an access token. If your user is in the middle of a sign-in process, you must authorize their token-authorized API request with a session token that Amazon Cognito returned in the response to the previous request.

For example, in a public client, you might want to update a user's profile in a way that restricts the write access to the user's own profile only. To make this update, your client can include the user's access token in a [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html) API request.

To send these requests in a public client that you developed with an AWS SDK, you don't need to configure any credentials. Include an `AccessToken` or `Session` parameter in your request. You can also send requests directly to the [service endpoints](https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html) for the Amazon Cognito user pools API. To authorize a request to a service endpoint, include the access or session token in the POST body of your request.

To sign an API request for a token-authorized operation, include the access token as an `Authorization` header in your request, in the format `Bearer <Base64-encoded access token>`.


| Token-authorized user operations | AccessToken | Session | 
| --- |--- |--- |
| [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) |  | ✓ | 
| [ChangePassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ChangePassword.html) | ✓ |  | 
| [GetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html) | ✓ |  | 
| [StartWebAuthnRegistration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StartWebAuthnRegistration.html) | ✓ |  | 
| [CompleteWebAuthnRegistration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CompleteWebAuthnRegistration.html) | ✓ |  | 
| [DeleteWebAuthnCredential](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteWebAuthnCredential.html) | ✓ |  | 
| [ListWebAuthnCredentials](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListWebAuthnCredentials.html) | ✓ |  | 
| [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html) | ✓ |  | 
| [DeleteUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserAttributes.html) | ✓ |  | 
| [DeleteUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUser.html) | ✓ |  | 
| [ConfirmDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmDevice.html) | ✓ |  | 
| [ForgetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgetDevice.html) | ✓ |  | 
| [GetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetDevice.html) | ✓ |  | 
| [ListDevices](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html) | ✓ |  | 
| [UpdateDeviceStatus](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateDeviceStatus.html) | ✓ |  | 
| [GetUserAttributeVerificationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html) | ✓ |  | 
| [VerifyUserAttribute](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html) | ✓ |  | 
| [SetUserSettings](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserSettings.html) | ✓ |  | 
| [SetUserMFAPreference](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserMFAPreference.html) | ✓ |  | 
| [GlobalSignOut](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GlobalSignOut.html) | ✓ |  | 
| [UpdateAuthEventFeedback](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateAuthEventFeedback.html) |  | ✓ | 
| [AssociateSoftwareToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AssociateSoftwareToken.html) | ✓ | ✓ | 
| [VerifySoftwareToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifySoftwareToken.html) | ✓ | ✓ | 
| [RevokeToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RevokeToken.html)¹ |  |  | 
| [GetTokensFromRefreshToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetTokensFromRefreshToken.html)¹ |  |  | 

¹ `RevokeToken` and `GetTokensFromRefreshToken` take refresh tokens as the authorization parameter. The refresh token serves as the authorizing token, and as the target resource.

# User pool sign-in with third party identity providers
<a name="cognito-user-pools-identity-federation"></a>

Your app users can either sign in directly through a user pool, or they can federate through a third-party identity provider (IdP). The user pool manages the overhead of handling the tokens that are returned from social sign-in through Facebook, Google, Amazon, and Apple, and from OpenID Connect (OIDC) and SAML IdPs. With the built-in hosted web UI, Amazon Cognito provides token handling and management for authenticated users from all IdPs. This way, your backend systems can standardize on one set of user pool tokens.

## How federated sign-in works in Amazon Cognito user pools
<a name="cognito-user-pools-identity-federation-how-it-works"></a>

Sign-in through a third party (federation) is available in Amazon Cognito user pools. This feature is independent of federation through Amazon Cognito identity pools (federated identities).

![\[Authentication overview with social sign-in\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-cup.png)


Amazon Cognito is a user directory and an OAuth 2.0 identity provider (IdP). When you sign in *local users* to the Amazon Cognito directory, your user pool is an IdP to your app. A local user exists exclusively in your user pool directory without federation through an external IdP.

When you connect Amazon Cognito to social, SAML, or OpenID Connect (OIDC) IdPs, your user pool acts as a bridge between multiple service providers and your app. To your IdP, Amazon Cognito is a service provider (SP). Your IdPs pass an OIDC ID token or a SAML assertion to Amazon Cognito. Amazon Cognito reads the claims about your user in the token or assertion and maps those claims to a new user profile in your user pool directory.

Amazon Cognito then creates a user profile for your federated user in its own directory. Amazon Cognito adds attributes to your user based on the claims from your IdP and, in the case of OIDC and social identity providers, an IdP-operated public `userinfo` endpoint. Your user's attributes change in your user pool when a mapped IdP attribute changes. You can also add more attributes independent of those from the IdP.

After Amazon Cognito creates a profile for your federated user, it changes its function and presents itself as the IdP to your app, which is now the SP. Amazon Cognito is a combination OIDC and OAuth 2.0 IdP. It generates access tokens, ID tokens, and refresh tokens. For more information about tokens, see [Understanding user pool JSON web tokens (JWTs)](amazon-cognito-user-pools-using-tokens-with-identity-providers.md).

You must design an app that integrates with Amazon Cognito to authenticate and authorize your users, whether federated or local.

## The responsibilities of an app as a service provider with Amazon Cognito
<a name="cognito-user-pools-identity-federation-how-it-works-app-responsibilities"></a><a name="cognito-user-pools-identity-federation-how-it-works-app-responsibilities"></a>

**Verify and process the information in the tokens**  
In most scenarios, Amazon Cognito redirects your authenticated user to an app URL that it appends with an authorization code. Your app [exchanges the code](https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html) for access, ID, and refresh tokens. Then, it must [check the validity of the tokens](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html) and serve information to your user based on the claims in the tokens.

**Respond to authentication events with Amazon Cognito API requests**  
Your app must integrate with the [Amazon Cognito user pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html) and the [ authentication API endpoints](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html). The authentication API signs your user in and out, and manages tokens. The user pools API has a variety of operations that manage your user pool, your users, and the security of your authentication environment. Your app must know what to do next when it receives a response from Amazon Cognito.

## Things to know about Amazon Cognito user pools third-party sign-in
<a name="cognito-user-pools-identity-federation-how-it-works-considerations"></a><a name="cognito-user-pools-identity-federation-how-it-works-considerations"></a>
+ If you want your users to sign in with federated providers, you must choose a domain. This sets up the pages for [managed login](cognito-userpools-server-contract-reference.md). For more information, see [Using your own domain for managed login](cognito-user-pools-add-custom-domain.md).
+ You can't sign in federated users with API operations like [ InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html). Federated users can only sign in with the [Login endpoint](login-endpoint.md) or the [Authorize endpoint](authorization-endpoint.md).
+ The [Authorize endpoint](authorization-endpoint.md) is a *redirection* endpoint. If you provide an `idp_identifier` or `identity_provider` parameter in your request, it redirects silently to your IdP, bypassing managed login. Otherwise, it redirects to the managed login [Login endpoint](login-endpoint.md).
+ When managed login redirects a session to a federated IdP, Amazon Cognito includes the `user-agent` header `Amazon/Cognito` in the request.
+ Amazon Cognito derives the `username` attribute for a federated user profile from a combination of a fixed identifier and the name of your IdP. To generate a user name that matches your custom requirements, create a mapping to the `preferred_username` attribute. For more information, see [Things to know about mappings](cognito-user-pools-specifying-attribute-mapping.md#cognito-user-pools-specifying-attribute-mapping-requirements).

  Example: `MyIDP_bob@example.com`
+ Amazon Cognito creates a [user group](cognito-user-pools-user-groups.md) for each OIDC, SAMl, and social IdP that you add to your user pool. The name of the group is in the format `[user pool ID]_[IdP name]`, for example `us-east-1_EXAMPLE_MYSSO` or `us-east-1_EXAMPLE_Google`. Each unique automatically-generated IdP user profile is automatically added to this group. [Linked users](cognito-user-pools-identity-federation-consolidate-users.md) aren't automatically added to this group, but you can add their profiles to the group in a separate process.
+ Amazon Cognito records information about your federated user's identity to an attribute, and a claim in the ID token, called `identities`. This claim contains your user's provider and their unique ID from the provider. You can't change the `identities` attribute in a user profile directly. For more information about how to link a federated user, see [Linking federated users to an existing user profile](cognito-user-pools-identity-federation-consolidate-users.md).
+ When you update your IdP in an [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html) API request, your changes can take up to a minute to appear in managed login.
+ Amazon Cognito supports up to 20 HTTP redirects between itself and your IdP.
+ When your user signs in with managed login, their browser stores an encrypted login-session cookie which records the client and provider they signed in with. If they attempt to sign in again with the same parameters, managed login reuses any *unexpired* existing session, and the user authenticates without providing credentials again. If your user signs in again with a different IdP, including a switch to or from local user pool sign-in, they must provide credentials and generate a new login session.

  You can assign any of your user pool IdPs to any app client, and users can only sign in with an IdP that you assigned to their app client.

**Topics**
+ [

## How federated sign-in works in Amazon Cognito user pools
](#cognito-user-pools-identity-federation-how-it-works)
+ [

## The responsibilities of an app as a service provider with Amazon Cognito
](#cognito-user-pools-identity-federation-how-it-works-app-responsibilities)
+ [

## Things to know about Amazon Cognito user pools third-party sign-in
](#cognito-user-pools-identity-federation-how-it-works-considerations)
+ [

# Configuring identity providers for your user pool
](cognito-user-pools-identity-provider.md)
+ [

# Using social identity providers with a user pool
](cognito-user-pools-social-idp.md)
+ [

# Using SAML identity providers with a user pool
](cognito-user-pools-saml-idp.md)
+ [

# Using OIDC identity providers with a user pool
](cognito-user-pools-oidc-idp.md)
+ [

# Mapping IdP attributes to profiles and tokens
](cognito-user-pools-specifying-attribute-mapping.md)
+ [

# Linking federated users to an existing user profile
](cognito-user-pools-identity-federation-consolidate-users.md)

# Configuring identity providers for your user pool
<a name="cognito-user-pools-identity-provider"></a>

With user pools, you can implement sign-in through a variety of external identity providers (IdPs). This section of the guide has instructions for setting up these identity providers with your user pool in the Amazon Cognito console. Alternatively, you can use the user pools API and an AWS SDK to programmatically add user pool identity providers. For more information, see [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html).

The supported identity provider options include social providers like Facebook, Google, and Amazon, as well as OpenID Connect (OIDC) and SAML 2.0 providers. Before you get started, set yourself up with administrative credentials for your IdP. For each type of provider, you'll need to register your application, obtain the necessary credentials, and then configure the provider details in your user pool. Your users can then sign up and sign in to your application with their existing accounts from the connected identity providers.

The **Social and external providers** menu under **Authentication** adds and updates user pool IdPs. For more information, see [User pool sign-in with third party identity providers](cognito-user-pools-identity-federation.md).

**Topics**
+ [

## Set up user sign-in with a social IdP
](#cognito-user-pools-facebook-provider)
+ [

## Set up user sign-in with an OIDC IdP
](#cognito-user-pools-oidc-providers)
+ [

## Set up user sign-in with a SAML IdP
](#cognito-user-pools-saml-providers)

## Set up user sign-in with a social IdP
<a name="cognito-user-pools-facebook-provider"></a>

You can use federation to integrate Amazon Cognito user pools with social identity providers such as Facebook, Google, and Login with Amazon.

To add a social identity provider, you first create a developer account with the identity provider. After you have your developer account, register your app with the identity provider. The identity provider creates an app ID and an app secret for your app, and you configure those values in your Amazon Cognito user pools.
+ [Google identity platform](https://developers.google.com/identity/)
+ [Facebook for developers](https://developers.facebook.com/docs/facebook-login)
+ [Login with Amazon](https://developer.amazon.com/login-with-amazon)
+ [Sign in with Apple](https://developer.apple.com/sign-in-with-apple/)

**To integrate user sign-in with a social IdP**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. In the navigation pane, choose **User Pools**, and choose the user pool you want to edit.

1. Choose the **Social and external providers** menu.

1. Choose **Add an identity provider**, or choose the **Facebook**, **Google**, **Amazon**, or **Apple** identity provider you have configured, locate **Identity provider information**, and choose **Edit**. For more information about adding a social identity provider, see [Using social identity providers with a user pool](cognito-user-pools-social-idp.md).

1. Enter your social identity provider's information by completing one of the following steps, based on your choice of IdP:  
**Facebook, Google, and Login with Amazon**  
Enter the app ID and app secret that you received when you created your client app.  
**Sign In with Apple**  
Enter the service ID that you provided to Apple, and the team ID, key ID, and private key you received when you created your app client.

1. For **Authorized scopes**, enter the names of the social identity provider scopes that you want to map to user pool attributes. Scopes define which user attributes, such as name and email, that you want to access with your app. When entering scopes, use the following guidelines based on your choice of IdP:
   + **Facebook** — Separate scopes with commas. For example:

     `public_profile, email`
   + **Google, Login with Amazon, and Sign In with Apple** — Separate scopes with spaces. For example:
     + **Google:** `profile email openid`
     + **Login with Amazon:** `profile postal_code`
     + **Sign In with Apple:** `name email`
**Note**  
For Sign In with Apple (console), use the check boxes to choose scopes.

1. Choose **Save changes**.

1. From the **App clients** menu, choose an app client from the list and then select **Edit**. Add the new social identity provider to the app client under **Identity providers**.

1. Choose **Save changes**.

For more information on social IdPs, see [Using social identity providers with a user pool](cognito-user-pools-social-idp.md).

## Set up user sign-in with an OIDC IdP
<a name="cognito-user-pools-oidc-providers"></a>

You can integrate user sign-in with an OpenID Connect (OIDC) identity provider (IdP) such as Salesforce or Ping Identity.

**To add an OIDC provider to a user pool**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools** from the navigation menu.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Social and external providers** menu and select **Add an identity provider**.

1. Choose an **OpenID Connect** identity provider.

1. Enter a unique name into **Provider name**.

1. Enter the client ID that you received from your provider into **Client ID**.

1. Enter the client secret that you received from your provider into **Client secret**.

1. Enter **Authorized scopes** for this provider. Scopes define which groups of user attributes (such as `name` and `email`) that your application will request from your provider. Scopes must be separated by spaces, following the [OAuth 2.0](https://tools.ietf.org/html/rfc6749#section-3.3) specification.

   Your user must consent to provide these attributes to your application.

1. Choose an **Attribute request method** to provide Amazon Cognito with the HTTP method (either GET or POST) that Amazon Cognito uses to fetch the details of the user from the **userInfo** endpoint operated by your provider.

1. Choose a **Setup method** to retrieve OpenID Connect endpoints either by **Auto fill through issuer URL** or **Manual input**. Use **Auto fill through issuer URL** when your provider has a public `.well-known/openid-configuration` endpoint where Amazon Cognito can retrieve the URLs of the `authorization`, `token`, `userInfo`, and `jwks_uri` endpoints.

1. Enter the issuer URL or `authorization`, `token`, `userInfo`, and `jwks_uri` endpoint URLs from your IdP.
**Note**  
You can use only port numbers 443 and 80 with discovery, auto-filled, and manually entered URLs. User logins fail if your OIDC provider uses any nonstandard TCP ports.  
The issuer URL must start with `https://`, and must not end with a `/` character. For example, Salesforce uses this URL:  
`https://login.salesforce.com`   
The `openid-configuration` document associated with your issuer URL must provide HTTPS URLs for the following values: `authorization_endpoint`, `token_endpoint`, `userinfo_endpoint`, and `jwks_uri`. Similarly, when you choose **Manual input**, you can only enter HTTPS URLs.

1. The OIDC claim **sub** is mapped to the user pool attribute **Username** by default. You can map other OIDC [claims](https://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims) to user pool attributes. Enter the OIDC claim, and select the corresponding user pool attribute from the drop-down list. For example, the claim **email** is often mapped to the user pool attribute **Email**.

1. Map additional attributes from your identity provider to your user pool. For more information, see [Specifying Identity Provider attribute mappings for your user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html).

1. Choose **Create**.

1. From the **App clients** menu, select an app client from the list. To add the new SAML identity provider to the app client, navigate to the **Login pages** tab and select **Edit** on **Managed login pages configuration**.

1. Choose **Save changes**.

For more information on OIDC IdPs, see [Using OIDC identity providers with a user pool](cognito-user-pools-oidc-idp.md).

## Set up user sign-in with a SAML IdP
<a name="cognito-user-pools-saml-providers"></a>

You can use federation for Amazon Cognito user pools to integrate with a SAML identity provider (IdP). You supply a metadata document, either by uploading the file or by entering a metadata document endpoint URL. For information about obtaining metadata documents for third-party SAML IdPs, see [Configuring your third-party SAML identity provider](cognito-user-pools-integrating-3rd-party-saml-providers.md).

**To configure a SAML 2.0 identity provider in your user pool**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Social and external provider** menu and select **Add an identity provider**.

1. Choose a **SAML** identity provider.

1. Enter **Identifiers** separated by commas. An identifier directs Amazon Cognito to check the user sign-in email address, and then direct the user to the provider that corresponds to their domain.

1. Choose **Add sign-out flow** if you want Amazon Cognito to send signed sign-out requests to your provider when a user logs out. Configure your SAML 2.0 identity provider to send sign-out responses to the `https://mydomain.auth.us-east-1.amazoncognito.com/saml2/logout` endpoint that Amazon Cognito creates when you configure managed login. The `saml2/logout` endpoint uses POST binding.
**Note**  
If you select this option and your SAML identity provider expects a signed logout request, you also must configure the signing certificate provided by Amazon Cognito with your SAML IdP.   
The SAML IdP will process the signed logout request and logout your user from the Amazon Cognito session.

1. Choose a **Metadata document source**. If your identity provider offers SAML metadata at a public URL, you can choose **Metadata document URL** and enter that public URL. Otherwise, choose **Upload metadata document** and select a metadata file you downloaded from your provider earlier.
**Note**  
If your provider has a public endpoint, we recommend that you enter a metadata document URL, rather than uploading a file. If you use the URL, Amazon Cognito refreshes metadata automatically. Typically, metadata refresh happens every 6 hours or before the metadata expires, whichever is earlier.

1. **Map attributes between your SAML provider and your app** to map SAML provider attributes to the user profile in your user pool. Include your user pool required attributes in your attribute map. 

   For example, when you choose **User pool attribute** `email`, enter the SAML attribute name as it appears in the SAML assertion from your identity provider. Your identity provider might offer sample SAML assertions for reference. Some identity providers use simple names, such as `email`, while others use URL-formatted attribute names similar to:

   ```
   http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
   ```

1. Choose **Create**.

**Note**  
If you see `InvalidParameterException` while creating a SAML IdP with an HTTPS metadata endpoint URL, make sure that the metadata endpoint has SSL correctly set up and that there is a valid SSL certificate associated with it. One example of such an exception would be "Error retrieving metadata from *<metadata endpoint>*".

**To set up the SAML IdP to add a signing certificate**
+ To get the certificate containing the public key that the IdP uses to verify the signed logout request, do the following:

  1. Go to the **Social and external providers** menu of your user pool.

  1. Select your SAML provider,

  1. Choose **View signing certificate.**

For more information on SAML IdPs see [Using SAML identity providers with a user pool](cognito-user-pools-saml-idp.md).

# Using social identity providers with a user pool
<a name="cognito-user-pools-social-idp"></a>

Your web and mobile app users can sign in through social identity providers (IdP) like Facebook, Google, Amazon, and Apple. With the built-in hosted web UI, Amazon Cognito provides token handling and management for all authenticated users. This way, your backend systems can standardize on one set of user pool tokens. You must enable managed login to integrate with supported social identity providers. When Amazon Cognito builds your managed login pages, it creates OAuth 2.0 endpoints that Amazon Cognito and your OIDC and social IdPs use to exchange information. For more information, see the [Amazon Cognito user pools Auth API reference](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html).

You can add a social IdP in the AWS Management Console, or you can use the AWS CLI or Amazon Cognito API. 

**Note**  
Sign-in through a third party (federation) is available in Amazon Cognito user pools. This feature is independent of federation through Amazon Cognito identity pools (federated identities).

**Topics**
+ [

## Set up a social IdP developer account and application
](#cognito-user-pools-social-idp-step-1)
+ [

## Configure your user pool with a social IdP
](#cognito-user-pools-social-idp-step-2)
+ [

## Test your social IdP configuration
](#cognito-user-pools-social-idp-step-3)

## Set up a social IdP developer account and application
<a name="cognito-user-pools-social-idp-step-1"></a>

Before you create a social IdP with Amazon Cognito, you must register your application with the social IdP to receive a client ID and client secret.

------
#### [ Facebook ]

For the latest information about configuration of Meta developer accounts and authentication, see [Meta App Development](https://developers.facebook.com/docs/development).

**How to register an application with Facebook/Meta**

1. Create a [developer account with Facebook](https://developers.facebook.com/docs/facebook-login).

1. [Sign in](https://developers.facebook.com/) with your Facebook credentials.

1. From the **My Apps** menu, choose **Create New App**.

1. Enter a name for your Facebook app, and then choose **Create App ID**.

1. On the left navigation bar, choose **Settings**, and then **Basic**.

1. Note the **App ID** and the **App Secret**. You will use them in the next section.

1. Choose **\$1 Add Platform** from the bottom of the page.

1. Choose **Website**.

1. Under **Website**, enter the path to the sign-in page for your app into **Site URL**.

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com
   ```

1. Choose **Save changes**.

1. Enter the path to the root of your user pool domain into **App Domains**.

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com
   ```

1. Choose **Save changes**.

1. From the navigation bar choose **Add Product** and choose **Set up** for the **Facebook Login** product.

1. From the navigation bar choose **Facebook Login** and then **Settings**.

   Enter the path to the `/oauth2/idpresponse` endpoint for your user pool domain into **Valid OAuth Redirect URIs**.

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/idpresponse
   ```

1. Choose **Save changes**.

------
#### [ Login with Amazon ]

For the latest information about configuration of Login with Amazon developer accounts and authentication, see [Login with Amazon Documentation](https://developer.amazon.com/docs/login-with-amazon/documentation-overview.html).

**How to register an application with Login with Amazon**

1. Create a [developer account with Amazon](https://developer.amazon.com/login-with-amazon).

1. [Sign in](https://developer.amazon.com/lwa/sp/overview.html) with your Amazon credentials.

1. You need to create an Amazon security profile to receive the Amazon client ID and client secret.

   Choose **Apps and Services** from navigation bar at the top of the page and then choose **Login with Amazon**.

1. Choose **Create a Security Profile**.

1. Enter a **Security Profile Name**, a **Security Profile Description**, and a **Consent Privacy Notice URL**.

1. Choose **Save**.

1. Choose **Client ID** and **Client Secret** to show the client ID and secret. You will use them in the next section.

1. Hover over the gear icon and choose **Web Settings**, and then choose **Edit**.

1. Enter your user pool domain into **Allowed Origins**.

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com
   ```

1. Enter your user pool domain with the `/oauth2/idpresponse` endpoint into **Allowed Return URLs**.

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/idpresponse
   ```

1. Choose **Save**.

------
#### [ Google ]

For more information about OAuth 2.0 in the Google Cloud platform, see [Learn about authentication & authorization](https://developers.google.com/workspace/guides/auth-overview) in the Google Workspace for Developers documentation.

**How to register an application with Google**

1. Create a [developer account with Google](https://developers.google.com/identity).

1. Sign in to the [Google Cloud Platform console](https://console.cloud.google.com/home/dashboard).

1. From the top navigation bar, choose **Select a project**. If you already have a project in the Google platform, this menu displays your default project instead.

1. Select **NEW PROJECT**.

1. Enter a name for your product and then choose **CREATE**.

1. On the left navigation bar, choose **APIs and Services**, then **Oauth consent screen**.

1. Enter App information, an **App domain**, **Authorized domains**, and **Developer contact information**. Your **Authorized domains** must include `amazoncognito.com` and the root of your custom domain, for example `example.com`. Choose **SAVE AND CONTINUE**.

1. 1. Under **Scopes**, choose **Add or remove scopes**, and choose, at minimum, the following OAuth scopes.

   1. `.../auth/userinfo.email`

   1. `.../auth/userinfo.profile`

   1. openid

1. Under **Test users**, choose **Add users**. Enter your email address and any other authorized test users, then choose **SAVE AND CONTINUE**.

1. Expand the left navigation bar again, and choose **APIs and Services**, then **Credentials**. 

1. Choose **CREATE CREDENTIALS**, then **OAuth client ID**.

1. Choose an **Application type** and give your client a **Name**.

1. Under **Authorized JavaScript origins**, choose **ADD URI**. Enter your user pool domain.

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com
   ```

1. Under **Authorized redirect URIs**, choose **ADD URI**. Enter the path to the `/oauth2/idpresponse` endpoint of your user pool domain.

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/idpresponse
   ```

1. Choose **CREATE**.

1. Securely store the values the Google displays under **Your client ID** and **Your client secret**. Provide these values to Amazon Cognito when you add a Google IdP.

------
#### [ Sign in with Apple ]

For the most up-to-date information about setting up Sign in with Apple, see [Configuring Your Environment for Sign in with Apple](https://developer.apple.com/documentation/signinwithapple/configuring-your-environment-for-sign-in-with-apple) in the Apple Developer documentation.

**How to register an application with Sign in with Apple (SIWA)**

1. Create a [developer account with Apple](https://developer.apple.com/programs/enroll/).

1. [Sign in](https://developer.apple.com/account/#/welcome) with your Apple credentials.

1. On the left navigation bar, choose **Certificates, Identifiers & Profiles**.

1. On the left navigation bar, choose **Identifiers**.

1. On the **Identifiers** page, choose the **\$1** icon.

1. On the **Register a New Identifier** page, choose **App IDs**, and then choose **Continue**.

1. On the **Select a type** page, choose **App**, then choose **Continue**.

1. On the **Register an App ID** page, do the following:

   1. Under **Description**, enter a description.

   1. Under **App ID Prefix**, enter a **Bundle ID**. Make a note of the value under **App ID Prefix**. You will use this value after you choose Apple as your identity provider in [Configure your user pool with a social IdP](#cognito-user-pools-social-idp-step-2).

   1. Under **Capabilities**, choose **Sign In with Apple**, and then choose **Edit**.

   1. On the **Sign in with Apple: App ID Configuration** page, choose to set up the app as either primary or grouped with other App IDs, and then choose **Save**.

   1. Choose **Continue**.

1. On the **Confirm your App ID** page, choose **Register**.

1. On the **Identifiers** page, choose the **\$1** icon.

1. On the **Register a New Identifier** page, choose **Services IDs**, and then choose **Continue**.

1. On the **Register a Services ID** page, do the following:

   1. Under **Description**, type a description.

   1. Under **Identifier**, type an identifier. Make a note of this Services ID as you will need this value after you choose Apple as your identity provider in [Configure your user pool with a social IdP](#cognito-user-pools-social-idp-step-2).

   1. Choose **Continue**, then **Register**.

1. Choose the Services ID you just create from the Identifiers page.

   1. Select **Sign In with Apple**, and then choose **Configure**.

   1. On the **Web Authentication Configuration** page, select the app ID that you created earlier as the **Primary App ID**. 

   1. Choose the **\$1** icon next to **Website URLs**. 

   1. Under **Domains and subdomains**, enter your user pool domain without an `https://` prefix.

      ```
      mydomain.auth.us-east-1.amazoncognito.com
      ```

   1. Under **Return URLs**, enter the path to the `/oauth2/idpresponse` endpoint of your user pool domain.

      ```
      https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/idpresponse
      ```

   1. Choose **Next**, and then **Done**. You don't need to verify the domain.

   1. Choose **Continue**, and then choose **Save**.

1. On the left navigation bar, choose **Keys**.

1. On the **Keys** page, choose the **\$1** icon.

1. On the **Register a New Key** page, do the following:

   1. Under **Key Name**, enter a key name. 

   1. Choose **Sign In with Apple**, and then choose **Configure**.

   1. On the **Configure Key** page and select the app ID that you created earlier as the **Primary App ID**. Choose **Save**.

   1. Choose **Continue**, and then choose **Register**.

1. On the **Download Your Key** page, choose **Download** to download the private key and note the **Key ID** shown, and then choose **Done**. You will need this private key and the **Key ID** value shown on this page after you choose Apple as your identity provider in [Configure your user pool with a social IdP](#cognito-user-pools-social-idp-step-2).

------

## Configure your user pool with a social IdP
<a name="cognito-user-pools-social-idp-step-2"></a>

**To configure a user pool social IdP with the AWS Management Console**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list or create a user pool.

1. Choose the **Social and external providers** menu and then select **Add an identity provider**.

1. Choose a social IdP: **Facebook**, **Google**, **Login with Amazon**, or **Sign in with Apple**.

1. Choose from the following steps, based on your choice of social IdP:
   + **Google** and **Login with Amazon** — Enter the **app client ID** and **app client secret** generated in the previous section.
   + **Facebook** — Enter the **app client ID** and **app client secret** generated in the previous section, and then choose an API version (for example, version 2.12). We recommend that you choose the latest possible version, as each Facebook API has a lifecycle and discontinuation date. Facebook scopes and attributes can vary between API versions. We recommend that you test your social identity log in with Facebook to make sure that federation works as you intend.
   + **Sign In with Apple** — Enter the **Services ID**, **Team ID**, **Key ID**, and **private key** generated in the previous section.

1. Enter the names of the **Authorized scopes** you want to use. Scopes define which user attributes (such as `name` and `email`) you want to access with your app. For Facebook, these should be separated by commas. For Google and Login with Amazon, they should be separated by spaces. For Sign in with Apple, select the check boxes for the scopes you want access to.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-social-idp.html)

   Your app user is prompted to consent to providing these attributes to your app. For more information about social provider scopes, see the documentation from Google, Facebook, Login with Amazon, or Sign in with Apple. 

   With Sign in with Apple, the following are user scenarios where scopes might not be returned:
   + An end user encounters failures after leaving Apple’s sign in page (can be from Internal failures within Amazon Cognito or anything written by the developer)
   + The service ID identifier is used across user pools and/or other authentication services
   + A developer adds additional scopes after the end user has signed in before (no new information is retrieved)
   + A developer deletes the user and then the user signs in again without removing the app from their Apple ID profile

1. Map attributes from your IdP to your user pool. For more information, see [Specifying Identity Provider Attribute Mappings for Your User Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html).

1. Choose **Create**.

1. From the **App clients** menu, select an app client from the list. To add the new social identity provider to the app client, navigate to the **Login pages** tab and select **Edit** on **Managed login pages configuration**.

1. Choose **Save changes**.

## Test your social IdP configuration
<a name="cognito-user-pools-social-idp-step-3"></a>

In your application, you must invoke a browser in the user's client so that they can sign in with their social provider. Test sign-in with your social provider after you have completed the setup procedures in the preceding sections. The following example URL loads the sign-in page for your user pool with a prefix domain.

```
https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com
```

This link is the page that Amazon Cognito directs you to when you go to the **App clients** menu, select an app client, navigate to the **Login pages** tab, and select **View login page**. For more information about user pool domains, see [Configuring a user pool domain](cognito-user-pools-assign-domain.md). For more information about app clients, including client IDs and callback URLs, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).

The following example link sets up silent redirect to a social provider from the [Authorize endpoint](authorization-endpoint.md) with an `identity_provider` query parameter. This URL bypasses interactive user pool sign-in with managed login and goes directly to the IdP sign-in page.

```
https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?identity_provider=Facebook|Google|LoginWithAmazon|SignInWithApple&response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com
```

# Using SAML identity providers with a user pool
<a name="cognito-user-pools-saml-idp"></a>

You can choose to have your web and mobile app users sign in through a SAML identity provider (IdP) like [Microsoft Active Directory Federation Services (ADFS)](https://msdn.microsoft.com/en-us/library/bb897402.aspx), or [Shibboleth](http://www.shibboleth.net/). You must choose a SAML IdP which supports the [SAML 2.0 standard](http://saml.xml.org/saml-specifications).

With managed login, Amazon Cognito authenticates local and third-party IdP users and issues JSON web tokens (JWTs). With the tokens that Amazon Cognito issues, you can consolidate multiple identity sources into a universal OpenID Connect (OIDC) standard across all of your apps. Amazon Cognito can process SAML assertions from your third-party providers into that SSO standard. You can create and manage a SAML IdP in the AWS Management Console, through the AWS CLI, or with the Amazon Cognito user pools API. To create your first SAML IdP in the AWS Management Console, see [Adding and managing SAML identity providers in a user pool](cognito-user-pools-managing-saml-idp.md).

![\[Authentication overview with SAML sign-in\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-saml.png)


**Note**  
Federation with sign-in through a third-party IdP is a feature of Amazon Cognito user pools. Amazon Cognito identity pools, sometimes called Amazon Cognito federated identities, are an implementation of federation that you must set up separately in each identity pool. A user pool can be a third-party IdP to an identity pool. For more information, see [Amazon Cognito identity pools](cognito-identity.md).

## Quick reference for IdP configuration
<a name="cognito-user-pools-saml-idp-reference"></a>

You must configure your SAML IdP to accept request and send responses to your user pool. The documentation for your SAML IdP will contain information about how to add your user pool as a relying party or application for your SAML 2.0 IdP. The documentation that follows provides the values that you must provide for the SP entity ID and assertion consumer service (ACS) URL.User pool SAML values quick reference

**SP entity ID**  

```
urn:amazon:cognito:sp:us-east-1_EXAMPLE
```

**ACS URL**  

```
https://Your user pool domain/saml2/idpresponse
```

You must configure your user pool to support your identity provider. The high-level steps to add an external SAML IdP are as follows.

1. Download SAML metadata from your IdP, or retrieve the URL to your metadata endpoint. See [Configuring your third-party SAML identity provider](cognito-user-pools-integrating-3rd-party-saml-providers.md).

1. Add a new IdP to your user pool. Upload the SAML metadata or provide the metadata URL. See [Adding and managing SAML identity providers in a user pool](cognito-user-pools-managing-saml-idp.md).

1. Assign the IdP to your app clients. See [Application-specific settings with app clients](user-pool-settings-client-apps.md).

**Topics**
+ [

## Quick reference for IdP configuration
](#cognito-user-pools-saml-idp-reference)
+ [

# Things to know about SAML IdPs in Amazon Cognito user pools
](cognito-user-pools-saml-idp-things-to-know.md)
+ [

## Case sensitivity of SAML user names
](#saml-nameid-case-sensitivity)
+ [

# Configuring your third-party SAML identity provider
](cognito-user-pools-integrating-3rd-party-saml-providers.md)
+ [

# Adding and managing SAML identity providers in a user pool
](cognito-user-pools-managing-saml-idp.md)
+ [

# SAML session initiation in Amazon Cognito user pools
](cognito-user-pools-SAML-session-initiation.md)
+ [

# Signing out SAML users with single sign-out
](cognito-user-pools-saml-idp-sign-out.md)
+ [

# SAML signing and encryption
](cognito-user-pools-SAML-signing-encryption.md)
+ [

# SAML identity provider names and identifiers
](cognito-user-pools-managing-saml-idp-naming.md)

# Things to know about SAML IdPs in Amazon Cognito user pools
<a name="cognito-user-pools-saml-idp-things-to-know"></a>

Implementation of a SAML 2.0 IdP comes with some requirements and restrictions. Refer to this section when you're implementing your IdP. You'll also find information that's useful for troubleshooting errors during SAML federation with a user pool.

**Amazon Cognito processes SAML assertions for you**  
Amazon Cognito user pools support SAML 2.0 federation with POST-binding endpoints. This eliminates the need for your app to retrieve or parse SAML assertion responses, because the user pool directly receives the SAML response from your IdP through a user agent. Your user pool acts as a service provider (SP) on behalf of your application. Amazon Cognito supports SP-initiated and IdP-initiated single sign-on (SSO) as described in sections 5.1.2 and 5.1.4 of the [SAML V2.0 Technical Overview](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0-cd-02.html).

**Provide a valid IdP signing certificate**  
The signing certificate in your SAML provider metadata must not be expired when you configure the SAML IdP in your user pool.

**User pools support multiple signing certificates**  
When your SAML IdP includes more than one signing certificate in SAML metadata, at sign-in your user pool determines that the SAML assertion is valid if it matches any certificate in the SAML metadata. Each signing certificate must be no longer than 4,096 characters in length.

**Maintain the relay state parameter**  
Amazon Cognito and your SAML IdP maintain session information with a `relayState` parameter.  

1. Amazon Cognito supports `relayState` values greater than 80 bytes. While SAML specifications state that the `relayState` value "must not exceed 80 bytes in length”, current industry practice often deviates from this behavior. As a consequence, rejecting `relayState` values greater than 80 bytes will break many standard SAML provider integrations.

1. The `relayState` token is an opaque reference to state information maintained by Amazon Cognito. Amazon Cognito doesn't guarantee the contents of the `relayState` parameter. Don't parse its contents such that your app depends on the result. For more information, see the [SAML 2.0 specification](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html).

**Identify the ACS endpoint**  
Your SAML identity provider requires that you set an assertion consumer endpoint. Your IdP redirects your users to this endpoint with their SAML assertion. Configure the following endpoint in your user pool domain for SAML 2.0 POST binding in your SAML identity provider.  

```
https://Your user pool domain/saml2/idpresponse
With an Amazon Cognito domain:
https://mydomain.auth.us-east-1.amazoncognito.com/saml2/idpresponse
With a custom domain:
https://auth.example.com/saml2/idpresponse
```
See [Configuring a user pool domain](cognito-user-pools-assign-domain.md) for more information about user pool domains.

**No replayed assertions**  
You can't repeat, or *replay*, a SAML assertion to your Amazon Cognito `saml2/idpresponse` endpoint. A replayed SAML assertion has an assertion ID that duplicates the ID of an earlier IdP response.

**User pool ID is SP entity ID**  
You must provide your IdP with your user pool ID in the service provider (SP) `urn`, also called the *audience URI* or *SP entity ID*. The audience URI for your user pool has the following format.  

```
urn:amazon:cognito:sp:us-east-1_EXAMPLE
```
You can find your user pool ID under **User pool overview** in the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home).

**Map all required attributes**  
Configure your SAML IdP to provide values for any attributes that you set as required in your user pool. For example, `email` is a common required attribute for user pools. Before your users can sign in, your SAML IdP assertions must include a claim that you map to the **User pool attribute** `email`. For more information about attribute mapping, see [Mapping IdP attributes to profiles and tokens](cognito-user-pools-specifying-attribute-mapping.md).

**Assertion format has specific requirements**  
Your SAML IdP must include the following claims in the SAML assertion.  
+ A `NameID` claim. Amazon Cognito associates a SAML assertion with the destination user by `NameID`. If `NameID` changes, Amazon Cognito considers the assertion to be for a new user. The attribute that you set to `NameID` in your IdP configuration must have a persistent value. To assign SAML users to a consistent user profile in your user pool, assign your `NameID` claim from an attribute with a value that doesn't change.

  ```
  <saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:persistent">
    carlos
  </saml2:NameID>
  ```

  A `Format` in your IdP `NameID` claim of `urn:oasis:names:tc:SAML:1.1:nameid-format:persistent` indicates that your IdP is passing an unchanging value. Amazon Cognito doesn't require this format declaration, and assigns a format of `urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified` if your IdP doesn't specify a format of the `NameID` claim. This behavior complies with section 2.2.2 *Complex Type NameIDType*, of [the SAML 2.0 specification](https://groups.oasis-open.org/higherlogic/ws/public/download/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf/latest).
+ An `AudienceRestriction` claim with an `Audience` value that sets your user pool SP entity ID as the target of the response.

  ```
  <saml:AudienceRestriction>
    <saml:Audience> urn:amazon:cognito:sp:us-east-1_EXAMPLE
  </saml:AudienceRestriction>
  ```
+ For SP-initiated single sign-on, a `Response` element with an `InResponseTo` value of the original SAML request ID.

  ```
  <saml2p:Response Destination="https://mydomain.auth.us-east-1.amazoncognito.com/saml2/idpresponse" ID="id123" InResponseTo="_dd0a3436-bc64-4679-a0c2-cb4454f04184" IssueInstant="Date-time stamp" Version="2.0" xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  ```
**Note**  
IdP-initiated SAML assertions must *not* contain an `InResponseTo` value.
+ A `SubjectConfirmationData` element with a `Recipient` value of your user pool `saml2/idpresponse` endpoint and, for SP-initiated SAML, an `InResponseTo` value that matches the original SAML request ID.

  ```
  <saml2:SubjectConfirmationData InResponseTo="_dd0a3436-bc64-4679-a0c2-cb4454f04184" NotOnOrAfter="Date-time stamp" Recipient="https://mydomain.auth.us-east-1.amazoncognito.com/saml2/idpresponse"/>
  ```

**SP-initiated sign-in requests**  
When the [Authorize endpoint](authorization-endpoint.md) redirects your user to your IdP sign-in page, Amazon Cognito includes a *SAML request* in a URL parameter of the `HTTP GET` request. A SAML request contains information about your user pool, including your ACS endpoint. You can optionally apply a cryptographic signature to these requests.

**Sign requests and encrypt responses**  
Every user pool with a SAML provider generates an asymmetric key pair and *signing certificate* for a digital signature that Amazon Cognito assigns to SAML requests. Every external SAML IdP that you configure to support encrypted SAML response causes Amazon Cognito to generate a new key pair and *encryption certificate* for that provider. To view and download the certificates with the public key, choose your IdP in the **Social and external providers** menu in the Amazon Cognito console.  
To establish trust with SAML requests from your user pool, provide your IdP with a copy of your user pool SAML 2.0 signing certificate. Your IdP might ignore SAML requests that your user pool signed if you don’t configure the IdP to accept signed requests.  

1. Amazon Cognito applies a digital signature to SAML requests that your user passes to your IdP. Your user pool signs all single logout (SLO) requests, and you can configure your user pool to sign single sign-on (SSO) requests for any SAML external IdP. When you provide a copy of the certificate, your IdP can verify the integrity of your users' SAML requests. 

1. Your SAML IdP can encrypt SAML responses with the encryption certificate. When you configure an IdP with SAML encryption, your IdP must only send encrypted responses.

**Encode non-alphanumeric characters**  
Amazon Cognito doesn't accept 4-byte UTF-8 characters like 😐 or 𠮷 that your IdP passes as an attribute value. You can encode the character to Base64, pass it as text, and then decode it in your app.  
In the following example, the attribute claim will not be accepted:  

```
<saml2:Attribute Name="Name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
  <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">😐</saml2:AttributeValue>
</saml2:Attribute>
```
In contrast to the preceding example, the following attribute claim will be accepted:  

```
<saml2:Attribute Name="Name" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
  <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">8J+YkA==</saml2:AttributeValue>
</saml2:Attribute>
```

**Metadata endpoint must have valid transport-layer security**  
If you see `InvalidParameterException` while creating a SAML IdP with an HTTPS metadata endpoint URL, for example, "Error retrieving metadata from *<metadata endpoint>*," make sure that the metadata endpoint has SSL correctly set up and that there is a valid SSL certificate associated with it. For more information about validating certificates, see [What Is An SSL/TLS Certificate?](https://aws.amazon.com/what-is/ssl-certificate/).

**Metadata endpoint must be on standard TCP port for HTTP or HTTPS**  
Amazon Cognito only accepts metadata URLs for SAML providers on the standard TCP ports 80 for HTTP and 443 for HTTPS. As a security best practice, host SAML metadata at a TLS-encrypted URL with the `https://` prefix. Enter metadata URLs in the format *`http://www.example.com/saml2/metadata.xml`* or *`https://www.example.com/saml2/metadata.xml`*. The Amazon Cognito console accepts metadata URLs only with the `https://` prefix. You can also configure IdP metadata with [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html) and [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html).

**App clients with IdP-initiated SAML can only sign in with SAML**  
When you activate support for a SAML 2.0 IdP that supports IdP-initiated sign in an app client, you can only add other SAML 2.0 IdPs to that app client. You're prevented from adding the user directory in the user pool *and* all non-SAML external identity providers to an app client configured in this way.

**Logout responses must use POST binding**  
The `/saml2/logout` endpoint accepts `LogoutResponse` as `HTTP POST` requests. User pools don't accept logout responses with `HTTP GET` binding.

**Metadata Signing Certificate Rotation**  
Amazon Cognito caches SAML metadata for up to six hours when you provide metadata with a URL. When performing any metadata signing certificate rotation, configure your metadata source to publish *both* the original and new certificates for at least six hours. When Amazon Cognito refreshes the cache from the metadata URL, it treats each certificate as valid and your SAML IdP can start signing SAML assertions with the new certificate. After this period has elapsed, you can remove the original certificate from the published metadata.

## Case sensitivity of SAML user names
<a name="saml-nameid-case-sensitivity"></a>

When a federated user attempts to sign in, the SAML identity provider (IdP) passes a unique `NameId` to Amazon Cognito in the user's SAML assertion. Amazon Cognito identifies a SAML-federated user by their `NameId` claim. Regardless of the case sensitivity settings of your user pool, Amazon Cognito recognizes a returning federated user from a SAML IdP when they pass their unique and case-sensitive `NameId` claim. If you map an attribute like `email` to `NameId`, and your user changes their email address, they can't sign in to your app.

Map `NameId` in your SAML assertions from an IdP attribute that has values that don't change.

For example, Carlos has a user profile in your case-insensitive user pool from an Active Directory Federation Services (ADFS) SAML assertion that passed a `NameId` value of `Carlos@example.com`. The next time Carlos attempts to sign in, your ADFS IdP passes a `NameId` value of `carlos@example.com`. Because `NameId` must be an exact case match, the sign-in doesn't succeed.

If your users can't log in after their `NameID` changes, delete their user profiles from your user pool. Amazon Cognito will create new user profiles the next time they sign in.

**Topics**
+ [

## Quick reference for IdP configuration
](#cognito-user-pools-saml-idp-reference)
+ [

# Things to know about SAML IdPs in Amazon Cognito user pools
](cognito-user-pools-saml-idp-things-to-know.md)
+ [

## Case sensitivity of SAML user names
](#saml-nameid-case-sensitivity)
+ [

# Configuring your third-party SAML identity provider
](cognito-user-pools-integrating-3rd-party-saml-providers.md)
+ [

# Adding and managing SAML identity providers in a user pool
](cognito-user-pools-managing-saml-idp.md)
+ [

# SAML session initiation in Amazon Cognito user pools
](cognito-user-pools-SAML-session-initiation.md)
+ [

# Signing out SAML users with single sign-out
](cognito-user-pools-saml-idp-sign-out.md)
+ [

# SAML signing and encryption
](cognito-user-pools-SAML-signing-encryption.md)
+ [

# SAML identity provider names and identifiers
](cognito-user-pools-managing-saml-idp-naming.md)

# Configuring your third-party SAML identity provider
<a name="cognito-user-pools-integrating-3rd-party-saml-providers"></a>

When you want to add a SAML identity provider (IdP) to your user pool, you must make some configuration updates in the management interface of your IdP. This section describes how to format the values that you must provide to your IdP. You can also learn about how to retrieve the static or active-URL metadata document that identifies the IdP and its SAML claims to your user pool.

To configure third-party SAML 2.0 identity provider (IdP) solutions to work with federation for Amazon Cognito user pools, you must configure your SAML IdP to redirect to the following Assertion Consumer Service (ACS) URL: `https://mydomain.auth.us-east-1.amazoncognito.com/saml2/idpresponse`. If your user pool has an Amazon Cognito domain, you can find your user pool domain path in the **Domain** menu of your user pool in the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home).

Some SAML IdPs require that you provide the `urn`, also called the audience URI or SP entity ID, in the form `urn:amazon:cognito:sp:us-east-1_EXAMPLE`. You can find your user pool ID under **User pool overview** in the Amazon Cognito console.

You must also configure your SAML IdP to provide values for any attributes that you designated as *required attributes* in your user pool. Typically, `email` is a required attribute for user pools, in which case the SAML IdP must provide some form of an `email` claim in their SAML assertion, and you must map the claim to the attribute for that provider.

The following configuration information for third-party SAML 2.0 IdP solutions is a good place to start setting up federation with Amazon Cognito user pools. For the most current information, consult your provider's documentation directly.

To sign SAML requests, you must configure your IdP to trust requests signed by your user pool signing certificate. To accept encrypted SAML responses, you must configure your IdP to encrypt *all* SAML responses to your user pool. Your provider will have documentation about configuring these features. For an example from Microsoft, see [Configure Microsoft Entra SAML token encryption](https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/howto-saml-token-encryption).

**Note**  
Amazon Cognito only requires your identity provider metadata document. Your provider might also offer customized configuration information for SAML 2.0 federation with IAM or AWS IAM Identity Center. To learn how to set up Amazon Cognito integration, look for general directions for retrieving the metadata document and manage the rest of the configuration in your user pool.


| Solution | More information | 
| --- | --- | 
| Microsoft Entra ID | [Federation Metadata](https://learn.microsoft.com/en-us/entra/identity-platform/federation-metadata) | 
| Okta | [How to Download the IdP Metadata and SAML Signing Certificates for a SAML App Integration](https://support.okta.com/help/s/article/Location-to-download-Okta-IDP-XML-metadata-for-a-SAML-app-in-the-new-Admin-User-Interface) | 
| Auth0 | [Configure Auth0 as SAML Identity Provider](https://auth0.com/docs/authenticate/protocols/saml/saml-sso-integrations/configure-auth0-saml-identity-provider) | 
| Ping Identity (PingFederate) | [Exporting SAML metadata from PingFederate](https://docs.pingidentity.com/integrations/contentful/configuring_single_sign-on/pf_contentful_integration_exporting_saml_metadata_from_pf.html) | 
| JumpCloud | [SAML Configuration Notes](https://jumpcloud.com/support/saml-configuration-notes) | 
| SecureAuth | [SAML application integration](https://docs.secureauth.com/2104/en/saml-application-integration.html) | 

# Adding and managing SAML identity providers in a user pool
<a name="cognito-user-pools-managing-saml-idp"></a>

After you configure your identity provider to work with Amazon Cognito, you can add it to your user pools and app clients. The following procedures demonstrate how to create, modify, and delete SAML providers in an Amazon Cognito user pool.

------
#### [ AWS Management Console ]

You can use the AWS Management Console to create and delete SAML identity providers (IdPs).

Before you create a SAML IdP, you must have the SAML metadata document that you get from the third-party IdP. For instructions on how to get or generate the required SAML metadata document, see [Configuring your third-party SAML identity provider](cognito-user-pools-integrating-3rd-party-saml-providers.md).

**To configure a SAML 2.0 IdP in your user pool**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Social and external providers** menu and then select **Add an identity provider**.

1. Choose a **SAML** IdP.

1. Enter a **Provider name**. You can pass this friendly name in an `identity_provider` request parameter to the [Authorize endpoint](authorization-endpoint.md).

1. Enter **Identifiers** separated by commas. An identifier tells Amazon Cognito it should check the email address a user enters when they sign in, and then direct them to the provider that corresponds to their domain.

1. Choose **Add sign-out flow** if you want Amazon Cognito to send signed sign-out requests to your provider when a user logs out. You must configure your SAML 2.0 IdP to send sign-out responses to the `https://mydomain.auth.us-east-1.amazoncognito.com/saml2/logout` endpoint that is created when you configure managed login. The `saml2/logout` endpoint uses POST binding.
**Note**  
If this option is selected and your SAML IdP expects a signed logout request, you must also provide your SAML IdP with the signing certificate from your user pool.  
The SAML IdP will process the signed logout request and sign out your user from the Amazon Cognito session.

1. Choose your **IdP-initiated SAML sign-in** configuration. As a security best practice, choose **Accept SP-initiated SAML assertions only**. If you have prepared your environment to securely accept unsolicited SAML sign-in sessions, choose **Accept SP-initiated and IdP-initiated SAML assertions**. For more information, see [SAML session initiation in Amazon Cognito user pools](cognito-user-pools-SAML-session-initiation.md).

1. Choose a **Metadata document source**. If your IdP offers SAML metadata at a public URL, you can choose **Metadata document URL** and enter that public URL. Otherwise, choose **Upload metadata document** and select a metadata file you downloaded from your provider earlier.
**Note**  
We recommend that you enter a metadata document URL if your provider has a public endpoint instead of uploading a file. Amazon Cognito automatically refreshes metadata from the metadata URL. Typically, metadata refresh happens every 6 hours or before the metadata expires, whichever is earlier.

1. **Map attributes between your SAML provider and your user pool** to map SAML provider attributes to the user profile in your user pool. Include your user pool required attributes in your attribute map. 

   For example, when you choose **User pool attribute** `email`, enter the SAML attribute name as it appears in the SAML assertion from your IdP. If your IdP offers sample SAML assertions, you can use these sample assertions to help you to find the name. Some IdPs use simple names, such as `email`, while others use names like the following.

   ```
   http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
   ```

1. Choose **Create**.

------
#### [ API/CLI ]

Use the following commands to create and manage a SAML identity provider (IdP).

**To create an IdP and upload a metadata document**
+ AWS CLI: `aws cognito-idp create-identity-provider`

  Example with metadata file: `aws cognito-idp create-identity-provider --user-pool-id us-east-1_EXAMPLE --provider-name=SAML_provider_1 --provider-type SAML --provider-details file:///details.json --attribute-mapping email=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`

  Where `details.json` contains:

  ```
  "ProviderDetails": { 
        "MetadataFile": "<SAML metadata XML>",
        "IDPSignout" : "true",
        "RequestSigningAlgorithm" : "rsa-sha256",
        "EncryptedResponses" : "true",
        "IDPInit" : "true"
  }
  ```
**Note**  
If the *<SAML metadata XML>* contains any instances of the character `"`, you must add `\` as an escape character: `\"`.

  Example with metadata URL: `aws cognito-idp create-identity-provider --user-pool-id us-east-1_EXAMPLE --provider-name=SAML_provider_1 --provider-type SAML --provider-details MetadataURL=https://myidp.example.com/sso/saml/metadata --attribute-mapping email=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`
+ AWS API: [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html)

**To upload a new metadata document for an IdP**
+ AWS CLI: `aws cognito-idp update-identity-provider`

  Example with metadata file: `aws cognito-idp update-identity-provider --user-pool-id us-east-1_EXAMPLE --provider-name=SAML_provider_1 --provider-details file:///details.json --attribute-mapping email=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`

  Where `details.json` contains:

  ```
  "ProviderDetails": { 
        "MetadataFile": "<SAML metadata XML>",
        "IDPSignout" : "true",
        "RequestSigningAlgorithm" : "rsa-sha256",
        "EncryptedResponses" : "true",
        "IDPInit" : "true"
  }
  ```
**Note**  
If the *<SAML metadata XML>* contains any instances of the character `"`, you must add `\` as an escape character: `\"`.

  Example with metadata URL: `aws cognito-idp update-identity-provider --user-pool-id us-east-1_EXAMPLE --provider-name=SAML_provider_1 --provider-details MetadataURL=https://myidp.example.com/sso/saml/metadata --attribute-mapping email=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`
+ AWS API: [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html)

**To get information about a specific IdP**
+ AWS CLI: `aws cognito-idp describe-identity-provider`

  `aws cognito-idp describe-identity-provider --user-pool-id us-east-1_EXAMPLE --provider-name=SAML_provider_1`
+ AWS API: [DescribeIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeIdentityProvider.html)

**To list information about all IdPs**
+ AWS CLI: `aws cognito-idp list-identity-providers`

  Example: `aws cognito-idp list-identity-providers --user-pool-id us-east-1_EXAMPLE --max-results 3`
+ AWS API: [ListIdentityProviders](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListIdentityProviders.html)

**To delete an IdP**
+ AWS CLI: `aws cognito-idp delete-identity-provider`

  `aws cognito-idp delete-identity-provider --user-pool-id us-east-1_EXAMPLE --provider-name=SAML_provider_1`
+ AWS API: [DeleteIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteIdentityProvider.html)

------

**To set up the SAML IdP to add a user pool as a relying party**
+ The user pools service provider URN is: `urn:amazon:cognito:sp:us-east-1_EXAMPLE`. Amazon Cognito requires an audience restriction value that matches this URN in the SAML response. Configure your IdP to use the following POST binding endpoint for the IdP-to-SP response message.

  ```
  https://mydomain.auth.us-east-1.amazoncognito.com/saml2/idpresponse
  ```
+ Your SAML IdP must populate `NameID` and any required attributes for your user pool in the SAML assertion. `NameID` is used for uniquely identifying your SAML federated user in the user pool. Your IdP must pass each user’s SAML name ID in a consistent, case-sensitive format. Any variation in the value of a user's name ID creates a new user profile.

**To provide a signing certificate to your SAML 2.0 IDP**
+ To download a copy of the the public key from Amazon Cognito that your IdP can use to validate SAML logout requests, choose the **Social and external providers** menu of your user pool, select your IdP, and under **View signing certificate**, select **Download as .crt**.

You can delete any SAML provider you have set up in your user pool with the Amazon Cognito console.

**To delete a SAML provider**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home).

1. In the navigation pane, choose **User Pools**, and choose the user pool you want to edit.

1. Choose the **Social and external providers** menu.

1. Select the radio button next to the SAML IdPs you wish to delete.

1. When you are prompted to **Delete identity provider**, enter the name of the SAML provider to confirm deletion, and then choose **Delete**.

# SAML session initiation in Amazon Cognito user pools
<a name="cognito-user-pools-SAML-session-initiation"></a>

Amazon Cognito supports service provider-initiated (SP-initiated) single sign-on (SSO) and IdP-initiated SSO. As a best security practice, implement SP-initiated SSO in your user pool. Section 5.1.2 of the [ SAML V2.0 Technical Overview](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0-cd-02.html#5.1.2.SP-Initiated%20SSO:%20%20Redirect/POST%20Bindings|outline) describes SP-initiated SSO. Amazon Cognito is the identity provider (IdP) to your app. The app is the service provider (SP) that retrieves tokens for authenticated users. However, when you use a third-party IdP to authenticate users, Amazon Cognito is the SP. When your SAML 2.0 users authenticate with an SP-initiated flow, they must always first make a request to Amazon Cognito and redirect to the IdP for authentication.

For some enterprise use cases, access to internal applications starts at a bookmark on a dashboard hosted by the enterprise IdP. When a user selects a bookmark, the IdP generates a SAML response and sends it to the SP to authenticate the user with the application.

You can configure a SAML IdP in your user pool to support IdP-initiated SSO. When you support IdP-initiated authentication, Amazon Cognito can't verify that it has solicited the SAML response that it receives because Amazon Cognito doesn't initiate authentication with a SAML request. In SP-initiated SSO, Amazon Cognito sets state parameters that validate a SAML response against the original request. With SP-initiated sign-in you can also guard against cross-site request forgery (CSRF).

**Topics**
+ [

## Implement SP-initated SAML sign-in
](#cognito-user-pools-saml-idp-authentication)
+ [

## Implement IdP-initiated SAML sign-in
](#cognito-user-pools-SAML-session-initiation-idp-initiation)

## Implement SP-initated SAML sign-in
<a name="cognito-user-pools-saml-idp-authentication"></a>

As a best practice, implement service-provider-initiated (SP-initiated) sign-in to your user pool. Amazon Cognito initiates your user's session and redirects them to your IdP. With this method, you have the greatest control over who presents sign-in requests. You can also permit IdP-initiated sign-in under certain conditions.

The following process shows how users complete SP-initiated sign in to your user pool through a SAML provider.

![\[Authentication flow diagram of Amazon Cognito SP-initiated SAML sign-in.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-saml-stepbystep.png)


1. Your user enters their email address at a sign-in page. To determine your user’s redirect to their IdP, you can collect their email address in a custom-built application or invoke managed login in web view.

   You can configure your managed login pages to display a list of IdPs or to prompt for an email address and match it to the identifier of your SAML IdP. To prompt for an email address, edit your managed login branding style and in **Foundation**, locate **Authentication behavior** and under **Provider display**, set **Display style** to **Domain search input**.

1. Your app invokes your user pool redirect endpoint and requests a session with the client ID that corresponds to the app and the IdP ID that corresponds to the user.

1. Amazon Cognito redirects your user to the IdP with a SAML request, [optionally signed](cognito-user-pools-SAML-signing-encryption.md#cognito-user-pools-SAML-signing.title), in an `AuthnRequest` element.

1. The IdP authenticates the user interactively, or with a remembered session in a browser cookie.

1. The IdP redirects your user to your user pool SAML response endpoint with the [optionally-encrypted](cognito-user-pools-SAML-signing-encryption.md#cognito-user-pools-SAML-signing-encryption.title) SAML assertion in their POST payload.
**Note**  
Amazon Cognito cancels sessions that don't receive a response within 5 minutes, and redirects the user to managed login. When your user experiences this outcome, they receive a `Something went wrong` error message.

1. After it verifies the SAML assertion and [maps user attributes](cognito-user-pools-specifying-attribute-mapping.md#cognito-user-pools-specifying-attribute-mapping.title) from the claims in the response, Amazon Cognito internally creates or updates the user's profile in the user pool. Typically, your user pool returns an authorization code to your user's browser session.

1. Your user presents their authorization code to your app, which exchanges the code for JSON web tokens (JWTs).

1. Your app accepts and processes your user's ID token as authentication, generates authorized requests to resources with their access token, and stores their refresh token.

When a user authenticates and receives an authorization code grant, the user pool returns ID, access, and refresh tokens. The ID token is a authentication object for OIDC-based identity management. The access token is an authorization object with [OAuth 2.0](https://oauth.net/2/) scopes. The refresh token is an object that generates new ID and access tokens when your user's current tokens have expired. You can configure the duration of users' tokens in your user pool app client.

You can also choose the duration of refresh tokens. After a user's refresh token expires, they must sign in again. If they authenticated through a SAML IdP, your users' session duration is set by the expiration of their tokens, not the expiration of their session with their IdP. Your app must store each user's refresh token and renew their session when it expires. Managed login maintains user sessions in a browser cookie that's valid for 1 hour.

## Implement IdP-initiated SAML sign-in
<a name="cognito-user-pools-SAML-session-initiation-idp-initiation"></a>

When you configure your identity provider for IdP-initiated SAML 2.0 sign-in, you can present SAML assertions to the `saml2/idpresponse` endpoint in your user pool domain without the need to initiate the session at the [Authorize endpoint](authorization-endpoint.md). A user pool with this configuration accepts IdP-initiated SAML assertions from a user pool external identity provider that the requested app client supports.

![\[Authentication flow diagram of Amazon Cognito IdP-initiated SAML sign-in.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-saml-idpinit.png)


1. A user requests SAML sign-in with your application.

1. Your application invokes a browser or redirects the user to the sign-in page for their SAML provider.

1. The IdP authenticates the user interactively, or with a remembered session in a browser cookie.

1. The IdP redirects your user to your application with the SAML assertion, or response, in their POST body.

1. Your application adds the SAML assertion to the POST body of a request to your user pool `saml2/idpresponse` endpoint.

1. Amazon Cognito issues an authorization code to your user.

1. Your user presents their authorization code to your app, which exchanges the code for JSON web tokens (JWTs).

1. Your application accepts and processes your user's ID token as authentication, generates authorized requests to resources with their access token, and stores their refresh token.

The following steps describe the overall process to configure and sign in with an IdP-initiated SAML 2.0 provider.

1. Create or designate a user pool and app client.

1. Create a SAML 2.0 IdP in your user pool.

1. Configure your IdP to support IdP initiation. IdP-initiated SAML introduces security considerations that other SSO providers aren’t subject to. Because of this, you can’t add non-SAML IdPs, including the user pool itself, to any app client that uses a SAML provider with IdP-initiated sign-in.

1. Associate your IdP-initiated SAML provider with an app client in your user pool.

1. Direct your user to the sign-in page for your SAML IdP and retrieve a SAML assertion.

1. Direct your user to your user pool `saml2/idpresponse` endpoint with their SAML assertion.

1. Receive JSON web tokens (JWTs).

To accept unsolicited SAML assertions in your user pool, you must consider its effect on your app security. Request spoofing and CSRF attempts are likely when you accept IdP-initiated requests. Although your user pool can't verify an IdP-initiated sign-in session, Amazon Cognito validates your request parameters and SAML assertions.

Additionally, your SAML assertion must not contain an `InResponseTo` claim and must have been issued within the previous 6 minutes.

You must submit requests with IdP-initiated SAML to your `/saml2/idpresponse`. For SP-initiated and managed login authorization requests, you must provide parameters that identify your requested app client, scopes, redirect URI, and other details as query string parameters in `HTTP GET` requests. For IdP-initiated SAML assertions, however, the details of your request must be formatted as a `RelayState` parameter in the body of an `HTTP POST` request. The request body must also contain your SAML assertion as a `SAMLResponse` parameter.

The following is an example request and response for an IdP-initiated SAML provider.

```
POST /saml2/idpresponse HTTP/1.1
User-Agent: USER_AGENT
Accept: */*
Host: example.auth.us-east-1.amazoncognito.com
Content-Type: application/x-www-form-urlencoded

SAMLResponse=[Base64-encoded SAML assertion]&RelayState=identity_provider%3DMySAMLIdP%26client_id%3D1example23456789%26redirect_uri%3Dhttps%3A%2F%2Fwww.example.com%26response_type%3Dcode%26scope%3Demail%2Bopenid%2Bphone

HTTP/1.1 302 Found
Date: Wed, 06 Dec 2023 00:15:29 GMT
Content-Length: 0
x-amz-cognito-request-id: 8aba6eb5-fb54-4bc6-9368-c3878434f0fb
Location: https://www.example.com?code=[Authorization code]
```

------
#### [ AWS Management Console ]

**To configure an IdP for IdP-initiated SAML**

1. Create a [user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html), [app client](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-configuring-app-integration.html), and SAML identity provider.

1. Disassociate all social and OIDC identity providers from your app client, if any are associated.

1. Navigate to the **Social and external providers** menu of your user pool.

1. Edit or add a SAML provider.

1. Under **IdP-initiated SAML sign-in**, choose **Accept SP-initiated and and IdP-initiated SAML assertions**.

1. Choose **Save changes**.

------
#### [ API/CLI ]

**To configure an IdP for IdP-initiated SAML**

Configure IdP-initiated SAML with the `IDPInit` parameter in a [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html) or [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html) API request. The following is an example `ProviderDetails` of an IdP that supports IdP-initiated SAML.

```
"ProviderDetails": { 
      "MetadataURL" : "https://myidp.example.com/saml/metadata",
      "IDPSignout" : "true",
      "RequestSigningAlgorithm" : "rsa-sha256",
      "EncryptedResponses" : "true",
      "IDPInit" : "true"
}
```

------

# Signing out SAML users with single sign-out
<a name="cognito-user-pools-saml-idp-sign-out"></a>

Amazon Cognito supports SAML 2.0 [single logout](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0-cd-02.html#5.3.Single%20Logout%20Profile|outline) (SLO. With SLO, your application can sign out users from their SAML identity providers (IdPs) when they sign out from your user pool. This way, when users want to sign in to your application again, they must authenticate with their SAML IdP. Otherwise, they might have IdP or user pool browser cookies in place that pass them through to your application without the requirement that they provide credentials.

When you configure your SAML IdP to support **Sign-out flow**, Amazon Cognito redirects your user with a signed SAML logout request to your IdP. Amazon Cognito determines the redirect location from the `SingleLogoutService` URL in your IdP metadata. Amazon Cognito signs the sign-out request with your user pool signing certificate.

![\[Authentication flow diagram of Amazon Cognito SAML sign-out. The user requests sign-out and Amazon Cognito redirects them to their provider with a SAML sign-out request.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-saml-sign-out.png)


When you direct a user with a SAML session to your user pool `/logout` endpoint, Amazon Cognito redirects your SAML user with the following request to the SLO endpoint that's specified in the IdP metadata.

```
https://[SingleLogoutService endpoint]?
SAMLRequest=[encoded SAML request]&
RelayState=[RelayState]&
SigAlg=http://www.w3.org/2001/04/xmldsig-more#rsa-sha256&
Signature=[User pool RSA signature]
```

Your user then returns to your `saml2/logout` endpoint with a `LogoutResponse` from their IdP. Your IdP must send the `LogoutResponse` in an `HTTP POST` request. Amazon Cognito then redirects them to the redirect destination from their initial sign-out request.

Your SAML provider might send a `LogoutResponse` with more than one `AuthnStatement` in it. The `sessionIndex` in the first `AuthnStatement` in a response of this type must match the `sessionIndex` in the SAML response that originally authenticated the user. If the `sessionIndex` is in any other `AuthnStatement`, Amazon Cognito won’t recognize the session and your user won’t be signed out.

------
#### [ AWS Management Console ]

**To configure SAML sign-out**

1. Create a [user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html), [app client](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-configuring-app-integration.html), and SAML IdP.

1. When you create or edit your SAML identity provider, under **Identity provider information**, check the box with the title **Add sign-out flow**.

1. From the **Social and external providers** menu of your user pool, choose your IdP and locate the **Signing certificate**.

1. Choose **Download as .crt**.

1. Configure your SAML provider to support SAML single logout and request signing, and upload the user pool signing certificate. Your IdP must redirect to `/saml2/logout` in your user pool domain.

------
#### [ API/CLI ]

**To configure SAML sign-out**

Configure single logout with the `IDPSignout` parameter of a [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html) or [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html) API request. The following is an example `ProviderDetails` of an IdP that supports SAML single logout.

```
"ProviderDetails": { 
      "MetadataURL" : "https://myidp.example.com/saml/metadata",
      "IDPSignout" : "true",,
      "RequestSigningAlgorithm" : "rsa-sha256",
      "EncryptedResponses" : "true",
      "IDPInit" : "true"
}
```

------

# SAML signing and encryption
<a name="cognito-user-pools-SAML-signing-encryption"></a>

SAML 2.0 sign-in is built around the user of an application as a bearer of requests and responses in their authentication flow. You might want to ensure that users aren't reading or modifying these SAML documents in transit. To accomplish this, add SAML signing and encryption to the SAML identity providers (IdPs) in your user pool. With SAML signing, your user pools adds a signature to SAML sign-in and sign-out requests. With your user pool public key, your IdP can verify that it's receiving unmodified SAML requests. Then, when your IdP responds and passes SAML assertions to users' browser sessions, the IdP can encrypt that response so that the user can't inspect their own attributes and entitlements.

With SAML signing and encryption, all cryptographic operations during user pool SAML operations must generate signatures and ciphertext with user-pool-provided keys that Amazon Cognito generates. Currently, you can't configure a user pool to sign requests or accept encrypted assertions with an external key.

**Note**  
Your user pool certificates are valid for 10 years. Once per year, Amazon Cognito generates new signing and encryption certificates for your user pool. Amazon Cognito returns the most recent certificate when you request the signing certificate, and signs requests with the most recent signing certificate. Your IdP can encrypt SAML assertions with any user pool encryption certificate that isn’t expired. Your previous certificates continue to be valid for their entire duration and the public key doesn't change between certificates. As a best practice, update the certificate in your provider configuration annually.

**Topics**
+ [

## Accepting encrypted SAML responses from your IdP
](#cognito-user-pools-SAML-encryption)
+ [

## Signing SAML requests
](#cognito-user-pools-SAML-signing)

## Accepting encrypted SAML responses from your IdP
<a name="cognito-user-pools-SAML-encryption"></a>

Amazon Cognito and your IdP can establish confidentiality in SAML responses when users sign in and sign out. Amazon Cognito assigns a public-private RSA key pair and a certificate to each external SAML provider that you configure in your user pool. When you enable response encryption for your user pool SAML provider, you must upload your certificate to an IdP that supports encrypted SAML responses. Your user pool connection to your SAML IdP isn’t functional before your IdP begins to encrypt all SAML assertions with the provided key.

The following is an overview of the flow of an encrypted SAML sign-in.

1. Your user starts sign-in and chooses their SAML IdP.

1. Your user pool [Authorize endpoint](authorization-endpoint.md) redirects your user to their SAML IdP with a SAML sign-in request. Your user pool can optionally accompany this request with a signature that enables integrity verification by the IdP. When you want to sign SAML requests, you must configure your IdP to accept requests that your user pool has signed with the public key in the signing certificate.

1. The SAML IdP signs in your user and generates a SAML response. The IdP encrypts the response with the public key and redirects your user to your user pool `/saml2/idpresponse` endpoint. The IdP must encrypt the response as defined by the SAML 2.0 specification. For more information, see `Element <EncryptedAssertion>` in [Assertions and Protocols for the OASIS Security Assertion Markup Language (SAML) V2.0](https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf).

1. Your user pool decrypts the ciphertext in the SAML response with the private key and signs in your user.

**Important**  
When you enable response encryption for a SAML IdP in your user pool, your IdP must encrypt all responses with a public key that's specific to the provider. Amazon Cognito doesn't accept unencrypted SAML responses from a SAML external IdP that you configure to support encryption. 

Any external SAML IdP in your user pool can support response encryption, and each IdP receives its own key pair.

------
#### [ AWS Management Console ]

**To configure SAML response encryption**

1. Create a [user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html), [app client](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-configuring-app-integration.html), and SAML IdP.

1. When you create or edit your SAML identity provider, under **Sign requests and encrypt responses**, check the box with the title **Require encrypted SAML assertions from this provider**.

1. From the **Social and external providers** menu of your user pool, select your SAML IdP and choose **View encryption certificate**.

1. Choose **Download as .crt** and provide the downloaded file to your SAML IdP. Configure your SAML IdP to encrypt SAML responses with the key in the certificate.

------
#### [ API/CLI ]

**To configure SAML response encryption**

Configure response encryption with the `EncryptedResponses` parameter of a [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html) or [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html) API request. The following is an example `ProviderDetails` of an IdP that supports request signing.

```
"ProviderDetails": { 
      "MetadataURL" : "https://myidp.example.com/saml/metadata",
      "IDPSignout" : "true",
      "RequestSigningAlgorithm" : "rsa-sha256",
      "EncryptedResponses" : "true",
      "IDPInit" : "true"
}
```

To get the encryption certificate from your user pool, make a [DescribeIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeIdentityProvider.html) API request and retrieve the value of `ActiveEncryptionCertificate` in the response parameter `ProviderDetails`. Save this certificate and provide it to your IdP as the encryption certificate for sign-in requests from your user pool.

------

## Signing SAML requests
<a name="cognito-user-pools-SAML-signing"></a>

The ability to prove the integrity of SAML 2.0 requests to your IdP is a security advantage of Amazon Cognito SP-initiated SAML sign-in. Each user pool with a domain receives a user pool X.509 signing certificate. With the public key in this certificate, user pools apply a cryptographic signature to the *sign-out requests* that your user pool generates when your users select a SAML IdP. You can optionally configure your app client to sign SAML *sign-in requests*. When you sign your SAML requests, your IdP can check that the signature in the XML metadata of your requests matches the public key in the user pool certificate that you provide.

------
#### [ AWS Management Console ]

**To configure SAML request signing**

1. Create a [user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html), [app client](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-configuring-app-integration.html), and SAML IdP.

1. When you create or edit your SAML identity provider, under **Sign requests and encrypt responses**, check the box with the title **Sign SAML requests to this provider**.

1. From the **Social and external providers** menu of your user pool, choose **View signing certificate**.

1. Choose **Download as .crt** and provide the downloaded file to your SAML IdP. Configure your SAML IdP to verify the signature of incoming SAML requests.

------
#### [ API/CLI ]

**To configure SAML request signing**

Configure request signing with the `RequestSigningAlgorithm` parameter of a [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html) or [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html) API request. The following is an example `ProviderDetails` of an IdP that supports request signing.

```
"ProviderDetails": { 
      "MetadataURL" : "https://myidp.example.com/saml/metadata",
      "IDPSignout" : "true",
      "RequestSigningAlgorithm" : "rsa-sha256",
      "EncryptedResponses" : "true",
      "IDPInit" : "true"
}
```

------

# SAML identity provider names and identifiers
<a name="cognito-user-pools-managing-saml-idp-naming"></a>

When you name your SAML identity providers (IdPs) and assign IdP identifiers, you can automate the flow of SP-initiated sign-in and sign-out requests to that provider. For information about string constraints to the provider name, see the `ProviderName` property of [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html#CognitoUserPools-CreateIdentityProvider-request-ProviderName).

![\[Authentication flow diagram of Amazon Cognito SP-initiated SAML sign-in with an IdP identifier and managed login. The user provides an email address to managed login and Amazon Cognito automatically redirects them to their provider.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-saml-identifier.png)


You can also choose up to 50 identifiers for your SAML providers. An identifier is a friendly name for an IdP in your user pool, and must be unique within the user pool. If your SAML identifiers match your users' email domains, managed login requests each user's email address, evaluates the domain in their email address, and redirects them to the IdP that corresponds to their domain. Because the same organization can own multiple domains, a single IdP can have multiple identifiers.

Whether you use or don't use email-domain identifiers, you can use identifiers in a multi-tenant app to redirect users to the correct IdP. When you want to bypass managed login entirely, you can customize the links that you present to users such that they redirect through the [Authorize endpoint](authorization-endpoint.md) directly to their IdP. To sign in your users with an identifier and redirect to their IdP, include the identifier in the format `idp_identifier=myidp.example.com` in the request parameters of their initial authorization request.

Another method to pass a user through to your IdP is to populate the parameter `identity_provider` with the name of your IdP in the following URL format.

```
https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
identity_provider=MySAMLIdP&
client_id=1example23456789&
redirect_uri=https://www.example.com
```

After a user signs in with your SAML IdP, your IdP redirects them with a SAML response in the `HTTP POST` body to your `/saml2/idpresponse` endpoint. Amazon Cognito processes the SAML assertion and, if the claims in the response meet expectations, redirects to your app client callback URL. After your user has completed authentication in this way, they have interacted with webpages for only your IdP and your app.

With IdP identifiers in a domain format, managed login requests email addresses at sign-in and then, when the email domain matches an IdP identifier, redirects users to the sign-in page for their IdP. As an example, you build an app that requires sign-in by employees of two different companies. The first company, AnyCompany A, owns `exampleA.com` and `exampleA.co.uk`. The second company, AnyCompany B, owns `exampleB.com`. For this example, you have set up two IdPs, one for each company, as follows: 
+ For IdP A, you define identifiers `exampleA.com` and `exampleA.co.uk`.
+ For IdP B, you define identifier `exampleB.com`.

In your app, invoke managed login for your app client to prompt each user to enter their email address. Amazon Cognito derives the domain from the email address, correlates the domain to an IdP with a domain identifier, and redirects your user to the correct IdP with a request to the [Authorize endpoint](authorization-endpoint.md) that contains an `idp_identifier` request parameter. For example, if a user enters `bob@exampleA.co.uk`, the next page that they interact with is the IdP sign-in page at `https://auth.exampleA.co.uk/sso/saml`.

You can also implement the same logic independently. In your app, you can build a custom form that collects user input and correlates it to the correct IdP according to your own logic. You can generate custom portals for each of your app tenants, where each links to the authorize endpoint with the tenant's identifier in the request parameters.

To collect an email address and parse the domain in managed login, assign at least one identifier to each SAML IdP that you have assigned to your app client. By default, the managed login sign-in screen displays a button for each of the IdPs that you have assigned to your app client. However, if you have successfully assigned identifiers, your classic hosted UI sign-in page looks like the following image.

![\[An Amazon Cognito managed login sign-in page displaying local user sign-in and a prompt for a federated user to enter an email address.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/cup-saml-identifiers.png)


**Note**  
In the classic hosted UI, the sign-in page for your app client automatically prompts for an email address when you assign identifiers to your IdPs. In the managed login experience, you must enable this behavior in the branding editor. In the **Authentication behavior** settings category, select **Domain search input** under the heading **Provider display**.

Domain parsing in managed login requires that you use domains as your IdP identifiers. If you assign an identifier of any type to each of the SAML IdPs for an app client, managed login for that app no longer displays IdP-selection buttons. Add IdP identifiers for SAML when you intend to use email parsing or custom logic to generate redirects. When you want to generate silent redirects and also want your managed login pages to display a list of IdPs, don't assign identifiers and use the `identity_provider` request parameter in your authorization requests.
+ If you assign only one SAML IdP to your app client, the managed login sign-in page displays a button to sign in with that IdP.
+ If you assign an identifier to every SAML IdP that you activate for your app client, a user input prompt for an email address appears in the managed login sign-in page.
+ If you have multiple IdPs and you do not assign an identifier to all of them, the managed login sign-in page displays a button to sign in with each assigned IdP.
+ If you assigned identifiers to your IdPs and you want your managed login pages to display a selection of IdP buttons, add a new IdP that has no identifier to your app client, or create a new app client. You can also delete an existing IdP and add it again without an identifier. If you create a new IdP, your SAML users will create new user profiles. This duplication of active users might have a billing impact in the month that you change your IdP configuration.

For more information about IdP setup, see [Configuring identity providers for your user pool](cognito-user-pools-identity-provider.md).

# Using OIDC identity providers with a user pool
<a name="cognito-user-pools-oidc-idp"></a>

Users can sign in to your application using their existing accounts from OpenID Connect (OIDC) identity providers (IdPs). With OIDC providers, users of independent single sign-on systems can provide existing credentials while your application receives OIDC tokens in the shared format of user pools. To configure an OIDC IdP, set up your IdP to handle your user pool as the RP and configure your application to handle your user pool as the IdP. Amazon Cognito serves as an intermediate step between multiple OIDC IdPs and your applications. Your user pool applies attribute-mapping rules to the claims in the ID and access tokens that your provider passes directly to your user pool. Amazon Cognito then issues new tokens based on the mapped user attributes and any additional adjustments you've made to the authentication flow with [Lambda triggers](cognito-user-pools-working-with-lambda-triggers.md#lambda-triggers-for-federated-users).

Users who sign in with an OIDC IdP aren't required to provide new credentials or information to access your user pool application. Your application can silently redirect them to their IdP for sign-in, with a user pool as a tool in the background that standardizes the token format for your application. To learn more about IdP redirection, see [Authorize endpoint](authorization-endpoint.md).

Like with other third-party identity providers, you must register your application with the OIDC provider and obtain information about the IdP application that you want to connect to your user pool. A user pool OIDC IdP requires a client ID, client secret, scopes that you want to request, and information about provider service endpoints. Your user pool can discover the provider OIDC endpoints from a discovery endpoint or you can enter them manually. You must also examine provider ID tokens and create attribute mappings between the IdP and the attributes in your user pool.

![\[User pool OIDC IdP authentication flow\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/flow-cup-oidc-endpoints.png)


See [OIDC user pool IdP authentication flow](cognito-user-pools-oidc-flow.md) for more details about this authentication flow.

**Note**  
Sign-in through a third party (federation) is available in Amazon Cognito user pools. This feature is independent of OIDC federation with Amazon Cognito identity pools.

You can add an OIDC IdP to your user pool in the AWS Management Console, through the AWS CLI, or with the user pool API method [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html).

**Topics**
+ [

## Prerequisites
](#cognito-user-pools-oidc-idp-prerequisites)
+ [

## Register an application with an OIDC IdP
](#cognito-user-pools-oidc-idp-step-1)
+ [

## Add an OIDC IdP to your user pool
](#cognito-user-pools-oidc-idp-step-2)
+ [

## Test your OIDC IdP configuration
](#cognito-user-pools-oidc-idp-step-3)
+ [

# OIDC user pool IdP authentication flow
](cognito-user-pools-oidc-flow.md)

## Prerequisites
<a name="cognito-user-pools-oidc-idp-prerequisites"></a>

Before you begin, you need the following:
+ A user pool with an app client and a user pool domain. For more information, see [Create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).
+ An OIDC IdP with the following configuration: 
  + Supports `client_secret_post` client authentication. Amazon Cognito doesn't check the `token_endpoint_auth_methods_supported` claim at the OIDC discovery endpoint for your IdP. Amazon Cognito doesn't support `client_secret_basic` client authentication. For more information on client authentication, see [Client Authentication](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication) in the OpenID Connect documentation.
  + Only uses HTTPS for OIDC endpoints such as `openid_configuration`, `userInfo`, and `jwks_uri`.
  + Only uses TCP ports 80 and 443 for OIDC endpoints.
  + Only signs ID tokens with HMAC-SHA, ECDSA, or RSA algorithms.
  + Publishes a key ID `kid` claim at its `jwks_uri` and includes a `kid` claim in its tokens.
  + Presents a non-expired public key with a valid root CA trust chain.

## Register an application with an OIDC IdP
<a name="cognito-user-pools-oidc-idp-step-1"></a>

Before you add an OIDC IdP to your user pool configuration and assign it to app clients, you set up an OIDC client application in your IdP. Your user pool is the relying-party application that will manage authentication with your IdP.

**To register with an OIDC IdP**

1. Create a developer account with the OIDC IdP.  
**Links to OIDC IdPs**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-oidc-idp.html)

1. Register your user pool domain URL with the `/oauth2/idpresponse` endpoint with your OIDC IdP. This ensures that the OIDC IdP later accepts it from Amazon Cognito when it authenticates users.

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/idpresponse
   ```

1. Select the [scopes](cognito-user-pools-define-resource-servers.md#cognito-user-pools-define-resource-servers-about-scopes) that you want your user directory to share with your user pool. The scope **openid** is required for OIDC IdPs to offer any user information. The `email` scope is needed to grant access to the `email` and `email_verified` [claims](https://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims). Additional scopes in the OIDC specification are `profile` for all user attributes and `phone` for `phone_number` and `phone_number_verified`.

1. The OIDC IdP provides you with a client ID and a client secret. Note these values and add them to the configuration of the OIDC IdP that you add to your user pool later.

**Example: Use Salesforce as an OIDC IdP with your user pool**

 You use an OIDC IdP when you want to establish trust between an OIDC-compatible IdP such as Salesforce and your user pool.

1. [Create an account](https://developer.salesforce.com/signup) on the Salesforce Developers website.

1. [Sign in](https://developer.salesforce.com) through your developer account that you set up in the previous step.

1. From your Salesforce page, do one of the following:
   +  If you’re using Lightning Experience, choose the setup gear icon, then choose **Setup Home**.
   +  If you’re using Salesforce Classic and you see **Setup** in the user interface header, choose it.
   +  If you’re using Salesforce Classic and you don’t see **Setup** in the header, choose your name from the top navigation bar, and choose **Setup** from the drop-down list.

1. On the left navigation bar, choose **Company Settings**. 

1. On the navigation bar, choose **Domain**, enter a domain, and choose **Create**. 

1. On the left navigation bar, under **Platform Tools**, choose **Apps**. 

1. Choose **App Manager**.

1. 

   1. Choose **New connected app**.

   1. Complete the required fields.

      Under **Start URL**, enter a URL at the `/authorize` endpoint for the user pool domain that signs in with your Salesforce IdP. When your users access your connected app, Salesforce directs them to this URL to complete sign-in. Then Salesforce redirects the users to the callback URL that you have associated with your app client.

      ```
      https://mydomain.auth.us-east-1.amazoncognito.com/authorize?response_type=code&client_id=<your_client_id>&redirect_uri=https://www.example.com&identity_provider=CorpSalesforce
      ```

   1. Enable **OAuth settings** and enter the URL of the `/oauth2/idpresponse` endpoint for your user pool domain in **Callback URL**. This is the URL where Salesforce issues the authorization code that Amazon Cognito exchanges for an OAuth token.

      ```
      https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/idpresponse
      ```

1. Select your [scopes](https://openid.net/specs/openid-connect-basic-1_0.html#Scopes). You must include the scope **openid**. To grant access to the **email** and **email\$1verified** [claims](https://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims), add the **email** scope. Separate scopes by spaces.

1. Choose **Create**.

   In Salesforce, the client ID is called a **Consumer Key**, and the client secret is a **Consumer Secret**. Note your client ID and client secret. You will use them in the next section.

## Add an OIDC IdP to your user pool
<a name="cognito-user-pools-oidc-idp-step-2"></a>

After you set up your IdP, you can configure your user pool to handle authentication requests with an OIDC IdP.

------
#### [ Amazon Cognito console ]

**Add an OIDC IdP in the console**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools** from the navigation menu.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Social and external providers** menu and then select **Add an identity provider**.

1. Choose an **OpenID Connect** IdP.

1. Enter a unique **Provider name**.

1. Enter the IdP **Client ID**. This is the ID of the application client you build in your OIDC IdP. The client ID that you provide must be an OIDC provider that you've configured with a callback url of `https://[your user pool domain]/oauth2/idpresponse`.

1. Enter the IdP **Client secret**. This must be the client secret for the same application client from the previous step.

1. <a name="cognito-user-pools-oidc-step-2-substep-9"></a>Enter **Authorized scopes** for this provider. Scopes define which groups of user attributes (such as `name` and `email`) that your application will request from your provider. Scopes must be separated by spaces, following the [OAuth 2.0](https://tools.ietf.org/html/rfc6749#section-3.3) specification.

   Your IdP might prompt users to consent to providing these attributes to your application when they sign in.

1. Choose an **Attribute request method**. IdPs might require that requests to their `userInfo` endpoints are formatted as either `GET` or `POST`. The Amazon Cognito `userInfo` endpoint requires `HTTP GET` requests, for example.

1. Choose a **Setup method** for the way that you want your user pool to determine the path to key OIDC-federation endpoints at your IdP. Typically, IdPs host a `/well-known/openid-configuration` endpoint at an issuer base URL. If this is the case for your provider, the **Auto fill through issuer URL** option prompts you for that base URL, attempts to access the `/well-known/openid-configuration` path from there, and reads the endpoints listed there. You might have non-typical endpoint paths or wish to pass requests to one or more endpoints through an alternate proxy. In this case, select **Manual input** and specify paths for the `authorization`, `token`, `userInfo`, and `jwks_uri` endpoints.
**Note**  
The URL should start with `https://`, and shouldn't end with a slash `/`. Only port numbers 443 and 80 can be used with this URL. For example, Salesforce uses this URL:  
`https://login.salesforce.com`   
If you choose auto fill, the discovery document must use HTTPS for the following values: `authorization_endpoint`, `token_endpoint`, `userinfo_endpoint`, and `jwks_uri`. Otherwise the login will fail.

1. Configure your attribute-mapping rules under **Map attributes between your OpenID Connect provider and your user pool**. **User pool attribute** is the *destination* attribute in the Amazon Cognito user profile and **OpenID Connect attribute** is the *source* attribute that you want Amazon Cognito to find in an ID-token claim or `userInfo` response. Amazon Cognito automatically maps the OIDC claim **sub** to `username` in the destination user profile.

   For more information, see [Mapping IdP attributes to profiles and tokens](cognito-user-pools-specifying-attribute-mapping.md).

1. Choose **Add identity provider**.

1. From the **App clients** menu, select an app client from the list. Navigate to the **Login pages** tab and under **Managed login pages configuration**, select **Edit**. Locate **Identity providers** and add your new OIDC IdP.

1. Choose **Save changes**.

------
#### [ API/CLI ]

See the OIDC configuration in example two at [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html#API_CreateIdentityProvider_Example_2). You can modify this syntax and use it as the request body of `CreateIdentityProvider`, `UpdateIdentityProvider`, or the `--cli-input-json` input file for [create-identity-provider](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-identity-provider.html).

------

## Test your OIDC IdP configuration
<a name="cognito-user-pools-oidc-idp-step-3"></a>

In your application, you must invoke a browser in the user's client so that they can sign in with their OIDC provider. Test sign-in with your provider after you have completed the setup procedures in the preceding sections. The following example URL loads the sign-in page for your user pool with a prefix domain.

```
https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com
```

This link is the page that Amazon Cognito directs you to when you go to the **App clients** menu, select an app client, navigate to the **Login pages** tab, and select **View login page**. For more information about user pool domains, see [Configuring a user pool domain](cognito-user-pools-assign-domain.md). For more information about app clients, including client IDs and callback URLs, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).

The following example link sets up silent redirect to the `MyOIDCIdP` provider from the [Authorize endpoint](authorization-endpoint.md) with an `identity_provider` query parameter. This URL bypasses interactive user pool sign-in with managed login and goes directly to the IdP sign-in page.

```
https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?identity_provider=MyOIDCIdP&response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com
```

# OIDC user pool IdP authentication flow
<a name="cognito-user-pools-oidc-flow"></a>

With OpenID Connect (OIDC) sign-in, your user pool automates an authorization-code sign-in flow with your identity provider (IdP). After your user completes sign-in with their IdP, Amazon Cognito collects their code at the `oauth2/idpresponse` endpoint of the external provider. With the resulting access token, your user pool queries the IdP `userInfo` endpoint to retrieve user attributes. Your user pool then compares the received attributes to the attribute-mapping rules you've set up and populates the user's profile and ID token accordingly.

The OAuth 2.0 scopes that you request in your OIDC provider configuration define the user attributes that the IdP provides to Amazon Cognito. As a best security practice, only request the scopes that correspond to attributes that you want to map to your user pool. For example, if your user pool requests `openid profile`, you'll get all possible attributes, but if you request `openid email phone_number` you'll only get the user's email address and phone number. You can configure the scopes that you [request from OIDC IdPs](cognito-user-pools-oidc-idp.md#cognito-user-pools-oidc-step-2-substep-9) to differ from those you authorize and request in the [app client](user-pool-settings-client-apps.md#user-pool-settings-client-apps-scopes) and user pool authentication request.

When your user signs in to your application using an OIDC IdP, your user pool conducts the following authentication flow.

1. A user accesses your managed login sign-in page, and chooses to sign in with their OIDC IdP.

1. Your application directs the user's browser to the authorization endpoint of your user pool.

1. Your user pool redirects the request to the authorization endpoint of the OIDC IdP.

1. Your IdP displays a login prompt.

1. In your application, your user's session displays a sign-in prompt for the OIDC IdP.

1. The user enters their credentials for the IdP or presents a cookie for an already-authenticated session.

1. After your user authenticates, the OIDC IdP redirects to Amazon Cognito with an authorization code.

1. Your user pool exchanges the authorization code for ID and access tokens. Amazon Cognito receives access tokens when you configure your IdP with the scopes `openid`. The claims in the ID token and the `userInfo` response are determined by additional scopes from your IdP configuration, for example `profile` and `email`.

1. Your IdP issues the requested tokens.

1. Your user pool determines the path to the IdP `jwks_uri` endpoint from the issuer URLs in your IdP configuration and requests the token signing keys from the JSON web key set (JWKS) endpoint.

1. The IdP returns signing keys from the JWKS endpoint.

1. Your user pool validates the IdP tokens from signature and expiration data in the tokens.

1. Your user pool authorizes a request to the IdP `userInfo` endpoint with the access token. The IdP responds with user data based on the access token scopes.

1. Your user pool compares the ID token and `userInfo` response from the IdP to the attribute-mapping rules in your user pool. It writes mapped IdP attributes to user pool profile attributes.

1. Amazon Cognito issues your application bearer tokens, which might include identity, access, and refresh tokens.

1. Your application processes the user pool tokens and signs the user in.

![\[User pool OIDC IdP authentication flow\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/flow-cup-oidc-endpoints.png)


**Note**  
Amazon Cognito cancels authentication requests that do not complete within 5 minutes, and redirects the user to managed login. The page displays a `Something went wrong` error message.

OIDC is an identity layer on top of OAuth 2.0, which specifies JSON-formatted (JWT) identity tokens that are issued by IdPs to OIDC client apps (relying parties). See the documentation for your OIDC IdP for information about to add Amazon Cognito as an OIDC relying party.

When a user authenticates with an authorization code grant, the user pool returns ID, access, and refresh tokens. The ID token is a standard [OIDC](http://openid.net/specs/openid-connect-core-1_0.html) token for identity management, and the access token is a standard [OAuth 2.0](https://oauth.net/2/) token. For more information about grant types that your user pool app client can support, see [Authorize endpoint](authorization-endpoint.md).

## How a user pool processes claims from an OIDC provider
<a name="how-a-cognito-user-pool-processes-claims-from-an-oidc-provider"></a>

When your user completes sign-in with a third-party OIDC provider, managed login retrieves an authorization code from the IdP. Your user pool exchanges the authorization code for access and ID tokens with the `token` endpoint of your IdP. Your user pool doesn't pass these tokens on to your user or your app, but uses them to build a user profile with data that it presents in claims in its own tokens.

 Amazon Cognito doesn't independently validate the access token. Instead, it requests user-attribute information from the provider `userInfo` endpoint and expects the request to be denied if the token isn't valid.

Amazon Cognito validates the provider ID token with the following checks:

1. Check that the provider signed the token with an algorithm from the following set: RSA, HMAC, Elliptic Curve.

1. If the provider signed the token with an asymmetric signing algorithm, check that the signing key ID in the token `kid` claim is listed at the provider `jwks_uri` endpoint. Amazon Cognito refreshes the signing key from the JWKS endpoint in your IdP configuration for each IdP ID token that it processes.

1. Compare the ID token signature to the signature that it expects based on provider metadata.

1. Compare the `iss` claim to the OIDC issuer configured for the IdP.

1. Compare the `aud` claim matches the client ID configured on the IdP, or that it contains the configured client ID if there are multiple values in the `aud` claim.

1. Check that the timestamp in the `exp` claim is not before the current time.

Your user pool validates the ID token, then attempts a request to the provider `userInfo` endpoint with the provider access token. It retrieves any user profile information that the scopes in the access token authorize it to read. Your user pool then searches for the user attributes that you have set as required in your user pool. You must create attribute mappings in your provider configuration for required attributes. Your user pool checks the provider ID token and the `userInfo` response. Your user pool writes all claims that match mapping rules to user attributes on the user pool user profile. Your user pool ignores attributes that match a mapping rule but aren't required and aren't found in the provider's claims.

# Mapping IdP attributes to profiles and tokens
<a name="cognito-user-pools-specifying-attribute-mapping"></a>

Identity provider (IdP) services, including Amazon Cognito, can typically record more information about a user. You might want to know what company they work for, how to contact them, and other identifying information. But the format that these attributes take has variations between providers. For example, set up three IdPs from three different vendors with your user pool and examine an example SAML assertion, ID token, or `userInfo` payload from each. One will represent the user's email address as `email`, another as `emailaddress`, and the third as `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`.

A major benefit that comes from consolidation of IdPs with a user pool is the ability to map the variety of attribute names into a single OIDC token schema with consistent, predicable, shared attribute names. This way, your developers aren't required to maintain the logic for processing a complex variety of single sign-on events. This format consolidation is attribute mapping. User pool attribute mapping assigns IdP attribute names to the corresponding user pool attribute names. For example, you can configure your user pool to write the value of an `emailaddress` claim to the standard user pool attribute `email`.

Each user pool IdP has a separate attribute-mapping schema. To specify attribute mappings for your IdP, configure a user pool identity provider in the Amazon Cognito console, an AWS SDK, or the user pools REST API .

## Things to know about mappings
<a name="cognito-user-pools-specifying-attribute-mapping-requirements"></a>

Before you begin to set up user-attribute mapping, review the following important details.
+ When a federated user signs in to your application, a mapping must be present for each user pool attribute that your user pool requires. For example, if your user pool requires an `email` attribute for sign-up, map this attribute to its equivalent from the IdP.
+ By default, mapped email addresses are unverified. You can't verify a mapped email address using a one-time code. Instead, map an attribute from your IdP to get the verification status. For example, Google and most OIDC providers include the `email_verified` attribute.
+ You can map identity provider (IdP) tokens to custom attributes in your user pool. Social providers present an access token, and OIDC providers present an access and ID token. To map a token, add a custom attribute with a maximum length of 2,048 characters, grant your app client write access to the attribute, and map `access_token` or `id_token` from the IdP to the custom attribute.
+ For each mapped user pool attribute, the maximum value length of 2,048 characters must be large enough for the value that Amazon Cognito obtains from the IdP. Otherwise, Amazon Cognito reports an error when users sign in to your application. Amazon Cognito doesn't support mapping IdP tokens to custom attributes when the tokens are more than 2,048 characters long.
+ Amazon Cognito derives the `username` attribute in a federated user's profile from specific claims that your federated IdP passes, as shown in the following table. Amazon Cognito prepends this attribute value with the name of your IdP, for example `MyOIDCIdP_[sub]`. When you want your federated users to have an attribute that exactly matches an attribute in your external user directory, map that attribute to a Amazon Cognito sign-in attribute like `preferred_username`.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html)
+ When a user pool is [case insensitive](user-pool-case-sensitivity.md), Amazon Cognito converts the username source attribute to lowercase in federated users' automatically-generated usernames. The following is an example username for a case-sensitive user pool: `MySAML_TestUser@example.com`. The following is the same username for a case-*insensitive* user pool: `MySAML_testuser@example.com`.

  In case-insensitive user pools, your Lambda triggers that process the username must account for this modification to any mixed-case claims for user name source attributes. To link your IdP to a user pool that has a different case-sensitivity setting than your current user pool, create a new user pool.
+ Amazon Cognito must be able to update your mapped user pool attributes when users sign in to your application. When a user signs in through an IdP, Amazon Cognito updates the mapped attributes with the latest information from the IdP. Amazon Cognito only updates mapped attributes when their values change. To ensure that Amazon Cognito can update the attributes, check the following requirements:
  + All of the user pool custom attributes that you map from your IdP must be *mutable*. You can update mutable custom attributes at any time. By contrast, you can only set a value for a user's *immutable* custom attribute when you first create the user profile. To create a mutable custom attribute in the Amazon Cognito console, activate the **Mutable** checkbox for the attribute you add when you select **Add custom attributes** in the **Sign-up** menu. Or, if you create your user pool by using the [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) API operation, you can set the `Mutable` parameter for each of these attributes to `true`. If your IdP sends a value for a mapped immutable attribute, Amazon Cognito returns an error and sign-in fails.
  + In the app client settings for your application, the mapped attributes must be *writable*. You can set which attributes are writable in the **App clients** page in the Amazon Cognito console. Or, if you create the app client by using the [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) API operation, you can add these attributes to the `WriteAttributes` array. If your IdP sends a value for a mapped non-writable attribute, Amazon Cognito doesn't set the attribute value and proceeds with authentication.
+ When IdP attributes contain multiple values, Amazon Cognito flattens all values into a single comma-delimited string enclosed in the square-bracket characters `[` and `]`. Amazon Cognito URL form-encodes the values containing non-alphanumeric characters except for `.`, `-`, `*`, and `_`. You must decode and parse the individual values before you use them in your app.
+ The destination attribute retains any value that your attribute-mapping rules assign to it unless a sign-in or administrative action changes it. Amazon Cognito doesn't remove attributes from users when the source attribute is no longer sent in the provider token or SAML assertion. The following actions remove the value of an attribute from a user pool profile for a federated user:

  1. The IdP sends a blank value for the source attribute and a mapping rule applies the blank value to the destination attribute.

  1. You clear the value of the mapped attribute with an [DeleteUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserAttributes.html) or [AdminDeleteUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDeleteUserAttributes.html) request.

## Specifying identity provider attribute mappings for your user pool (AWS Management Console)
<a name="cognito-user-pools-specifying-attribute-mapping-console"></a>

You can use the AWS Management Console to specify attribute mappings for the IdP your user pool.

**Note**  
Amazon Cognito will map incoming claims to user pool attributes only if the claims exist in the incoming token. If a previously mapped claim no longer exists in the incoming token, it won't be deleted or changed. If your application requires mapping of deleted claims, you can use the Pre-Authentication Lambda trigger to delete the custom attribute during authentication and allow these attributes to repopulate from the incoming token.

**To specify a social IdP attribute mapping**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. In the navigation pane, choose **User Pools**, and choose the user pool you want to edit.

1. Choose the **Social and external providers** menu.

1. Choose **Add an identity provider**, or choose the **Facebook**, **Google**, **Amazon** or **Apple** IdP you have configured. Locate **Attribute mapping** and choose **Edit**. 

   For more information about adding a social IdP, see [Using social identity providers with a user pool](cognito-user-pools-social-idp.md).

1. For each attribute you need to map, complete the following steps:

   1. Select an attribute from the **User pool attribute** column. This is the attribute that is assigned to the user profile in your user pool. Custom attributes are listed after standard attributes.

   1. Select an attribute from the ***<provider>* attribute** column. This will be the attribute passed from the provider directory. Known attributes from the social provider are provided in a drop-down list.

   1. To map additional attributes between your IdP and Amazon Cognito, choose **Add another attribute**.

1. Choose **Save changes**.

**To specify a SAML provider attribute mapping**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. In the navigation pane, choose **User Pools**, and choose the user pool you want to edit.

1. Choose the **Social and external providers** menu.

1. Choose **Add an identity provider**, or choose the SAML IdP you have configured. Locate **Attribute mapping**, and choose **Edit**. For more information about adding a SAML IdP, see [Using SAML identity providers with a user pool](cognito-user-pools-saml-idp.md).

1. For each attribute you need to map, complete the following steps:

   1. Select an attribute from the **User pool attribute** column. This is the attribute that is assigned to the user profile in your user pool. Custom attributes are listed after standard attributes.

   1. Select an attribute from the **SAML attribute** column. This will be the attribute passed from the provider directory.

      Your IdP might offer sample SAML assertions for reference. Some IdPs use simple names, such as `email`, while others use URL-formatted attribute names similar to:

      ```
      http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
      ```

   1. To map additional attributes between your IdP and Amazon Cognito, choose **Add another attribute**.

1. Choose **Save changes**.

## Specifying identity provider attribute mappings for your user pool (AWS CLI and AWS API)
<a name="cognito-user-pools-specifying-attribute-mapping-cli-api"></a>

The following request body for [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html) or [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html) maps the SAML provider "MyIdP" attributes `emailaddress`, `birthdate`, and `phone` to the user pool attributes `email`, `birthdate`, and `phone_number`, in that order. This is a complete request body for a SAML 2.0 provider—your request body will vary depending on IdP type and specific details. The attribute mapping is in the `AttributeMapping` parameter.

```
{
   "AttributeMapping": { 
      "email" : "emailaddress",
      "birthdate" : "birthdate",
      "phone_number" : "phone"
   },
   "IdpIdentifiers": [ 
      "IdP1",
      "pdxsaml"
   ],
   "ProviderDetails": { 
      "IDPInit": "true", 
      "IDPSignout": "true", 
      "EncryptedResponses" : "true", 
      "MetadataURL": "https://auth.example.com/sso/saml/metadata", 
      "RequestSigningAlgorithm": "rsa-sha256"
   },
   "ProviderName": "MyIdP",
   "ProviderType": "SAML",
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

Use the following commands to specify IdP attribute mappings for your user pool.

**To specify attribute mappings at provider creation time**
+ AWS CLI: `aws cognito-idp create-identity-provider`

  Example with metadata file: `aws cognito-idp create-identity-provider --user-pool-id <user_pool_id> --provider-name=SAML_provider_1 --provider-type SAML --provider-details file:///details.json --attribute-mapping email=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`

  Where `details.json` contains:

  ```
  { 
      "MetadataFile": "<SAML metadata XML>"
  }
  ```
**Note**  
If the *<SAML metadata XML>* contains any quotations (`"`), they must be escaped (`\"`).

  Example with metadata URL:

  ```
  aws cognito-idp create-identity-provider \
  --user-pool-id us-east-1_EXAMPLE \
  --provider-name=SAML_provider_1 \
  --provider-type SAML \
  --provider-details MetadataURL=https://myidp.example.com/saml/metadata \
  --attribute-mapping email=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
  ```
+ API/SDK: [CreateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateIdentityProvider.html)

**To specify attribute mappings for an existing IdP**
+ AWS CLI: `aws cognito-idp update-identity-provider`

  Example: `aws cognito-idp update-identity-provider --user-pool-id <user_pool_id> --provider-name <provider_name> --attribute-mapping email=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`
+ API/SDK: [UpdateIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateIdentityProvider.html)

**To get information about attribute mapping for a specific IdP**
+ AWS CLI: `aws cognito-idp describe-identity-provider`

  Example: `aws cognito-idp describe-identity-provider --user-pool-id <user_pool_id> --provider-name <provider_name>`
+ API/SDK: [DescribeIdentityProvider](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeIdentityProvider.html)

# Linking federated users to an existing user profile
<a name="cognito-user-pools-identity-federation-consolidate-users"></a>

Often, the same user has a profile with multiple identity providers (IdPs) that you have connected to your user pool. Amazon Cognito can link each occurrence of a user to the same user profile in your directory. This way, one person who has multiple IdP users can have a consistent experience in your app. [AdminLinkProviderForUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminLinkProviderForUser.html) tells Amazon Cognito to recognize a user's unique ID in your federated directory as a user in the user pool. A user in your user pool counts as one monthly active user (MAU) for the purposes of [billing](https://aws.amazon.com/cognito/pricing/) when you have zero or more federated identities associated with the user profile.

When a federated user signs in to your user pool for the first time, Amazon Cognito looks for a local profile that you have linked to their identity. If no linked profile exists, your user pool creates a new profile. You can create a local profile and link it to your federated user at any time before their first sign-in, in an `AdminLinkProviderForUser` API request, either in a planned prestaging task or in a [Pre sign-up Lambda trigger](user-pool-lambda-pre-sign-up.md). After your user signs in and Amazon Cognito detects a linked local profile, your user pool reads your user's claims and compares them to mapping rules for the IdP. Your user pool then updates the linked local profile with the claims mapped from their sign-in. In this way, you can configure the local profile with access claims and keep their identity claims up-to-date with your provider. After Amazon Cognito matches your federated user to a linked profile, they always sign in to that profile. You can then link more of your user's provider identities to the same profile, giving one customer a consistent experience in your app. To link a federated user who has previously signed in, you must first delete their existing profile. You can identify existing profiles by their format: `[Provider name]_identifier`. For example, `LoginWithAmazon_amzn1.account.AFAEXAMPLE`. A user that you created and then linked to a third-party user identity has the username that they were created with, and an `identities` attribute that contains the details of their linked identities.

**Important**  
Because `AdminLinkProviderForUser` allows a user with an external federated identity to sign in as an existing user in the user pool, it is critical that it only be used with external IdPs and provider attributes that have been trusted by the application owner.

For example, if you're a managed service provider (MSP) with an app that you share with multiple customers. Each of the customers signs in to your app through Active Directory Federation Services (ADFS). Your IT administrator, Carlos, has an account in each of your customers' domains. You want Carlos to be recognized as an app administrator every time he signs in, regardless of the IdP.

Your ADFS IdPs present Carlos' email address `msp_carlos@example.com` in the `email` claim of the Carlos' SAML assertions to Amazon Cognito. You create a user in your user pool with the user name `Carlos`. The following AWS Command Line Interface (AWS CLI) commands link Carlos' identities from IdPs ADFS1, ADFS2, and ADFS3.

**Note**  
You can link a user based on specific attribute claims. This ability is unique to OIDC and SAML IdPs. For other provider types, you must link based on a fixed source attribute. For more information, see [AdminLinkProviderForUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminLinkProviderForUser.html). You must set `ProviderAttributeName` to `Cognito_Subject` when you link a social IdP to a user profile. `ProviderAttributeValue` must be the user's unique identifier with your IdP.

```
aws cognito-idp admin-link-provider-for-user \
--user-pool-id us-east-1_EXAMPLE \
--destination-user ProviderAttributeValue=Carlos,ProviderName=Cognito \
--source-user ProviderName=ADFS1,ProviderAttributeName=email,ProviderAttributeValue=msp_carlos@example.com

aws cognito-idp admin-link-provider-for-user \
--user-pool-id us-east-1_EXAMPLE \
--destination-user ProviderAttributeValue=Carlos,ProviderName=Cognito \
--source-user ProviderName=ADFS2,ProviderAttributeName=email,ProviderAttributeValue=msp_carlos@example.com

aws cognito-idp admin-link-provider-for-user \
--user-pool-id us-east-1_EXAMPLE \
--destination-user ProviderAttributeValue=Carlos,ProviderName=Cognito \
--source-user ProviderName=ADFS3,ProviderAttributeName=email,ProviderAttributeValue=msp_carlos@example.com
```

The user profile `Carlos` in your user pool now has the following `identities` attribute.

```
[{
    "userId": "msp_carlos@example.com",
    "providerName": "ADFS1",
    "providerType": "SAML",
    "issuer": "http://auth.example.com",
    "primary": false,
    "dateCreated": 111111111111111
}, {
    "userId": "msp_carlos@example.com",
    "providerName": "ADFS2",
    "providerType": "SAML",
    "issuer": "http://auth2.example.com",
    "primary": false,
    "dateCreated": 111111111111111
}, {
    "userId": "msp_carlos@example.com",
    "providerName": "ADFS3",
    "providerType": "SAML",
    "issuer": "http://auth3.example.com",
    "primary": false,
    "dateCreated": 111111111111111
}]
```

**Things to know about linking federated users**
+ You can link up to five federated users to each user profile.
+ You can link users to each IdP from up to five IdP attribute claims, as defined by the `ProviderAttributeName` parameter of `SourceUser` in an `AdminLinkProviderForUser` API request. For example, if you have linked at least one user to the source attributes `email`, `phone`, `department`, `given_name`, and `location`, you can only link additional users on one of those five attributes.
+ You can link federated users to either an existing federated user profile, or to a local user.
+ You can't link providers to user profiles in the AWS Management Console.
+ Your user's ID token contains all of their associated providers in the `identities` claim.
+ You can set a password for the automatically-created federated user profile in an [AdminSetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html) API request. That user's status then changes from `EXTERNAL_PROVIDER` to `CONFIRMED`. A user in this state can sign in as a federated user, and initiate authentication flows in the API like a linked local user. They can also modify their password and attributes in token-authenticated API requests like [ChangePassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ChangePassword.html) and [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html). As a best security practice and to keep users in sync with your external IdP, don't set passwords on federated user profiles. Instead, link users to local profiles with `AdminLinkProviderForUser`.
+ Amazon Cognito populates user attributes to a linked local user profile when the user signs in through their IdP. Amazon Cognito processes identity claims in the ID token from an OIDC IdP, and also checks the `userInfo` endpoint of both OAuth 2.0 and OIDC providers. Amazon Cognito prioritizes information in an ID token over information from `userInfo`.

When you learn that your user is no longer using an external user account that you've linked to their profile, you can disassociate that user account with your user pool user. When you linked your user, you supplied the user's attribute name, attribute value and provider name in the request. To remove a profile that your user no longer needs, make an [AdminDisableProviderForUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDisableProviderForUser.html) API request with equivalent parameters.

See [AdminLinkProviderForUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminLinkProviderForUser.html) for additional command syntax and examples in the AWS SDKs.

# User pool managed login
<a name="cognito-user-pools-managed-login"></a>

You can choose a web domain to host services for your user pool. An Amazon Cognito user pool gains the following functions when you add a domain, collectively referred to as *managed login*.
+ An [authorization server](https://datatracker.ietf.org/doc/html/rfc6749#section-1.1) that acts as an identity provider (IdP) to applications that work with OAuth 2.0 and OpenID Connect (OIDC). The authorization server [routes requests](authorization-endpoint.md), [issues and manages JSON web tokens (JWTs)](token-endpoint.md), and [delivers user attribute information](userinfo-endpoint.md).
+ A ready-to-use user interface (UI) for authentication operations like sign-in, sign-out and password management. The *managed login pages* act as a web front end for authentication services.
+ A service provider (SP), or relying party (RP), to SAML 2.0 IdPs, OIDC IdPs, Facebook, Login with Amazon, Sign in with Apple, and Google.

An additional option that shares some features with managed login is the classic *hosted UI*. The classic hosted UI is a first-generation version of the managed login services. Hosted UI IdP and RP services generally have the same characteristics as managed login, but the login pages have a simpler design and fewer features. For example, passkey sign-in isn't available in the classic hosted UI. In the Lite [feature plan](cognito-sign-in-feature-plans.md), the classic hosted UI is your only option for user pool domain services.

The managed login pages are a collection of web interfaces for basic sign-up, sign-in, multi-factor authentication and password-reset activities in your user pool. They also connect users to one or more third-party identity providers (IdPs) when you want to give users a choice of sign-in option. Your app can invoke your managed login pages in users' browsers when you want to authenticate and authorize users.

You can make the managed login user experience fit your brand with custom logos, backgrounds and styles. You have two options for the branding that you might apply to your managed login UI: the *branding editor* for managed login, and *hosted UI (classic) branding* for the hosted UI.

**Branding editor**  
An updated user experience with the most up-to-date authentication options and a visual editor in the Amazon Cognito console.

**Hosted UI branding**  
A familiar user experience for previous adopters of Amazon Cognito user pools. Branding for the hosted UI is a file-based system. To apply branding to hosted UI pages, you upload a logo image file and a file that sets values for several predetermined CSS style options.

The branding editor isn't available in all feature plans for user pools. For more information, see [User pool feature plans](cognito-sign-in-feature-plans.md).

For more information about constructing requests to managed login and hosted UI services, see [User pool endpoints and managed login reference](cognito-userpools-server-contract-reference.md).

**Note**  
Amazon Cognito managed login doesn't support custom authentication with [custom authentication challenge Lambda triggers](user-pool-lambda-challenge.md).

**Topics**
+ [

## Managed login localization
](#managed-login-localization)
+ [

## Terms documents
](#managed-login-terms-documents)
+ [

## Setting up managed login with AWS Amplify
](#cognito-user-pools-app-integration-amplify)
+ [

## Setting up managed login with the Amazon Cognito console
](#set-up-managed-login)
+ [

## Viewing your sign-in page
](#view-login-pages)
+ [

## Customizing your authentication pages
](#cognito-user-pools-app-integration-customize-hosted-ui)
+ [

## Things to know about managed login and the hosted UI
](#managed-login-things-to-know)
+ [

# Configuring a user pool domain
](cognito-user-pools-assign-domain.md)
+ [

# Apply branding to managed login pages
](managed-login-branding.md)

## Managed login localization
<a name="managed-login-localization"></a>

Managed login defaults to the English language in user-interactive pages. You can display your managed login pages localized for the language of your choice. The available languages are those available in the AWS Management Console. In the link that you distribute to users, add a `lang` query parameter, as shown in the following example.

```
https://<your domain>/oauth2/authorize?lang=es&response_type=code&client_id=<your app client id>&redirect_uri=<your relying-party url>
```

Amazon Cognito sets a cookie in users' browser with their language preference after the initial request with a `lang` parameter. After the cookie is set, the language selection persists without displaying or requiring you to include the parameter in requests. For example, after a user makes a sign-in request with a `lang=de` parameter, their managed login pages render in German until they clear their cookies or make a new request with a new localization parameter like `lang=en`.

Localization is only available for managed login. You must be on the Essentials or Plus [feature plan](cognito-sign-in-feature-plans.md) and have assigned your domain to use [managed login branding](managed-login-branding.md).

The selection that your user makes in managed login isn't available to [custom email or SMS sender triggers](user-pool-lambda-custom-sender-triggers.md). When you implement these triggers, you must use other mechanisms to determine a user's preferred language. In sign-in flows, the `locale` attribute might indicate the user's preferred language based on location. In sign-up flows, the region or app client ID of your user pool might indicate a language preference.

The following languages are available.


**Managed login languages**  

| Language | Code | 
| --- | --- | 
| German | de | 
| English | en | 
| Spanish | es | 
| French | fr | 
| Bahasa Indonesia | id | 
| Italian | it | 
| Japanese | ja | 
| Korean | ko | 
| Portuguese (Brazil) | pt-BR | 
| Chinese (Simplified) | zh-CN | 
| Chinese (Traditional) | zh-TW | 

## Terms documents
<a name="managed-login-terms-documents"></a>

You can configure your managed login pages to display links to your **Terms of use** and **Privacy policy** documents when users sign up. When you set up both terms documents in your app client, users see the following text during sign-up: **By signing up, you agree to our Terms of use and Privacy policy.** The phrases **Terms of use** and **Privacy policy** appear in your managed login page, hyperlinked to your documents.

Terms documents support language-specific URLs that align with managed login localization. When users select a language with the `lang` query parameter, Amazon Cognito displays links to your terms documents in that language. If you haven't configured a URL for a specific language, Amazon Cognito uses the default URL that you configured for the app client.

To configure terms documents for your app client, navigate to the **Managed login** menu in your user pool. Under **Terms documents**, choose **Create terms document**.

------
#### [ Amazon Cognito console ]

**To create a terms document**

1. Navigate to your user pool and choose the **Managed login** menu. Locate **Terms documents**.

1. Choose **Create terms document**.

1. Select the app client that you want to assign the terms document to.

1. Enter a **Terms name**. This identifies your document in the console.

1. Under **Links**, choose a **Language** and enter the **URL** where you host your terms document in that language.

1. To add URLs for additional languages, choose **Add another**.

1. Choose **Create**.

------
#### [ Amazon Cognito user pools API ]

The following is an example [CreateTerms](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateTerms.html) request body. It causes the sign-up page for app client `1example23456789` to render links for a french-language and a portuguese-language (Brazil) version of the privacy policy when managed login is localized to that language. A separate request is required to set URLs for `terms-of-use` before managed login will render links at the sign-up page.

```
{
   "ClientId": "1example23456789",
   "Enforcement": "NONE",
   "Links": { 
      "cognito:default" : "https://example.com/privacy/",
      "cognito:french" : "https://example.com/fr/privacy/",
      "cognito:portuguese-brazil" : "https://example.com/pt/privacy/"
   },
   "TermsName": "privacy-policy",
   "TermsSource": "LINK",
   "UserPoolId": "us-east-1_EXAMPLE"
}
```

------

**Note**  
You must create both a terms of use and a privacy policy document for your app client before Amazon Cognito will display terms documents in your managed login pages.

## Setting up managed login with AWS Amplify
<a name="cognito-user-pools-app-integration-amplify"></a>

If you use AWS Amplify to add authentication to your web or mobile app, you can set up your managed login pages in the Amplify command line interface (CLI) and libraries in the Amplify framework. To add authentication to your app, add the `Auth` category to your project. Then, in your application, authenticate user pool users with Amplify client libraries.

You can invoke managed login pages for authentication or you can federate users through an authorization endpoint that redirects to an IdP. After a user successfully authenticates with the provider, Amplify creates a new user in your user pool and passes the user's tokens to your app.

The following examples show how to use AWS Amplify to set up managed login with social providers in your app.
+ [React](https://docs.amplify.aws/react/build-a-backend/auth/concepts/external-identity-providers/)
+ [Swift](https://docs.amplify.aws/swift/build-a-backend/auth/concepts/external-identity-providers/)
+ [Flutter](https://docs.amplify.aws/flutter/build-a-backend/auth/concepts/external-identity-providers/)
+ [Android](https://docs.amplify.aws/android/build-a-backend/auth/concepts/external-identity-providers/)

## Setting up managed login with the Amazon Cognito console
<a name="set-up-managed-login"></a>

The first requirement for managed login and hosted UI is a user pool domain. In the user pools console, navigate to the **Domain** tab of your user pool and add a **Cognito domain** or a **custom domain**. You can also choose a domain during the process of creating a new user pool. For more information, see [Configuring a user pool domain](cognito-user-pools-assign-domain.md). When a domain is active in your user pool, all app clients serve public authentication pages on that domain.

When you create or modify a user pool domain, you set the **Branding version** for your domain. This branding version is a choice of **Managed login** or **Hosted UI (classic)**. Your choice of branding version applies to all app clients that use the sign-in services at your domain.

The next step is to create an [app client](user-pool-settings-client-apps.md) from the **App clients** tab of your user pool. In the process of creating an app client, Amazon Cognito will ask you for information about your application, then prompt you to select a **Return URL**. The return URL is also called the relying party (RP) URL, the redirect URI, and the callback URL. This is the URL that your application runs from, for example `https://www.example.com` or `myapp://example`.

After you configure a domain and app client with a branding style in your user pool, your managed login pages become available on the internet.

## Viewing your sign-in page
<a name="view-login-pages"></a>

In the Amazon Cognito console, choose the **View login pages** button in the **Login pages** tab for your app client under the **App clients** menu. This button takes you to a sign-in page in your user pool domain with the following basic parameters.
+ The app client id
+ An authorization code grant request
+ A request for all scopes that you have activated for the current app client
+ The first callback URL in the list for the current app client

The **View login page** button is useful when you want to test the basic functions of your managed login pages. Your login pages will match the **Branding version** that you assigned to your [user pool domain](cognito-user-pools-assign-domain.md). You can customize your sign-in URL with additional and modified parameters. In most cases, the automatically-generated parameters of the **View login page** link don’t fully match the needs of your app. In these cases, you must customize the URL that your app invokes when it signs in your users. For more information about sign-in parameter keys and values, see [User pool endpoints and managed login reference](cognito-userpools-server-contract-reference.md).

The sign-in webpage uses the following URL format. This example requests an authorization code grant with the `response_type=code` parameter.

```
https://<your domain>/oauth2/authorize?response_type=code&client_id=<your app client id>&redirect_uri=<your relying-party url>
```

You can look up your user pool domain string from the **Domain** menu in your user pool. In the **App clients** menu, you can identify app client IDs, their callback URLs, their allowed scopes, and other configuration.

When you navigate to the `/oauth2/authorize` endpoint with your custom parameters, Amazon Cognito either redirects you to the `/oauth2/login` endpoint or, if you have an `identity_provider` or `idp_identifier` parameter, silently redirects you to your IdP sign-in page.

**Example request for an implicit grant**  
You can view your sign-in webpage with the following URL for the implicit code grant where `response_type=token`. After a successful sign-in, Amazon Cognito returns user pool tokens to your web browser's address bar.

```
            https://mydomain.auth.us-east-1.amazoncognito.com/authorize?response_type=token&client_id=1example23456789&redirect_uri=https://mydomain.example.com
```

The identity and access tokens appear as parameters appended to your redirect URL.

The following is an example response from an implicit grant request.

```
            https://auth.example.com/#id_token=eyJraaBcDeF1234567890&access_token=eyJraGhIjKlM1112131415&expires_in=3600&token_type=Bearer  
```

## Customizing your authentication pages
<a name="cognito-user-pools-app-integration-customize-hosted-ui"></a>

In the past, Amazon Cognito only hosted login pages with the classic *hosted UI*, a simple design that grants a universal look to authentication webpages. You could customize Amazon Cognito user pools with a logo image and tweak some styles with a file that specified some CSS style values. Later, Amazon Cognito introduced *managed login*, an updated hosted authentication service. Managed login is an updated look-and-feel with the *branding editor*. The branding editor is a no-code visual editor and a larger suite of options than the hosted UI customization experience. Managed login also introduced custom background images and a dark mode theme.

You can switch between the managed login and hosted UI branding experiences in user pools. To learn more about customizing your managed login pages, see [Apply branding to managed login pages](managed-login-branding.md).

## Things to know about managed login and the hosted UI
<a name="managed-login-things-to-know"></a>

**The one-hour managed login and hosted UI session cookie**  
When a user signs in with your login pages or a third-party provider, Amazon Cognito sets a cookie in their browser. With this cookie, users can sign in again with the same authentication method for one hour. When they sign in with their browser cookie, they get fresh tokens that last the duration specified in your app client configuration. Changes to user attributes or authentication factors have no effect on their ability to sign in again with their browser cookie.

Authentication with the session cookie doesn't reset the cookie duration to an additional hour. Users must sign in again if they attempt to access your sign-in pages more than an hour after their most recent successful interactive authentication.

**Confirming user accounts and verifying user attributes**  
For user pool [local users](cognito-terms.md#terms-localuser), managed login and the hosted UI work best when you configure your user pool to **Allow Cognito to automatically send messages to verify and confirm**. When you enable this setting, Amazon Cognito sends a message with a confirmation code to users who sign up. When you instead confirm users as a user pool administrator, your login pages display an error message after sign-up. In this state, Amazon Cognito has created the new user, but hasn't been able to send a verification message. You can still confirm users as an administrator, but they might contact your support desk after they encounter an error. For more information about administrative confirmation, see [Allowing users to sign up in your app but confirming them as a user pool administrator](signing-up-users-in-your-app.md#signing-up-users-in-your-app-and-confirming-them-as-admin).

**Managed login scope of operations**  
Managed login and the classic hosted UI support sign-up, sign-in, and password management. This includes completing sign-in with multi-factor authentication (MFA) and registration of webAuthn authenticators. Managed login doesn't support user self-service profile management like attribute changes and setting of MFA preference. You must implement profile management in your own application code. Managed login also doesn't provide the capacity to confirm attribute changes when you update email addresses and phone numbers as an administrator with the [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) API operation.

**Viewing your changes to configuration**  
If you make style changes to your pages and they do not immediately appear, wait a few minutes and then refresh the page.

**Decoding user pool tokens**  
Amazon Cognito user pool tokens are signed using an RS256 algorithm. You can decode and verify user pool tokens using AWS Lambda. See [Decode and verify Amazon Cognito JWT tokens](https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt) on GitHub.

**TLS version**  
Managed login and hosted UI pages require encryption in transit. User pool domains that are provided by Amazon Cognito require that users' browsers negotiate a minimum TLS version of 1.2. Custom domains support browser connections with TLS version 1.2. The hosted UI (classic) **doesn't require** TLS 1.2 for custom domains, but the newer managed login **requires** TLS version 1.2 both for custom and prefix domains. Because Amazon Cognito manages the configuration of your domain services, you can't modify the TLS requirements of your user pool domain.

**CORS policies**  
Neither managed login nor the hosted UI support custom cross-origin resource sharing (CORS) origin policies. A CORS policy would prevent users from passing authentication parameters in their requests. Instead, implement a CORS policy in your application front end. Amazon Cognito returns an `Access-Control-Allow-Origin: *` response header to requests to the following endpoints.

1. [Token endpoint](token-endpoint.md)

1. [Revoke endpoint](revocation-endpoint.md)

1. [userInfo endpoint](userinfo-endpoint.md)

**Cookies**  
Managed login and the hosted UI set cookies in users' browsers. The cookies conform to the requirements of some browsers that sites not set third-party cookies. They are scoped only to your user pool endpoints and include the following:
+ An `XSRF-TOKEN` cookie for each request.
+ A `csrf-state` cookie for session consistency when a user is redirected.
+ A `csrf-state-legacy` cookie for session consistency, read by Amazon Cognito as a fallback when your browser doesn't have support for the `SameSite` attribute.
+ A `cognito` session cookie that preserves successful sign-in attempts for an hour.
+ A `lang` cookie that preserves a user's choice of [language localization](#managed-login-localization) in managed login.
+ A `page-data` cookie that persists required data as a user navigates between managed login pages.

In iOS, you can [block all cookies](https://support.apple.com/en-us/105082). This setting isn't compatible with managed login or the hosted UI. To work with users who might enable this setting, build user pool authentication into a native iOS app with an AWS SDK. In this scenario, you can build your own session storage that isn't cookie-based.

**Effects of managed login version change**  
Consider the following effects of adding domains and setting the managed login version.
+ When you add a prefix domain, either with managed login or hosted UI (classic) branding, it can take up to 60 seconds before your login pages are available.
+ When you add a custom domain, either with managed login or hosted UI (classic) branding, it can take up to five minutes before your login pages are available.
+ When you change the branding version for your domain, it can take up to four minutes before your login pages are available in the new branding version.
+ When you switch between managed login and hosted UI (classic) branding, Amazon Cognito doesn't maintain user sessions. They must sign in again with the new interface.

**Default style**  
When you create an app client in the AWS Management Console, Amazon Cognito automatically assigns a branding style to your app client. When you programmatically create an app client with the [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) operation, no branding style is created. Managed login isn't available for an app client created with an AWS SDK until you create one with a [CreateManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateManagedLoginBranding.html) request.

**Managed login authentication prompt times out**  
Amazon Cognito cancels authentication requests that do not complete within five minutes, and redirects the user to managed login. The page displays a `Something went wrong` error message.

# Configuring a user pool domain
<a name="cognito-user-pools-assign-domain"></a>

Configuring a domain is an optional part of setting up a user pool. A user pool domain hosts features for user authentication, federation with third-party providers, and OpenID Connect (OIDC) flows. It has *managed login*, a prebuilt interface for key operations like signing up, signing in, and password recovery. It also hosts the standard OpenID Connect (OIDC) endpoints like [authorize](authorization-endpoint.md), [userInfo](userinfo-endpoint.md), and [token](token-endpoint.md), for machine-to-machine (M2M) authorization and other OIDC and OAuth 2.0 authentication and authorization flows.

Users authenticate with managed login pages at the domain associated with your user pool. You have two options for configuring this domain: you can either use the default Amazon Cognito hosted domain, or you can configure a custom domain that you own.

The custom domain option has more options for flexibility, security and control. For example, a familiar, organization-owned domain can encourage user trust and make the sign-in process more intuitive. However, the custom domain approach requires some additional overhead, like managing the SSL certificate and DNS configuration.

The OIDC discovery endpoints, `/.well-known/openid-configuration` for endpoint URLs and `/.well-known/jwks.json` for token signing keys, aren't hosted on your domain. For more information, see [Identity provider and relying party endpoints](federation-endpoints.md).

Understanding how to configure and manage the domain for your user pool is an important step in integrating authentication into your application. Sign-in with the user pools API and an AWS SDK can be an alternative to configuring a domain. The API-based model delivers tokens directly in an API response, but for implementations that use the extended capabilities of user pools as an OIDC IdP, you must configure a domain. For more information about the authentication models that are available in user pools, see [Understanding API, OIDC, and managed login pages authentication](authentication-flows-public-server-side.md#user-pools-API-operations).

**Topics**
+ [

## Things to know about user pool domains
](#cognito-user-pools-assign-domain-things-to-know)
+ [

# Using the Amazon Cognito prefix domain for managed login
](cognito-user-pools-assign-domain-prefix.md)
+ [

# Using your own domain for managed login
](cognito-user-pools-add-custom-domain.md)

## Things to know about user pool domains
<a name="cognito-user-pools-assign-domain-things-to-know"></a>

User pool domains are a point of service for OIDC relying parties in your applications and for UI elements. Consider the following details when you're planning your implementation of a domain for your user pool.

**Reserved terms**  
You can't use the text `aws`, `amazon`, or `cognito` in the name of an Amazon Cognito prefix domain.

**Discovery endpoints are on a different domain**  
The user pool [discovery endpoints](federation-endpoints.md) `.well-known/openid-configuration` and `.well-known/jwks.json` aren't on your user pool custom or prefix domain. The path to these endpoints is as follows.
+ `https://cognito-idp.Region.amazonaws.com/your user pool ID/.well-known/openid-configuration`
+ `https://cognito-idp.Region.amazonaws.com/your user pool ID/.well-known/jwks.json`

**Effective time of domain changes**  
It can take Amazon Cognito up to a minute to launch or update the branding version of a prefix domain. Changes to a custom domain can take up to five minutes to propagate. New custom domains can take up to one hour to propagate.

**Custom and prefix domains at the same time**  
You can set up a user pool with both a custom domain and a prefix domain that's owned by AWS. Because the user pool [discovery endpoints](federation-endpoints.md) are hosted at a different domain, they only serve the *custom domain*. For example, your `openid-configuration` will provide a single value for `"authorization_endpoint"` of `"https://auth.example.com/oauth2/authorize"`.

When you have both custom and prefix domains in a user pool, you can use the custom domain with the full features of an OIDC provider. The prefix domain in a user pool with this configuration doesn't have discovery or token-signing-key endpoints and should be used accordingly.

**Custom domains preferred as relying party ID for passkey**  
When you set up user pool authentication with [passkeys](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passkey), you must set a relying party (RP) ID. When you have a custom domain and a prefix domain, you can set the RP ID only as your custom domain. To set a prefix domain as the RP ID in the Amazon Cognito console, delete your custom domain or enter the fully-qualified domain name (FQDN) of the prefix domain as a **Third-party domain**.

**Don't use custom domains at different levels of your domain hierarchy**  
You can configure separate user pools to have custom domains in the same top-level domain (TLD), for example *auth.example.com* and *auth2.example.com*. The managed login session cookie is valid for a custom domain and all subdomains, for example *\$1.auth.example.com*. Because of this, no user of your applications should access managed login for any parent domain *and* subdomain. Where custom domains use the same TLD, keep them at the same subdomain level.

Say you have a user pool with the custom domain *auth.example.com*. Then you create another user pool and assign the custom domain *uk.auth.example.com.*. A user signs in with *auth.example.com.* and gets a cookie that their browser presents to any website in the wildcard path *\$1.auth.example.com*. They then try to sign in to *uk.auth.example.com.*. They pass an invalid cookie to your user pool domain and receive an error instead of a sign-in prompt. By contrast, a user with a cookie for *\$1.auth.example.com* has no issues starting a sign-in session at *auth2.example.com*.

**Branding version**  
When you create a domain, you set a **Branding version**. Your options are the newer managed-login experience and the classic hosted UI experience. This choice applies to all app clients that host services at your domain.

# Using the Amazon Cognito prefix domain for managed login
<a name="cognito-user-pools-assign-domain-prefix"></a>

The default experience for managed login is hosted on a domain that AWS owns. This approach has a low barrier to entry—choose a prefix name and it's active—but doesn't have the trust-inspiring features of a custom domain. There isn't a cost difference between the Amazon Cognito domain option and the custom domain option. The only difference is the domain in the web address that you direct your users to. For cases of third-party IdP redirects and client-credentials flows, the hosted domain has little visible effect. A custom domain is better for cases where your users sign in with managed login and would interact with a authentication domain that doesn't match the application domain.

The hosted Amazon Cognito domain has a prefix of your choosing, but is hosted at the root domain `amazoncognito.com`. The following is an example:

```
https://cognitoexample.auth.ap-south-1.amazoncognito.com
```

All prefix domains follow this format: `prefix`.`auth`.*`AWS Region code`*.`amazoncognito`.`com`. [Custom domain](cognito-user-pools-add-custom-domain.md) user pools can host the managed login or hosted UI pages on any domain that you own.

**Note**  
To augment the security of your Amazon Cognito applications, the parent domains of user pool endpoints are registered in the [Public Suffix List (PSL)](https://publicsuffix.org/). The PSL helps your users' web browsers establish a consistent understanding of your user pool endpoints and the cookies they set.  
User pool parent domains take the following formats.  

```
auth.Region.amazoncognito.com
auth-fips.Region.amazoncognito.com
```

To add an app client and a user pool domain with the AWS Management Console, see [Creating an app client](user-pool-settings-client-apps.md#cognito-user-pools-app-idp-settings-console-create).

**Topics**
+ [

## Prerequisites
](#cognito-user-pools-assign-domain-prefix-prereq)
+ [

## Configure an Amazon Cognito domain prefix
](#cognito-user-pools-assign-domain-prefix-step-1)
+ [

## Verify your sign-in page
](#cognito-user-pools-assign-domain-prefix-verify)

## Prerequisites
<a name="cognito-user-pools-assign-domain-prefix-prereq"></a>

Before you begin, you need:
+ A user pool with an app client. For more information, see [Getting started with user pools](getting-started-user-pools.md).

## Configure an Amazon Cognito domain prefix
<a name="cognito-user-pools-assign-domain-prefix-step-1"></a>

You can use either the AWS Management Console or the AWS CLI or API to configure a user pool domain.

------
#### [ Amazon Cognito console ]

**Configure a domain**

1. Navigate to the **Domain** menu under **Branding**.

1. Next to **Domain**, choose **Actions** and select **Create Cognito domain**. If you have already configured a user pool prefix domain, choose **Delete Cognito domain** before creating your new custom domain.

1. Enter an available domain prefix to use with a **Amazon Cognito domain**. For information on setting up a **Custom domain**, see [Using your own domain for managed login](cognito-user-pools-add-custom-domain.md).

1. Choose a **Branding version**. Your branding version applies to all user-interactive pages at that domain. Your user pool can host either managed login or hosted UI branding for all app clients.
**Note**  
You can have a custom domain and a prefix domain, but Amazon Cognito only serves the `/.well-known/openid-configuration` endpoint for the *custom* domain.

1. Choose **Create**.

------
#### [ CLI/API ]

Use the following commands to create a domain prefix and assign it to your user pool.

**To configure a user pool domain**
+ AWS CLI: `aws cognito-idp create-user-pool-domain`

  **Example:** `aws cognito-idp create-user-pool-domain --user-pool-id <user_pool_id> --domain <domain_name> --managed-login-version 2`
+ User pools API operation: [CreateUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolDomain.html)

**To get information about a domain**
+ AWS CLI: `aws cognito-idp describe-user-pool-domain`

  **Example:** `aws cognito-idp describe-user-pool-domain --domain <domain_name>`
+ User pools API operation: [DescribeUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolDomain.html)

**To delete a domain**
+ AWS CLI: `aws cognito-idp delete-user-pool-domain`

  **Example:** `aws cognito-idp delete-user-pool-domain --domain <domain_name>`
+ User pools API operation: [DeleteUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPoolDomain.html)

------

## Verify your sign-in page
<a name="cognito-user-pools-assign-domain-prefix-verify"></a>
+ Verify that the sign-in page is available from your Amazon Cognito hosted domain.

  ```
  https://<your_domain>/login?response_type=code&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>
  ```

Your domain is shown on the **Domain name** page of the Amazon Cognito console. Your app client ID and callback URL are shown on the **App client settings** page.

# Using your own domain for managed login
<a name="cognito-user-pools-add-custom-domain"></a>

After you set up an app client, you can configure your user pool with a custom domain for the domain services of [managed login](cognito-user-pools-managed-login.md). With a custom domain, users can sign in to your application using your own web address instead the default `amazoncognito.com` [prefix domain](cognito-user-pools-assign-domain-prefix.md). Custom domains improve user trust in your application with a familiar domain name, especially when the root domain matches the domain that hosts your application. Custom domains can improve compliance with organizational security requirements.

A custom domain has some prerequisites, including a user pool, an app client, and a web domain that you own. Custom domains also require an SSL certificate for the custom domain, managed with AWS Certificate Manager (ACM) in US East (N. Virginia). Amazon Cognito creates a Amazon CloudFront distribution, secured in transit with your ACM certificate. Because you own the domain, you must create a DNS record that directs traffic to the CloudFront distribution for your custom domain.

After these elements are ready, you can add the custom domain to your user pool through the Amazon Cognito console or API. This involves specifying the domain name and SSL certificate, and then updating your DNS configuration with the provided alias target. After making these changes, you can verify that the sign-in page is accessible at your custom domain.

The lowest-effort way to create a custom domain is with a public hosted zone in Amazon Route 53. The Amazon Cognito console can create the right DNS records in a few steps. Before you begin, consider [creating a Route 53 hosted zone](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingHostedZone.html) for a domain or subdomain that you own.

**Topics**
+ [

## Adding a custom domain to a user pool
](#cognito-user-pools-add-custom-domain-adding)
+ [

## Prerequisites
](#cognito-user-pools-add-custom-domain-prereq)
+ [

## Step 1: Enter your custom domain name
](#cognito-user-pools-add-custom-domain-console-step-1)
+ [

## Step 2: Add an alias target and subdomain
](#cognito-user-pools-add-custom-domain-console-step-2)
+ [

## Step 3: Verify your sign-in page
](#cognito-user-pools-add-custom-domain-console-step-3)
+ [

## Changing the SSL certificate for your custom domain
](#cognito-user-pools-add-custom-domain-changing-certificate)

## Adding a custom domain to a user pool
<a name="cognito-user-pools-add-custom-domain-adding"></a>

To add a custom domain to your user pool, you specify the domain name in the Amazon Cognito console, and you provide a certificate you manage with [AWS Certificate Manager](https://docs.aws.amazon.com/acm/latest/userguide/) (ACM). After you add your domain, Amazon Cognito provides an alias target, which you add to your DNS configuration.

## Prerequisites
<a name="cognito-user-pools-add-custom-domain-prereq"></a>

Before you begin, you need:
+ A user pool with an app client. For more information, see [Getting started with user pools](getting-started-user-pools.md).
+ A web domain that you own. Its *parent domain* must have a valid DNS **A record**. You can assign any value to this record. The parent may be the root of the domain, or a child domain that is one step up in the domain hierarchy. For example, if your custom domain is *auth.xyz.example.com*, Amazon Cognito must be able to resolve *xyz.example.com* to an IP address. To prevent accidental impact on customer infrastructure, Amazon Cognito doesn't support the use of top-level domains (TLDs) for custom domains. For more information see [Domain Names](https://tools.ietf.org/html/rfc1035).
+ The ability to create a subdomain for your custom domain. We recommend **auth** for your subdomain name. For example: *auth.example.com*.
**Note**  
You might need to obtain a new certificate for your custom domain's subdomain if you don't have a [wildcard certificate](https://en.wikipedia.org/wiki/Wildcard_certificate).
+ A public SSL/TLS certificate managed by ACM in US East (N. Virginia). The certificate must be in us-east-1 because the certificate will be associated with a distribution in CloudFront, a global service.
+ Browser clients that support Server Name Indication (SNI). The CloudFront distribution that Amazon Cognito assigns to custom domains requires SNI. You can't change this setting. For more information about SNI in CloudFront distributions, see [Use SNI to serve HTTPS requests](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cnames-https-dedicated-ip-or-sni.html#cnames-https-sni) in the *Amazon CloudFront Developer Guide*.
+ An application that permits your user pool authorization server to add cookies to user sessions. Amazon Cognito sets several required cookies for managed login pages. These include `cognito`, `cognito-fl`, and `XSRF-TOKEN`. Although each individual cookie conforms to browser size limits, changes to your user pool configuration might cause managed login cookies to grow in size. An intermediate service like an Application Load Balancer (ALB) in front of your custom domain might enforce a maximum header size or total cookie size. If your application also sets its own cookies, your users' sessions might exceed these limits. We recommend that, to avoid size limit conflicts, your application not set cookies on the subdomain that hosts your user pool domain services.
+ Permission to update Amazon CloudFront distributions. You can do so by attaching the following IAM policy statement to a user in your AWS account:

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
           {
              "Sid": "AllowCloudFrontUpdateDistribution",
              "Effect": "Allow",
              "Action": [
                  "cloudfront:updateDistribution"
              ],
              "Resource": [
                  "*"
              ]
          }
      ]
  }
  ```

------

  For more information about authorizing actions in CloudFront, see [Using Identity-Based Policies (IAM Policies) for CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/access-control-managing-permissions.html).

  Amazon Cognito initially uses your IAM permissions to configure the CloudFront distribution, but the distribution is managed by AWS. You can't change the configuration of the CloudFront distribution that Amazon Cognito associated with your user pool. For example, you can't update the supported TLS versions in the security policy.

## Step 1: Enter your custom domain name
<a name="cognito-user-pools-add-custom-domain-console-step-1"></a>

You can add your domain to your user pool by using the Amazon Cognito console or API.

------
#### [ Amazon Cognito console ]

**To add your domain to your user pool from the Amazon Cognito console:**

1. Navigate to the **Domain** menu under **Branding**.

1. Next to **Domain**, choose **Actions** and select **Create custom domain** or **Create Amazon Cognito domain**. If you have already configured a user pool custom domain, choose **Delete custom domain** before creating your new custom domain.

1. Next to **Domain**, choose **Actions** and select **Create custom domain**. If you have already configured a custom domain, choose **Delete custom domain** to delete the existing domain before creating your new custom domain.

1. For **Custom domain**, enter the URL of the domain you want to use with Amazon Cognito. Your domain name can include only lowercase letters, numbers, and hyphens. Do not use a hyphen for the first or last character. Use periods to separate subdomain names.

1. For **ACM certificate**, choose the SSL certificate that you want to use for your domain. Only ACM certificates in US East (N. Virginia) are eligible to use with an Amazon Cognito custom domain, regardless of the AWS Region of your user pool.

   If you don't have an available certificate, you can use ACM to provision one in US East (N. Virginia). For more information, see [Getting Started](https://docs.aws.amazon.com/acm/latest/userguide/gs.html) in the *AWS Certificate Manager User Guide*.

1. Choose a **Branding version**. Your branding version applies to all user-interactive pages at that domain. Your user pool can host either managed login or hosted UI branding for all app clients.
**Note**  
You can have a custom domain and a prefix domain, but Amazon Cognito only serves the `/.well-known/openid-configuration` endpoint for the *custom* domain.

1. Choose **Create**.

1. Amazon Cognito returns you to the **Domain** menu. A message titled **Create an alias record in your domain's DNS** is displayed. Note down the **Domain** and **Alias target** displayed in the console. They will be used in the next step to direct traffic to your custom domain.

------
#### [ API ]

The following [CreateUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolDomain.html) request body creates a custom domain.

```
{
   "Domain": "auth.example.com",
   "UserPoolId": "us-east-1_EXAMPLE",
   "ManagedLoginVersion": 2,
   "CustomDomainConfig": {
    "CertificateArn": "arn:aws:acm:us-east-1:111122223333:certificate/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
   }
}
```

------

## Step 2: Add an alias target and subdomain
<a name="cognito-user-pools-add-custom-domain-console-step-2"></a>

In this step, you set up an alias through your Domain Name Server (DNS) service provider that points back to the alias target from the previous step. If you are using Amazon Route 53 for DNS address resolution, choose the section **To add an alias target and subdomain using Route 53.**

### To add an alias target and subdomain to your current DNS configuration
<a name="cognito-user-pools-add-custom-domain-console-step-2a"></a>
+ If you aren't using Route 53 for DNS address resolution, then you must use your DNS service provider's configuration tools to add the alias target from the previous step to your domain's DNS record. Your DNS provider will also need to set up the subdomain for your custom domain.

### To add an alias target and subdomain using Route 53
<a name="cognito-user-pools-add-custom-domain-console-step-2b"></a>

1. Sign in to the [Route 53 console](https://console.aws.amazon.com/route53/). If prompted, enter your AWS credentials.

1. If you don't have a public hosted zone in Route 53, create one with a root that is a parent of your custom domain. For more information, see [Creating a public hosted zone](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingHostedZone.html) in the *Amazon Route 53 Developer Guide*.

   1. Choose **Create Hosted Zone**.

   1. Enter the parent domain, for example *auth.example.com*, of your custom domain, for example *myapp.auth.example.com*, from the **Domain Name** list.

   1. Enter a **Description** for your hosted zone.

   1. Choose a hosted zone **Type** of **Public hosted zone** to allow public clients to resolve your custom domain. Choosing **Private hosted zone** is not supported.

   1. Apply **Tags** as desired.

   1. Choose **Create hosted zone**.
**Note**  
You can also create a new hosted zone for your custom domain with a delegation set in the parent hosted zone that directs queries to the subdomain hosted zone. Otherwise, create an A record. This method offers more flexibility and security with your hosted zones.For more information, see [Creating a subdomain for a domain hosted through Amazon Route 53](https://aws.amazon.com/premiumsupport/knowledge-center/create-subdomain-route-53/).

1. On the **Hosted Zones** page, choose the name of your hosted zone.

1. Add a DNS record for the parent domain of your custom domain, if you don’t already have one. Create a DNS record for the parent domain with the following properties:
   + **Record name**: Leave blank.
   + **Record type**: `A`.
   + **Alias**: Don't enable.
   + **Value**: Enter a target of your choosing. This record must resolve to *something*, but the value of the record doesn't matter to Amazon Cognito.
   + **TTL**: Set to your preferred TTL or leave as default.
   + **Routing policy**: Choose **Simple routing**.

1. Choose **Create records**. The following is an example record for the domain *example.com*:

   `example.com. 60 IN A 198.51.100.1`
**Note**  
Amazon Cognito verifies that there is a DNS record for the parent domain of your custom domain to protect against accidental hijacking of production domains. If you do not have a DNS record for the parent domain, Amazon Cognito will return an error when you attempt to set the custom domain. A Start of Authority (SOA) record isn't a sufficient DNS record for the purposes of parent-domain verification.

1. Add another DNS record for your custom domain with the following properties:
   + **Record name**: Your custom domain prefix, for example `auth` to create a record for `auth.example.com`.
   + **Record type**: `A`.
   + **Alias**: Enable.
   + **Route traffic to**: Choose **Alias to Cloudfront distribution**. Enter the **Alias target** you recorded earlier, for example `123example.cloudfront.net`.
   + **Routing policy**: Choose **Simple routing**.

1. Choose **Create records**.
**Note**  
Your new records can take around 60 seconds to propagate to all Route 53 DNS servers. You can use the Route 53 [GetChange](https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetChange.html) API method to verify that your changes have propagated. 

## Step 3: Verify your sign-in page
<a name="cognito-user-pools-add-custom-domain-console-step-3"></a>
+ Verify that the sign-in page is available from your custom domain.

  Sign in with your custom domain and subdomain by entering this address into your browser. This is an example URL of a custom domain *example.com* with the subdomain *auth*:

  ```
  https://myapp.auth.example.com/login?response_type=code&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>
  ```

## Changing the SSL certificate for your custom domain
<a name="cognito-user-pools-add-custom-domain-changing-certificate"></a>

When necessary, you can use Amazon Cognito to change the certificate that you applied to your custom domain.

Usually, this is unnecessary following routine certificate renewal with ACM. When you renew your existing certificate in ACM, the ARN for your certificate remains the same, and your custom domain uses the new certificate automatically.

However, if you replace your existing certificate with a new one, ACM gives the new certificate a new ARN. To apply the new certificate to your custom domain, you must provide this ARN to Amazon Cognito.

After you provide your new certificate, Amazon Cognito requires up to 1 hour to distribute it to your custom domain.

**Before you begin**  
Before you can change your certificate in Amazon Cognito, you must add your certificate to ACM. For more information, see [Getting Started](https://docs.aws.amazon.com/acm/latest/userguide/gs.html) in the *AWS Certificate Manager User Guide*.  
When you add your certificate to ACM, you must choose US East (N. Virginia) as the AWS Region.

You can change your certificate by using the Amazon Cognito console or API.

------
#### [ AWS Management Console ]

**To renew a certificate from the Amazon Cognito console:**

1. Sign in to the AWS Management Console and open the Amazon Cognito console at [https://console.aws.amazon.com/cognito/home](https://console.aws.amazon.com/cognito/home).

1. Choose **User Pools**.

1. Choose the user pool for which you want to update the certificate.

1. Choose the **Domain** menu.

1. Choose **Actions**, **Edit ACM certificate**.

1. Select the new certificate you want to associate with your custom domain.

1. Choose **Save changes**.

------
#### [ API ]

**To renew a certificate (Amazon Cognito API)**
+ Use the [UpdateUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolDomain.html) action.

------

# Apply branding to managed login pages
<a name="managed-login-branding"></a>

You might want to provide a consistent user experience between your authentication service and your application. You can accomplish this goal either with custom forms and back-end API operations in an AWS SDK, or with managed login. Managed login and the classic hosted UI are web front ends for the component of your application that serves authentication with user pools. To synchronize your managed authentication services with your application UX, you have two customization options: the branding editor and hosted UI branding. You can choose your preferred experience in the Amazon Cognito console and with user pool API operations.

**The branding editor**  
The [branding editor](managed-login-brandingeditor.md) is the newest customization option for the newest user pools UI experience, [managed login](cognito-user-pools-managed-login.md). The branding editor is a no-code visual editor for managed login assets and style, and a set of API operations for programmatic configuration of a large number of configuration options. User pools that you configure with a [domain](cognito-user-pools-assign-domain.md) and managed login automatically render the branding-designer version of your login pages.

**Hosted UI (classic) branding**  
The [hosted UI (classic) branding experience](hosted-ui-classic-branding.md) has two options: to modify a cascading stylesheets (CSS) file with a fixed set of style options, and to add a custom logo image. You can set these options in the Amazon Cognito console or with the [SetUICustomization](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUICustomization.html) API operation. At the time that the service launched, Amazon Cognito had only this option. User pools that you configure with a [domain](cognito-user-pools-assign-domain.md) and the hosted UI branding version automatically render the classic version of your login pages. Your [feature plan](cognito-sign-in-feature-plans.md) might also support only the hosted UI.

**Note**  
The branding editor and the classic branding experience modify the visual properties of your hosted authentication service. Currently, you can't modify the text that's displayed on your managed login pages, except to apply localization into one of several languages. For more information about localization, see [Managed login localization](cognito-user-pools-managed-login.md#managed-login-localization).

## Choose a branding experience and assign styles
<a name="managed-login-branding-choose"></a>

In the Amazon Cognito console, new user pools default to the **Managed login** branding experience. User pools that you set up before managed login was available will have **Hosted UI (classic)** branding. You can switch between managed login and hosted UI branding. When you change your **Branding version**, Amazon Cognito immediately applies the change to the user-interactive pages of your user pool domain. With managed login and the hosted UI, your user pool can have a style for each app client.

Each app client can have a distinct branding *style*, but a user pool domain serves either managed login or the hosted UI. A style is the set of customization settings applied to an app client. You can set up one [custom domain](cognito-user-pools-add-custom-domain.md) and one [prefix domain](cognito-user-pools-assign-domain-prefix.md) per user pool. You can assign different branding versions to your custom and prefix domains. However, a prefix domain isn't fully functional when you also have a custom domain—the `.well-known` OIDC discovery endpoints *only* present custom-domain paths. You can only use the prefix domain for operations that don't require endpoint discovery (`openid-configuration`) in a user pool with this configuration. Because of these properties of user pools, you can effectively choose one branding version per user pool.

You can assign styles to the app clients in a user pool where a domain is set to the managed login branding version. Styles are a set of visual settings made up of image files, display options, CSS values. When you assign a style to an app client, Amazon Cognito immediately pushes your updates to your user-interactive login pages. Amazon Cognito renders your user-interactive pages with your chosen branding version and the customization that you have applied to it.

### Update and delete styles
<a name="managed-login-branding-update"></a>

When you create a style, you link it to an app client. To change a style assignment for an app client, you must first delete the original style. Currently, you can't copy settings between styles. You must do this programmatically. To replicate settings between styles and app clients, get the settings for a style with the [DescribeManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeManagedLoginBranding.html) API operation and apply them with [CreateManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateManagedLoginBranding.html) or [UpdateManagedLoginBranding](https://docs.aws.amazon.com/). You can't change the assigned styles of an app client—you can only delete the original and set a new one. For more information about managing styles with API and SDK operations, see [API and SDK operations for managed login branding](managed-login-brandingeditor.md#branding-designer-api).

**Note**  
Programmatic requests that create or update branding style must have a request size of no more than 2 MB. If your request is larger than this limit, break your request up into multiple `UpdateManagedLoginBranding` requests for groups of parameters that don't exceed the maximum request size. These requests don't result in unspecified parameters being set to default, so you can send partial requests without any effect on existing settings.

You delete a style in the Amazon Cognito console from the **Managed login** menu. Under **Styles**, choose the style that you want to delete and choose **Delete style**.

At a high level, the process of assigning branding to a domain consists of the following steps.

1. [Create a domain and set the branding version](cognito-user-pools-assign-domain.md).

1. Create a branding style and assign it to an app client.

**To assign a style to an app client**

1. In the **Domain** menu of your user pool, create a domain and set the **Branding version** to **Managed login**.

1. Navigate to the **Managed login** menu. Under **Styles**, choose **Create a style**.

1. Choose the app client that you want to assign your style to, or create a new [app client](user-pool-settings-client-apps.md).

1. To start configuring your branding settings, choose **Launch branding editor**.

**Topics**
+ [

## Choose a branding experience and assign styles
](#managed-login-branding-choose)
+ [

# The branding editor and customizing managed login
](managed-login-brandingeditor.md)
+ [

# Customizing hosted UI (classic) branding
](hosted-ui-classic-branding.md)

# The branding editor and customizing managed login
<a name="managed-login-brandingeditor"></a>

The branding editor is a visual design and editing tool for your managed login webpages. It's built in to the Amazon Cognito console. In the branding editor, you start with a preview of your login pages and can proceed into a quick-setup option or a detailed view with advanced options. You can modify and preview style parameters or add a custom background image and logo. You can configure light mode and dark mode.

![\[A preview of the branding editor visual editor for Amazon Cognito user pools.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/hosted-ui-customization-editor-preview.png)


To begin, create a style that you can apply to your user pool or an app client.

**To get started with the branding editor**

1. [Create a domain](cognito-user-pools-assign-domain.md) from the **Domain** tab, or update your existing domain. Under **Branding version**, set your domain to use **Managed login**.

1. Delete the existing app client style, if any.

   1. In the **App clients** menu, select your app client.

   1. Under **Managed login style**, select the syle assigned to your app client.

   1. Choose **Delete style**. Confirm your selection.

1. Navigate to the **Managed login** menu in your user pool. If you haven't already, follow the prompt to select a [feature plan](cognito-sign-in-feature-plans.md) that includes managed login. You can also select **Preview this feature** if you want to check out the branding editor without making changes.

1. Under **Styles**, choose **Create a style**.

1. Choose the app client that you want to assign your style to and select **Create**. You can also create a new app client.

1. The Amazon Cognito console launches the branding editor.

1. Choose a tab where you want to start editing, or select **Launch editor** and enter [quick setup](#branding-designer-quick-setup). The following tabs are available:  
**Preview**  
See how your current selections look in your managed login pages.  
**Foundation**  
Set an overall theme, configure links to external identity providers, and style form fields.  
**Components**  
Configure styles for headers, footers, and individual UI elements.

1. To make choices about initial settings, enter quick setup. Select **Change settings category** and choose **Quick setup**. When you select **Proceed**, the branding editor launches with a set of basic options for you to configure.

## Text and localization
<a name="branding-designer-loc"></a>

You can't modify or localize text in the branding editor. Instead, add a `lang` query parameter to the URL that you distribute to users. This parameters causes your managed login pages to be localized into one of several available languages. For more information, see [Managed login localization](cognito-user-pools-managed-login.md#managed-login-localization). 

## Quick setup
<a name="branding-designer-quick-setup"></a>

The **Launch branding editor** button loads a visual editor for your managed login configuration where you can select from a variety of primary customization options. As you make selections, Amazon Cognito renders your managed login changes in a preview window. To return to the detailed settings menu, select the **Change settings category** button.

**What should be the overall look and feel?**  
Configure basic theme settings for managed login.    
**Display mode**  
Choose a light-mode, dark-mode, or adaptive experience for your managed login. The adaptive settings defers to the user's browser preference when Amazon Cognito renders managed login. When you choose a browser-adaptive mode, you can choose different colors and logo images for light and dark mode.  
**Spacing**  
Set the default spacing between elements in the page.  
**Border radius**  
Set the rounding depth of the outer border of elements.

**How should the page background look?**    
**Background type**  
The **Show image** checkbox indicates whether you want a background image or to set a solid background color.  

1. To use an image, select **Show image** and choose a background image for light and dark modes. You can also set a dark-mode and light-mode **Page background color** for areas of the background that aren't covered by the image.

1. To use only a color for the background, deselect **Show image** and choose a light-mode and dark-mode **Page background color**.

**How should forms look?**  
Configure settings for the form elements of managed login. Examples of form items are login and code prompts.    
**Horizontal alignment**  
Set the horizontal alignment of form fields.  
**Form logo**  
Set the positioning of your logo image.  
**Logo image**  
Choose a logo image file to include in the form element for light and dark modes. To upload an image, select the **Logo image** dropdown, choose **Add new asset**, and add a logo file.  
**Primary branding color**  
Set a theme color for light and dark modes. This color will be applied as the background color to all elements classified as primary.

**How should headers look?**  
Choose whether you want to include a header in your managed login pages. The header can contain a logo image.    
**Header logo**  
Set the position of the logo image in your header.  
**Logo image**  
Choose a logo position and a logo image file to include in the header. To upload an image, select the **Logo image** dropdown, choose **Add new asset**, and add a logo file.  
**Header background color**  
Set the light and dark mode colors for the background of the header.

## Detailed settings
<a name="branding-designer-advanced"></a>

In the detailed settings view, you can modify individual components in the **Foundation** and **Components**. The **Preview** tab displays a preview of managed login in the current context with your customizations.

![\[An AWS Management Console screenshot of detailed configuration of managed login components.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/hosted-ui-customization-console-preview.png)


To enter the visual editor for a component, choose the edit icon in the tile for the component. From the theme studio editor, you can switch between components with the **Change setting category** button.

### Foundation
<a name="branding-designer-advanced-foundation"></a>

**App style**  
Configure the basics of your managed login configuration. This category has settings for the overall theme, text spacing, and the page header and footer.

**Display mode**  
Choose a light-mode, dark-mode, or adaptive experience for your managed login pages. When you choose a browser-adaptive mode, you can choose different colors and logo images for light and dark mode.

**Spacing**  
Set the default spacing between elements in the page.

**Authentication behavior**  
Configure styles for the buttons that connect your users to external identity providers (IdPs). This section includes the option **Domain search input** to have managed login prompt users for an email address and match them with their [SAML identity provider identifier](cognito-user-pools-managing-saml-idp-naming.md).

**Form behavior**  
Configure styles for input forms: the positioning of inputs, colors, and alignment of elements.

### Components
<a name="branding-designer-advanced-components"></a>

**Buttons**  
Styles for buttons that Amazon Cognito renders on managed login pages.

**Divider**  
Styles for divider lines and boundaries between managed login elements like the input form and the external-provider sign-in selector.

**Dropdown**  
Styles for dropdown menus.

**Favicon**  
Styles for the image that Amazon Cognito provides for the tab and bookmark icon.

**Focus rings**  
Styles for the highlights that indicate a currently-selected input.

**Form container**  
Styles for the elements that bound a form.

**Global footer**  
Styles for the footer that Amazon Cognito displays at the bottom of managed login pages.

**Global header**  
Styles for the header that Amazon Cognito displays at the top of managed login pages.

**Indications**  
Styles for error and success messages.

**Option controls**  
Styles for checkboxes, multi-selects, and other input prompts.

**Page background**  
Styles for the overall background of managed login.

**Inputs**  
Styles for form-field input prompts.

**Link**  
Styles for hyperlinks in managed login pages.

**Text for page**  
Styles for in-page text.

**Text for field**  
Styles for the text around form inputs.

## API and SDK operations for managed login branding
<a name="branding-designer-api"></a>

You can also apply branding to a managed login style with the API operations [CreateManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateManagedLoginBranding.html) and [UpdateManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateManagedLoginBranding.html). These operations are ideal for creating identical or slightly-modified versions of a branding style for another app client or user pool. Query the managed login branding of an existing style with the API operation [DescribeManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeManagedLoginBranding.html), then modify the output as needed and apply it to another resource.

The `UpdateManagedLoginBranding` operation doesn't change the app client that your style is applied to. It only updates the existing style that's assigned to an app client. To completely replace the style for an app client, delete the existing style with [DeleteManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteManagedLoginBranding.html) and assign a new style with `CreateManagedLoginBranding`. In the Amazon Cognito console, the same is true: you must delete the existing style and create a new one.

Setting up managed login branding in an API or SDK request requires that your settings be embedded in a JSON file that's converted to a `Document` datatype. The following is guidance for images that you can add and for generating programmatic requests to configure a branding style.

### Image assets
<a name="branding-designer-api-assets"></a>

[CreateManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateManagedLoginBranding.html) and [UpdateManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateManagedLoginBranding.html) include an `Assets` parameter. This parameter is an array of image files in base64-encoded binary format.

**Note**  
Programmatic requests that create or update branding style must have a request size of no more than 2 MB. The assets in your request might make it exceed this limit. If this is the case, break your request up into multiple `UpdateManagedLoginBranding` requests for groups of parameters that don't exceed the maximum request size. These requests don't result in unspecified parameters being set to default, so you can send partial requests without any effect on existing settings.

Some assets have limitations on the filetypes that you can submit.


****  

| Asset | Accepted file extensions | 
| --- | --- | 
| FAVICON\$1ICO | ico | 
| FAVICON\$1SVG | svg | 
| EMAIL\$1GRAPHIC | png, svg, jpeg | 
| SMS\$1GRAPHIC | png, svg, jpeg | 
| AUTH\$1APP\$1GRAPHIC | png, svg, jpeg | 
| PASSWORD\$1GRAPHIC | png, svg, jpeg | 
| PASSKEY\$1GRAPHIC | png, svg, jpeg | 
| PAGE\$1HEADER\$1LOGO | png, svg, jpeg | 
| PAGE\$1HEADER\$1BACKGROUND | png, svg, jpeg | 
| PAGE\$1FOOTER\$1LOGO | png, svg, jpeg | 
| PAGE\$1FOOTER\$1BACKGROUND | png, svg, jpeg | 
| PAGE\$1BACKGROUND | png, svg, jpeg | 
| FORM\$1BACKGROUND | png, svg, jpeg | 
| FORM\$1LOGO | png, svg, jpeg | 
| IDP\$1BUTTON\$1ICON | ico, svg | 

Files of the SVG type support the following attributes and elements.

------
#### [ Attributes ]

```
accent-height, accumulate, additivive, alignment-baseline, ascent, attributename, attributetype, azimuth, basefrequency, baseline-shift, begin, bias, by, class, clip, clip-path, clip-rule, color, color-interpolation, color-interpolation-filters, color-profile, color-rendering, cx, cy, d, dx, dy, diffuseconstant, direction, display, divisor, dur, edgemode, elevation, end, fill, fill-opacity, fill-rule, filter, filterunits, flood-color, flood-opacity, font-family, font-size, font-size-adjust, font-stretch, font-style, font-variant, font-weight, fx, fy, g1, g2, glyph-name, glyphref, gradientunits, gradienttransform, height, href, id, image-rendering, in, in2, k, k1, k2, k3, k4, kerning, keypoints, keysplines, keytimes, lang, lengthadjust, letter-spacing, kernelmatrix, kernelunitlength, lighting-color, local, marker-end, marker-mid, marker-start, markerheight, markerunits, markerwidth, maskcontentunits, maskunits, max, mask, media, method, mode, min, name, numoctaves, offset, operator, opacity, order, orient, orientation, origin, overflow, paint-order, path, pathlength, patterncontentunits, patterntransform, patternunits, points, preservealpha, preserveaspectratio, r, rx, ry, radius, refx, refy, repeatcount, repeatdur, restart, result, rotate, scale, seed, shape-rendering, specularconstant, specularexponent, spreadmethod, stddeviation, stitchtiles, stop-color, stop-opacity, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke, stroke-width, style, surfacescale, tabindex, targetx, targety, transform, text-anchor, text-decoration, text-rendering, textlength, type, u1, u2, unicode, values, viewbox, visibility, vert-adv-y, vert-origin-x, vert-origin-y, width, word-spacing, wrap, writing-mode, xchannelselector, ychannelselector, x, x1, x2, xmlns, y, y1, y2, z, zoomandpan
```

------
#### [ Elements ]

```
svg, a, altglyph, altglyphdef, altglyphitem, animatecolor, animatemotion, animatetransform, audio, canvas, circle, clippath, defs, desc, ellipse, filter, font, g, glyph, glyphref, hkern, image, line, lineargradient, marker, mask, metadata, mpath, path, pattern, polygon, polyline, radialgradient, rect, stop, style, switch, symbol, text, textpath, title, tref, tspan, video, view, vkern, feBlend, feColorMatrix, feComponentTransfer, feComposite, feConvolveMatrix, feDiffuseLighting, feDisplacementMap, feDistantLight, feFlood, feFuncA, feFuncB, feFuncG, feFuncR, feGaussianBlur, feMerge, feMergeNode, feMorphology, feOffset, fePointLight, feSpecularLighting, feSpotLight, feTile, feTurbulence
```

------

### Tools for managed login branding operations
<a name="branding-designer-api-tools"></a>

Amazon Cognito manages a file in the [JSON-Schema format](https://json-schema.org/docs) for the managed-login branding settings object. The following is how to programmatically update your branding style.

**To update branding in the user pools API**

1. In the Amazon Cognito console, create a default managed login branding style from the **Managed login** menu of your user pool. Assign it to an app client.

1. Record the ID of the app client that you created the style for, for example `1example23456789`.

1. Retrieve the settings for the branding style with a [DescribeManagedLoginBrandingByClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeManagedLoginBrandingByClient.html) API request with `ReturnMergedResources` set to `true`. The following is an example request body.

   ```
   {
      "ClientId": "1example23456789",
      "ReturnMergedResources": true,
      "UserPoolId": "us-east-1_EXAMPLE"
   }
   ```

1. Modify the output of `DescribeManagedLoginBrandingByClient` with your customizations.

   1. The response body is wrapped in a `ManagedLoginBranding` element that isn't part of the syntax for create and update operations. Remove this top level of the JSON object.

   1. To replace images, replace the `Bytes` value with the Base64-encoded binary data of each image file.

   1. To update settings, modify the output of the `Settings` object and include it in your next request. Amazon Cognito ignores any values in your `Settings` object that aren't in the schema that you receive in your API response.

1. Use the updated response body in a [CreateManagedLoginBranding](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateManagedLoginBranding.html) or [UpdateManagedLoginBranding](https://docs.aws.amazon.com/) request. If this request exceeds 2 MB in size, separate it out into multiple requests. These operations work in a `PATCH` model where original settings remain unchanged unless you specify otherwise.

# Customizing hosted UI (classic) branding
<a name="hosted-ui-classic-branding"></a>

You can use the AWS Management Console, or the AWS CLI or API, to specify classic customization settings for the hosted UI. You can upload a custom logo image to be displayed in the app. You can also apply some cascading style sheets (CSS) options to the look and feel of the UI.

You can customize the UI defaults and override individual [app clients](cognito-terms.md#term-appclient) with specific settings. Amazon Cognito applies the default configuration to every app client that doesn't have client-level settings.

In the Amazon Cognito console and in API requests, the request that sets your UI customization must not exceed 135 KB in size. In rare cases, the sum of request headers, your CSS file, and your logo might exceed 135KB. Amazon Cognito encodes the image file to Base64. This increases the size of a 100 KB image to 130 KB, keeping five KB for request headers and your CSS. If the request is too large, the AWS Management Console or your `SetUICustomization` API request returns a `request parameters too large` error. Adjust your logo image to be no greater than 100KB and your CSS file to be no larger than 3 KB. You can't set CSS and logo customization separately.

**Note**  
To customize your UI, you must set up a domain for your user pool.

## Specifying a custom logo in classic branding
<a name="cognito-user-pools-app-ui-customization-logo"></a>

Amazon Cognito centers your custom logo above the input fields at the [Login endpoint](login-endpoint.md).

Choose a PNG, JPG, or JPEG file that can scale to 350 by 178 pixels for your custom hosted UI logo. Your logo file can be no larger than 100 KB in size, or 130 KB after Amazon Cognito encodes to Base64. To set an `ImageFile` in [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUICustomization.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUICustomization.html) in the API, convert your file to a Base64-encoded text string or, in the AWS CLI, provide a file path and let Amazon Cognito encode it for you.

## Specifying CSS customizations in classic branding
<a name="cognito-user-pools-app-ui-customization-css"></a>

You can customize the CSS for the hosted app pages, with the following restrictions:
+ You can use any of the following CSS class names:
  + `background-customizable`
  + `banner-customizable`
  + `errorMessage-customizable`
  + `idpButton-customizable`
  + `idpButton-customizable:hover`
  + `idpDescription-customizable`
  + `inputField-customizable`
  + `inputField-customizable:focus`
  + `label-customizable`
  + `legalText-customizable`
  + `logo-customizable`
  + `passwordCheck-valid-customizable`
  + `passwordCheck-notValid-customizable`
  + `redirect-customizable`
  + `socialButton-customizable`
  + `submitButton-customizable`
  + `submitButton-customizable:hover`
  + `textDescription-customizable`
+ Property values can contain HTML, except for the following values: `@import`, `@supports`, `@page`, or `@media` statements, or Javascript.

You can customize the following CSS properties.

**Labels**  
+ **font-weight** is a multiple of 100 from 100 to 900.
+ **color** is the text color. Must be a [legal CSS color value](https://www.w3schools.com/cssref/css_colors_legal.php).

**Input fields**  
+ **width** is the width of the containing block as a percentage.
+ **height** is the height of the input field in pixels (px).
+ **color** is the text color. It can be any standard CSS color value.
+ **background-color** is the background color of the input field. It can be any standard CSS color value.
+ **border** is a standard CSS border value that specifies the width, transparency, and color of the border of your app window. Width can be any value from 1px to 100px. Transparency can be solid or none. Color can be any standard color value.

**Text descriptions**  
+ **padding-top** is the amount of padding above the text description.
+ **padding-bottom** is the amount of padding below the text description.
+ **display** can be `block` or `inline`.
+ **font-size** is the font size for text descriptions.
+ **color** is the text color. Must be a [legal CSS color value](https://www.w3schools.com/cssref/css_colors_legal.php).

**Submit button**  
+ **font-size** is the font size of the button text.
+ **font-weight** is the font weight of the button text: `bold`, `italic`, or `normal`.
+ **margin** is a string of four values indicating the top, right, bottom, and left margin sizes for the button.
+ **font-size** is the font size for text descriptions.
+ **width** is the width of the button text in percent of the containing block.
+ **height** is the height of the button in pixels (px).
+ **color** is the button text color. It can be any standard CSS color value.
+ **background-color** is the background color of the button. It can be any standard color value.

**Banner**  
+ **padding** is a string of four values indicating the top, right, bottom, and left padding sizes for the banner.
+ **background-color** is the banner's background color. It can be any standard CSS color value.

**Submit button hover**  
+ **color** is the foreground color of the button when you hover over it. It can be any standard CSS color value.
+ **background-color** is the background color of the button when you hover over it. It can be any standard CSS color value.

**Identity provider button hover**  
+ **color** is the foreground color of the button when you hover over it. It can be any standard CSS color value.
+ **background-color** is the background color of the button when you hover over it. It can be any standard CSS color value.

**Password check not valid**  
+ **color** is the text color of the `"Password check not valid"` message. It can be any standard CSS color value.

**Background**  
+ **background-color** is the background color of the app window. It can be any standard CSS color value.

**Error messages**  
+ **margin** is a string of four values indicating the top, right, bottom, and left margin sizes.
+ **padding** is the padding size.
+ **font-size** is the font size.
+ **width** is the width of the error message as a percentage of the containing block.
+ **background** is the background color of the error message. It can be any standard CSS color value.
+ **border** is a string of three values specifying the width, transparency, and color of the border.
+ **color** is the error message text color. It can be any standard CSS color value.
+ **box-sizing** is used to indicate to the browser what the sizing properties (width and height) should include.

**Identity provider buttons**  
+ **height** is the height of the button in pixels (px).
+ **width** is the width of the button text as a percentage of the containing block. 
+ **text-align** is the text alignment setting. It can be `left`, `right`, or `center`.
+ **margin-bottom** is the bottom margin setting. 
+ **color** is the button text color. It can be any standard CSS color value.
+ **background-color** is the background color of the button. It can be any standard CSS color value.
+ **border-color** is the color of the button border. It can be any standard CSS color value.

**Identity provider descriptions**  
+ **padding-top** is the amount of padding above the description.
+ **padding-bottom** is the amount of padding below the description.
+ **display** can be `block` or `inline`.
+ **font-size** is the font size for descriptions.
+ **color** is the text color for IdP section headers for example **Sign in with your corporate ID**. Must be a [legal CSS color value](https://www.w3schools.com/cssref/css_colors_legal.php).

**Legal text**  
+ **color** is the text color. It can be any standard CSS color value.
+ **font-size** is the font size.
When you customize **Legal text**, you are customizing the message **We won't post to any of your accounts without asking first** that is displayed under social identity providers in the sign-in page.

**Logo**  
+ **max-width** is the maximum width as a percentage of the containing block.
+ **max-height** is the maximum height as a percentage of the containing block.
+ **background-color** is the color of the background for logs with transparent sections. Must be a [legal CSS color value](https://www.w3schools.com/cssref/css_colors_legal.php).

**Input field focus**  
+ **border-color** is the color of the input field. It can be any standard CSS color value.
+ **outline** is the border width of the input field, in pixels.

**Social button**  
+ **height** is the height of the button in pixels (px).
+ **text-align** is the text alignment setting. It can be `left`, `right`, or `center`.
+ **width** is the width of the button text as a percentage of the containing block.
+ **margin-bottom** is the bottom margin setting.

**Password check valid**  
+ **color** is the text color of the `"Password check valid"` message. It can be any standard CSS color value.

## Customizing the hosted UI with classic branding in the AWS Management Console
<a name="cognito-user-pools-app-ui-customization-console"></a>

You can use the AWS Management Console to specify UI customization settings for your app.

**Note**  
You can view the hosted UI with your customizations by constructing the following URL, with the specifics for your user pool, and typing it into a browser: ` https://<your_domain>/login?response_type=code&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>` You may have to wait up to one minute to refresh your browser before changes made in the console appear.  
Your domain is shown on the **App integration** tab under **Domain**. Your app client ID and callback URL are shown under **App clients**.

**To specify app UI customization settings**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home).

1. In the navigation pane, choose **User Pools**, and choose the user pool you want to edit.

1. [Create a domain](cognito-user-pools-assign-domain.md) from the **Domain** tab, or update your existing domain. Under **Branding version**, set your domain to use **Hosted UI (classic)**.

1. Choose the **Managed login** menu.

1. To customize UI settings for all app clients, locate **Style** under **Hosted UI settings** and select **Edit**.

1. To customize UI settings for one app client, go to the **App clients** menu and select the app client you want to modify, then locate **Hosted UI (classic) style** and select **Override**. Select **Edit**.

1. To upload your own logo image file, choose **Choose file** or **Replace current file**.

1. To customize hosted UI CSS, download **CSS template.css** and modify the template with the values you want to customize. Only the keys that are included in the template can be used with the hosted UI. Added CSS keys will not be reflected in your UI. After you have customized the CSS file, choose **Choose file** or **Replace current file** to upload your custom CSS file.

## Customizing the hosted UI with classic branding in the user pools API and with the AWS CLI
<a name="cognito-user-pools-app-ui-customization-cli-api"></a>

Use the following commands to specify app UI customization settings for your user pool.

**To get the UI customization settings for a user pool's built-in app UI, use the following API operations.**
+ AWS CLI: `aws cognito-idp get-ui-customization`
+ AWS API: [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUICustomization.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUICustomization.html)

**To set the UI customization settings for a user pool's built-in app UI, use the following API operations.**
+ AWS CLI from image file: `aws cognito-idp set-ui-customization --user-pool-id <your-user-pool-id> --client-id <your-app-client-id> --image-file fileb://"<path-to-logo-image-file>" --css ".label-customizable{ color: <color>;}"`
+ AWS CLI with image encoded as Base64 binary text: `aws cognito-idp set-ui-customization --user-pool-id <your-user-pool-id> --client-id <your-app-client-id> --image-file <base64-encoded-image-file> --css ".label-customizable{ color: <color>;}"`
+ AWS API: [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUICustomization.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUICustomization.html)

# Customizing user pool workflows with Lambda triggers
<a name="cognito-user-pools-working-with-lambda-triggers"></a>

Amazon Cognito works with AWS Lambda functions to modify the authentication behavior of your user pool. You can configure your user pool to automatically invoke Lambda functions before their first sign-up, after they complete authentication, and at several stages in between. Your functions can modify the default behavior of your authentication flow, make API requests to modify your user pool or other AWS resources, and communicate with external systems. The code in your Lambda functions is your own. Amazon Cognito sends event data to your function, waits for the function to process the data, and in most cases anticipates a response event that reflects any changes you want to make to the session.

Within the system of request and response events, you can introduce your own authentication challenges, migrate users between your user pool and another identity store, customize messages, and modify JSON web tokens (JWTs).

Lambda triggers can customize the response that Amazon Cognito delivers to your user after they initiate an action in your user pool. For example, you can prevent sign-in by a user who would otherwise succeed. They can also perform runtime operations against your AWS environment, external APIs, databases, or identity stores. The migrate user trigger, for example, can combine external action with a change in Amazon Cognito: you can look up user information in an external directory, then set attributes on a new user based on that external information.

When you have a Lambda trigger assigned to your user pool, Amazon Cognito interrupts its default flow to request information from your function. Amazon Cognito generates a JSON *event* and passes it to your function. The event contains information about your user's request to create a user account, sign in, reset a password, or update an attribute. Your function then has an opportunity to take action, or to send the event back unmodified. An event returned unmodified notifies your user pool to proceed with the default action for the event. For example, your pre sign-up trigger can automatically confirm users for the `PreSignUp_SignUp` trigger source, but return the event unchanged for external and administrator-created users.

The following table summarizes some of the ways you can use Lambda triggers to customize user pool operations:


****  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html)

**Topics**
+ [

## Things to know about Lambda triggers
](#important-lambda-considerations)
+ [

## Add a user pool Lambda trigger
](#triggers-working-with-lambda)
+ [

## User pool Lambda trigger event
](#cognito-user-pools-lambda-trigger-event-parameter-shared)
+ [

## User pool Lambda trigger common parameters
](#cognito-user-pools-lambda-trigger-syntax-shared)
+ [

## Client metadata
](#working-with-lambda-trigger-client-metadata)
+ [

## Connecting API operations to Lambda triggers
](#lambda-triggers-by-event)
+ [

## Connecting Lambda triggers to user pool functional operations
](#working-with-lambda-trigger-sources)
+ [

# Pre sign-up Lambda trigger
](user-pool-lambda-pre-sign-up.md)
+ [

# Post confirmation Lambda trigger
](user-pool-lambda-post-confirmation.md)
+ [

# Pre authentication Lambda trigger
](user-pool-lambda-pre-authentication.md)
+ [

# Post authentication Lambda trigger
](user-pool-lambda-post-authentication.md)
+ [

# Inbound federation Lambda trigger
](user-pool-lambda-inbound-federation.md)
+ [

# Custom authentication challenge Lambda triggers
](user-pool-lambda-challenge.md)
+ [

# Pre token generation Lambda trigger
](user-pool-lambda-pre-token-generation.md)
+ [

# Migrate user Lambda trigger
](user-pool-lambda-migrate-user.md)
+ [

# Custom message Lambda trigger
](user-pool-lambda-custom-message.md)
+ [

# Custom sender Lambda triggers
](user-pool-lambda-custom-sender-triggers.md)

## Things to know about Lambda triggers
<a name="important-lambda-considerations"></a>

When you are preparing your user pools for Lambda functions, consider the following:
+ The events that Amazon Cognito sends to your Lambda triggers might change with new features. The positions of response and request elements in the JSON hierarchy might change, or element names might be added. In your Lambda function, you can expect to receive the input-element key-value pairs described in this guide, but stricter input validation can cause your functions to fail.
+ You can choose one of multiple versions of the events that Amazon Cognito sends to some triggers. Some versions might require you to accept a change to your Amazon Cognito pricing. For more information about pricing, see [Amazon Cognito Pricing](https://aws.amazon.com/cognito/pricing/). To customize access tokens in a [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md), you must configure your user pool with a feature plan other than *Lite* and update your Lambda trigger configuration to use event version 2.
+ Except for [Custom sender Lambda triggers](user-pool-lambda-custom-sender-triggers.md), Amazon Cognito invokes Lambda functions synchronously. When Amazon Cognito calls your Lambda function, it must respond within 5 seconds. If it doesn't and if the call can be retried, Amazon Cognito may retry the call. If all retry attempts fail, the function times out. You can't change this five-second timeout value. For more information, see [Lambda programming model](https://docs.aws.amazon.com/lambda/latest/dg/foundation-progmodel.html) in the AWS Lambda Developer Guide.

  Amazon Cognito doesn't retry function calls that return an [Invoke error](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_Errors) with an HTTP status code of 500-599. These codes indicate a configuration issue that leaves Lambda unable to launch the function. For more information, see [Error handling and automatic retries in AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/invocation-retries.html).
+ You can't declare a function version in your Lambda trigger configuration. Amazon Cognito user pools invoke the latest version of your function by default. However, you can associate a function version with an alias and set your trigger `LambdaArn` to the alias ARN in a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request. This option isn't available in the AWS Management Console. For more information about aliases, see [Lambda function aliases](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) in the *AWS Lambda Developer Guide*.
+ If you delete a Lambda trigger, you must update the corresponding trigger in the user pool. For example, if you delete the post authentication trigger, you must set the **Post authentication** trigger in the corresponding user pool to **none**. 
+ If your Lambda function doesn't return the request and response parameters to Amazon Cognito, or returns an error, the authentication event doesn't succeed. You can return an error in your function to prevent a user's sign-up, authentication, token generation, or any other stage of their authentication flow that invokes Lambda trigger.

  Managed login returns errors that Lambda triggers generate as error text above the sign-in prompt. The Amazon Cognito user pools API returns trigger errors in the format `[trigger] failed with error [error text from response]`. As a best practice, only generate errors in your Lambda functions that you want your users to see. Use output methods like `print()` to log any sensitive or debugging information to CloudWatch Logs. For an example, see [Pre sign-up example: Deny sign-up if user name has fewer than five characters](user-pool-lambda-pre-sign-up.md#aws-lambda-triggers-pre-registration-example-3).
+ You can add a Lambda function in another AWS account as a trigger for your user pool. You must add cross-account triggers with the [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) and [UpdateUserPool](https://docs.aws.amazon.com/) API operations, or their equivalents in CloudFormation and the AWS CLI. You can't add cross-account functions in the AWS Management Console.
+ When you add a Lambda trigger in the Amazon Cognito console, Amazon Cognito adds a resource-based policy to your function that permits your user pool to invoke the function. When you create a Lambda trigger outside of the Amazon Cognito console, including a cross-account function, you must add permissions to the resource-based policy of the Lambda function. Your added permissions must allow Amazon Cognito to invoke the function on behalf of your user pool. You can [add permissions from the Lambda Console](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html) or use the Lambda [AddPermission](https://docs.aws.amazon.com/lambda/latest/dg/API_AddPermission.html) API operation.

**Example Lambda Resource-Based Policy**  
The following example Lambda resource-based policy grants Amazon Cognito a limited ability to invoke a Lambda function. Amazon Cognito can only invoke the function when it does so on behalf of both the user pool in the `aws:SourceArn` condition and the account in the `aws:SourceAccount` condition.

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Id": "default",
      "Statement": [
          {
              "Sid": "LambdaCognitoIdpTrust",
              "Effect": "Allow",
              "Principal": {
                  "Service": "cognito-idp.amazonaws.com"
              },
              "Action": "lambda:InvokeFunction",
              "Resource": "arn:aws:lambda:us-east-1:111122223333:function:MyFunction",
              "Condition": {
                  "StringEquals": {
                      "AWS:SourceAccount": "111122223333"
                  },
                  "ArnLike": {
                      "AWS:SourceArn": "arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_EXAMPLE"
                  }
              }
          }
      ]
  }
  ```

------

## Add a user pool Lambda trigger
<a name="triggers-working-with-lambda"></a>

**To add a user pool Lambda trigger with the console**

1. Use the [Lambda console](https://console.aws.amazon.com/lambda/home) to create a Lambda function. For more information on Lambda functions, see the [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/).

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home), and then choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Extensions** menu and locate **Lambda triggers**.

1. Choose **Add a Lambda trigger**.

1. Select a Lambda trigger **Category** based on the stage of authentication that you want to customize.

1. Select **Assign Lambda function** and select a function in the same AWS Region as your user pool.
**Note**  
If your AWS Identity and Access Management (IAM) credentials have permission to update the Lambda function, Amazon Cognito adds a Lambda resource-based policy. With this policy, Amazon Cognito can invoke the function that you select. If the signed-in credentials do not have sufficient IAM permissions, you must update the resource-based policy separately. For more information, see [Things to know about Lambda triggers](#important-lambda-considerations).

1. Choose **Save changes**.

1. You can use CloudWatch in the Lambda console to log your Lambda function . For more information, see [Accessing CloudWatch Logs for Lambda](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions-logs.html).

## User pool Lambda trigger event
<a name="cognito-user-pools-lambda-trigger-event-parameter-shared"></a>

Amazon Cognito passes event information to your Lambda function. The Lambda function returns the same event object back to Amazon Cognito with any changes in the response. If your function returns the input event without modification, Amazon Cognito proceed with default behavior. The following shows the parameters that are common to all Lambda trigger input events. For trigger-specific event syntax, review the event schema on the section of this guide for each trigger.

------
#### [ JSON ]

```
{
    "version": "string",
    "triggerSource": "string",
    "region": AWSRegion,
    "userPoolId": "string",
    "userName": "string",
    "callerContext": 
        {
            "awsSdkVersion": "string",
            "clientId": "string"
        },
    "request":
        {
            "userAttributes": {
                "string": "string",
                ....
            }
        },
    "response": {}
}
```

------

## User pool Lambda trigger common parameters
<a name="cognito-user-pools-lambda-trigger-syntax-shared"></a>

**version**  
The version number of your Lambda function.

**triggerSource**  
The name of the event that triggered the Lambda function. For a description of each triggerSource see [Connecting Lambda triggers to user pool functional operations](#working-with-lambda-trigger-sources).

**region**  
The AWS Region as an `AWSRegion` instance.

**userPoolId**  
The ID of the user pool.

**userName**  
The current user's username.

**callerContext**  
Metadata about the request and the code environment. It contains the fields **awsSdkVersion** and **clientId**.    
**awsSdkVersion**  
The version of the AWS SDK that generated the request.  
****clientId****  
The ID of the user pool app client.

**request**  
Details of your user's API request. It includes the following fields, and any request parameters that are particular to the trigger. For example, an event that Amazon Cognito sends to a pre-authentication trigger will also contain a `userNotFound` parameter. You can process the value of this parameter to take a custom action when your user tries to sign in with an unregistered username.    
**userAttributes**  
One or more key-value pairs of user attribute names and values, for example `"email": "john@example.com"`.

**response**  
This parameter doesn't contain any information in the original request. Your Lambda function must return the entire event to Amazon Cognito, and add any return parameters to the `response`. To see what return parameters your function can include, refer to the documentation for the trigger that you want to use.

## Client metadata
<a name="working-with-lambda-trigger-client-metadata"></a>

You can submit custom parameters to your Lambda trigger functions in API operations and [Token endpoint](token-endpoint.md) requests. With client metadata, your application can collect additional information about the environment where requests originate. When you pass client metadata to your Lambda functions, they can process the additional data and make use of it in logging or customization of authentication flows. Client metadata is string pairs of your choosing and design in a JSON key-value format.

**Client metadata example use cases**
+ Pass geolocation data at sign-up to the [pre sign-up trigger](user-pool-lambda-pre-sign-up.md) and prevent sign-in from unwanted locations.
+ Pass tenant ID data to [custom challenge triggers](user-pool-lambda-challenge.md) and issue different challenges to customers from different business units.
+ Pass a user's token to the [pre token generation trigger](user-pool-lambda-pre-token-generation.md) and generate a log of the principal that an M2M request was made on behalf of. For an example request, see [Client credentials with basic authorizationClient credentials with POST body authorization](token-endpoint.md#exchanging-client-credentials-for-an-access-token-in-request-body).

Here is an example of passing client metadata to the pre sign-up trigger.

------
#### [ SignUp request ]

The following is an example [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html#CognitoUserPools-SignUp-request-ValidationData) request with client metadata that Amazon Cognito passes to a pre sign-up trigger.

```
POST HTTP/1.1
Host: cognito-idp.us-east-1.amazonaws.com
X-Amz-Date: 20230613T200059Z
Accept-Encoding: gzip, deflate, br
X-Amz-Target: AWSCognitoIdentityProviderService.SignUp
User-Agent: <UserAgentString>
Authorization: AWS4-HMAC-SHA256 Credential=<Credential>, SignedHeaders=<Headers>, Signature=<Signature>
Content-Length: <PayloadSizeBytes>

{
    "ClientId": "1example23456789",
    "Username": "mary_major",
    "Password": "<Password>",
    "SecretHash": "<Secret hash>",
    "ClientMetadata": { 
        "IpAddress" : "192.0.2.252",
        "GeoLocation" : "Netherlands (Kingdom of the) [NL]"
    }
    "UserAttributes": [
        {
            "Name": "name",
            "Value": "Mary"
        },
        {
            "Name": "email",
            "Value": "mary_major@example.com"
        },
        {
            "Name": "phone_number",
            "Value": "+12065551212"
        }
    ],
}
```

------
#### [ Lambda trigger input event ]

The request results in the following request body to your pre sign-up function.

```
{
    "callerContext": {
        "awsSdkVersion": "aws-sdk-unknown-unknown",
        "clientId": "1example23456789"
    },
    "region": "us-west-2",
    "request": {
        "clientMetadata": {
            "GeoLocation": "Netherlands (Kingdom of the) [NL]",
            "IpAddress": "192.0.2.252"
        },
        "userAttributes": {
            "email": "mary_major@example.com",
            "name": "Mary",
            "phone_number": "+12065551212"
        },
        "validationData": null
    },
    "response": {
        "autoConfirmUser": false,
        "autoVerifyEmail": false,
        "autoVerifyPhone": false
    },
    "triggerSource": "PreSignUp_SignUp",
    "userName": "mary_major2",
    "userPoolId": "us-west-2_EXAMPLE",
    "version": "1"
}
```

------

**Client metadata for machine-to-machine (M2M) client credentials**  
You can pass [client metadata](#working-with-lambda-trigger-client-metadata) in M2M requests. Client metadata is additional information from a user or application environment that can contribute to the outcomes of a [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md). In authentication operations with a user principal, you can pass client metadata to the pre token generation trigger in the body of [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API requests. Because applications conduct the flow for generation of access tokens for M2M with direct requests to the [Token endpoint](token-endpoint.md), they have a different model. In the POST body of token requests for client credentials, pass an `aws_client_metadata` parameter with the client metadata object URL-encoded (`x-www-form-urlencoded`) to string. For an example request, see [Client credentials with basic authorizationClient credentials with POST body authorization](token-endpoint.md#exchanging-client-credentials-for-an-access-token-in-request-body). The following is an example parameter that passes the key-value pairs `{"environment": "dev", "language": "en-US"}`.

```
aws_client_metadata=%7B%22environment%22%3A%20%22dev%22,%20%22language%22%3A%20%22en-US%22%7D
```

**Temporary user attributes: `validationData`**  
Some authentication operations also have a `validationData` parameter. Like client metadata, this is an opportunity to pass external information that Amazon Cognito doesn't automatically gather to Lambda triggers. The validation data field is intended to provide your Lambda function witth additional user context in sign-up and sign-in operations. [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html#CognitoUserPools-SignUp-request-ValidationData) and [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html#CognitoUserPools-AdminCreateUser-request-ValidationData) pass `validationData` to the [pre sign-up trigger](user-pool-lambda-pre-sign-up.md). [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-request-ClientMetadata) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html#CognitoUserPools-AdminInitiateAuth-request-ClientMetadata) pass `ClientMetadata` in the API request body as `validationData` in the input event to the [pre authentication](user-pool-lambda-pre-authentication.md) and [migrate user](user-pool-lambda-migrate-user.md) triggers.

To map API operations to the functions that they can pass client metadata to, refer to the trigger source sections that follow.

## Connecting API operations to Lambda triggers
<a name="lambda-triggers-by-event"></a>

The following sections describe the Lambda triggers that Amazon Cognito invokes from the activity in your user pool.

When your app signs in users through the Amazon Cognito user pools API, managed login, or user pool endpoints, Amazon Cognito invokes your Lambda functions based on the session context. For more information about the Amazon Cognito user pools API and user pool endpoints, see [Understanding API, OIDC, and managed login pages authentication](authentication-flows-public-server-side.md#user-pools-API-operations). The tables in the sections that follow describe events that cause Amazon Cognito to invoke a function, and the `triggerSource` string that Amazon Cognito includes in the request.

**Topics**
+ [

### Lambda triggers in the Amazon Cognito API
](#lambda-triggers-native-users-native-api)
+ [

### Lambda triggers for Amazon Cognito local users in managed login
](#lambda-triggers-native-users-hosted-UI)
+ [

### Lambda triggers for federated users
](#lambda-triggers-for-federated-users)

### Lambda triggers in the Amazon Cognito API
<a name="lambda-triggers-native-users-native-api"></a>

The following table describes the source strings for the Lambda triggers that Amazon Cognito can invoke when your app creates, signs in, or updates a local user.


**Local user trigger sources in the Amazon Cognito API**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html)

### Lambda triggers for Amazon Cognito local users in managed login
<a name="lambda-triggers-native-users-hosted-UI"></a>

The following table describes the source strings for the Lambda triggers that Amazon Cognito can invoke when a local user signs in to your user pool with managed login.


**Local user trigger sources in managed login**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html)

### Lambda triggers for federated users
<a name="lambda-triggers-for-federated-users"></a>

You can use the following Lambda triggers to customize your user pool workflows for users who sign in with a federated provider. 

**Note**  
Federated users can use managed login to sign in, or you can generate a request to the [Authorize endpoint](authorization-endpoint.md) that silently redirects them to their identity provider sign-in page. You can't sign in federated users with the Amazon Cognito user pools API.


**Federated user trigger sources**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html)

Federated sign-in does not invoke any [Custom authentication challenge Lambda triggers](user-pool-lambda-challenge.md), [Migrate user Lambda trigger](user-pool-lambda-migrate-user.md), [Custom message Lambda trigger](user-pool-lambda-custom-message.md), or [Custom sender Lambda triggers](user-pool-lambda-custom-sender-triggers.md) in your user pool.

## Connecting Lambda triggers to user pool functional operations
<a name="working-with-lambda-trigger-sources"></a>

Each Lambda trigger serves a functional role in your user pool. For example, a trigger can modify your sign-up flow, or add a custom authentication challenge. The event that Amazon Cognito sends to a Lambda function can reflect one of multiple actions that make up that functional role. For example, Amazon Cognito invokes a pre sign-up trigger when your user signs up, and when you create a user. Each of these different cases for the same functional role has its own `triggerSource` value. Your Lambda function can process incoming events differently based on the operation that invoked it.

Amazon Cognito also invokes all assigned functions when an event corresponds to a trigger source. For example, when a user signs in to a user pool where you assigned migrate user and pre authentication triggers, they activate both.


**Sign-up, confirmation, and sign-in (authentication) triggers**  

| Trigger | triggerSource value | Event | 
| --- | --- | --- | 
| Pre sign-up | PreSignUp\$1SignUp | Pre sign-up. | 
| Pre sign-up | PreSignUp\$1AdminCreateUser | Pre sign-up when an admin creates a new user. | 
| Pre sign-up | PreSignUp\$1ExternalProvider | Pre sign-up for external identity providers. | 
| Post confirmation | PostConfirmation\$1ConfirmSignUp | Post sign-up confirmation. | 
| Post confirmation | PostConfirmation\$1ConfirmForgotPassword | Post Forgot Password confirmation. | 
| Pre authentication | PreAuthentication\$1Authentication | Pre authentication. | 
| Post authentication | PostAuthentication\$1Authentication | Post authentication. | 


**Custom authentication challenge triggers**  

| Trigger | triggerSource value | Event | 
| --- | --- | --- | 
| Define auth challenge | DefineAuthChallenge\$1Authentication | Define Auth Challenge. | 
| Create auth challenge | CreateAuthChallenge\$1Authentication | Create Auth Challenge. | 
| Verify auth challenge | VerifyAuthChallengeResponse\$1Authentication | Verify Auth Challenge Response. | 


**Federation triggers**  

| Trigger | triggerSource value | Event | 
| --- | --- | --- | 
| Inbound federation | InboundFederation\$1ExternalProvider | Inbound federation. | 


**Pre token generation triggers**  

| Trigger | triggerSource value | Event | 
| --- | --- | --- | 
| Pre token generation | TokenGeneration\$1HostedAuth |  Amazon Cognito authenticates the user from your managed login sign-in page. | 
| Pre token generation | TokenGeneration\$1Authentication | User authentication or token refresh complete. | 
| Pre token generation | TokenGeneration\$1NewPasswordChallenge | Admin creates the user. Amazon Cognito invokes this when the user must change a temporary password. | 
| Pre token generation | TokenGeneration\$1AuthenticateDevice | End of the authentication of a user device. | 
| Pre token generation | TokenGeneration\$1RefreshTokens | User tries to refresh the identity and access tokens. | 


**Migrate user triggers**  

| Trigger | triggerSource value | Event | 
| --- | --- | --- | 
| User migration | UserMigration\$1Authentication | User migration at the time of sign-in. | 
| User migration | UserMigration\$1ForgotPassword | User migration during the forgot-password flow. | 


**Custom message triggers**  

| Trigger | triggerSource value | Event | 
| --- | --- | --- | 
| Custom message | CustomMessage\$1SignUp | Custom message when a user signs up in your user pool. | 
| Custom message | CustomMessage\$1AdminCreateUser | Custom message when you create a user as an administrator and Amazon Cognito sends them a temporary password. | 
| Custom message | CustomMessage\$1ResendCode | Custom message when your existing user requests a new confirmation code. | 
| Custom message | CustomMessage\$1ForgotPassword | Custom message when your user requests a password reset. | 
| Custom message | CustomMessage\$1UpdateUserAttribute | Custom message when a user changes their email address or phone number and Amazon Cognito sends a verification code. | 
| Custom message | CustomMessage\$1VerifyUserAttribute | Custom message when a user adds an email address or phone number and Amazon Cognito sends a verification code. | 
| Custom message | CustomMessage\$1Authentication | Custom message when a user who has configured SMS MFA signs in. | 


**Custom sender triggers**  

| Trigger | triggerSource value | Event | 
| --- | --- | --- | 
| Custom sender |  `CustomEmailSender_SignUp` `CustomSmsSender_SignUp`  | When a user signs up in your user pool. | 
| Custom sender |  `CustomEmailSender_AdminCreateUser` `CustomSmsSender_AdminCreateUser`  | When you create a user as an administrator and Amazon Cognito sends them a temporary password. | 
| Custom sender |  `CustomEmailSender_ForgotPassword` `CustomSmsSender_ForgotPassword`  | When your user requests a password reset. | 
| Custom sender |  `CustomEmailSender_UpdateUserAttribute` `CustomSmsSender_UpdateUserAttribute`  | When a user changes their email address or phone number and Amazon Cognito sends a verification code. | 
| Custom sender |  `CustomEmailSender_VerifyUserAttribute` `CustomSmsSender_VerifyUserAttribute`  | When a user adds an email address or phone number and Amazon Cognito sends a verification code. | 
| Custom sender |  `CustomEmailSender_Authentication` `CustomSmsSender_Authentication`  | When a user who has configured SMS or email MFA or OTP signs in. | 
| Custom sender | CustomEmailSender\$1AccountTakeOverNotification | When your threat protection settings take an automated action against a user's sign-in attempt and the action for the risk level includes a notification. | 

# Pre sign-up Lambda trigger
<a name="user-pool-lambda-pre-sign-up"></a>

You might want to customize the sign-up process in user pools that have self-service sign-up options. Some common uses of the pre sign-up trigger are to perform custom analysis and recording of new users, apply security and governance standards, or link users from a third-party IdP to a [consolidated user profile](cognito-user-pools-identity-federation-consolidate-users.md). You might also have trusted users who aren't required to undergo [verification and confirmation](signing-up-users-in-your-app.md).

Immediately before Amazon Cognito completes creation of a new [local](cognito-terms.md#terms-localuser) or [federated](cognito-terms.md#terms-federateduser) user, it activates the pre sign-up Lambda function. The `userAttributes` in the request object sent to this function contain attributes that have been provided by local user sign-up or that have successfully been mapped from provider attributes for a federated user. Your user pool invokes this trigger on self-service sign-up with [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) or first sign-in with a trusted [identity provider](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-federated), and on user creation with [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html). As part of the sign-up process, you can use this function to analyze the sign-in event with custom logic, and modify or deny the new user.

**Topics**
+ [

## Pre sign-up Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-pre-signup)
+ [

## Pre sign-up example: Auto-confirm users from a registered domain
](#aws-lambda-triggers-pre-registration-example)
+ [

## Pre sign-up example: Auto-confirm and auto-verify all users
](#aws-lambda-triggers-pre-registration-example-2)
+ [

## Pre sign-up example: Deny sign-up if user name has fewer than five characters
](#aws-lambda-triggers-pre-registration-example-3)

## Pre sign-up Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        },
        "validationData": {
            "string": "string",
            . . .
         },
        "clientMetadata": {
            "string": "string",
            . . .
         }
    },

    "response": {
        "autoConfirmUser": "boolean",
        "autoVerifyPhone": "boolean",
        "autoVerifyEmail": "boolean"
    }
}
```

------

### Pre sign-up request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup-request"></a>

**userAttributes**  
One or more name-value pairs representing user attributes. The attribute names are the keys.

**validationData**  
One or more key-value pairs with user attribute data that your app passed to Amazon Cognito in the request to create a new user. Send this information to your Lambda function in the ValidationData parameter of your [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) or [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) API request.  
Amazon Cognito doesn't set your ValidationData data as attributes of the user that you create. ValidationData is temporary user information that you supply for the purposes of your pre sign-up Lambda trigger.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the pre sign-up trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html), [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html), [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html), and [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html).

### Pre sign-up response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup-response"></a>

In the response, you can set `autoConfirmUser` to `true` if you want to auto-confirm the user. You can set `autoVerifyEmail` to `true` to auto-verify the user's email. You can set `autoVerifyPhone` to `true` to auto-verify the user's phone number.

**Note**  
Response parameters `autoVerifyPhone`, `autoVerifyEmail` and `autoConfirmUser` are ignored by Amazon Cognito when the pre sign-up Lambda function is triggered by the `AdminCreateUser` API.

**autoConfirmUser**  
Set to `true` to auto-confirm the user, or `false` otherwise.

**autoVerifyEmail**  
Set to `true` to set as verified the email address of a user who is signing up, or `false` otherwise. If `autoVerifyEmail` is set to `true`, the `email` attribute must have a valid, non-null value. Otherwise an error will occur and the user will not be able to complete sign-up.  
If the `email` attribute is selected as an alias, an alias will be created for the user's email address when `autoVerifyEmail` is set. If an alias with that email address already exists, the alias will be moved to the new user and the previous user's email address will be marked as unverified. For more information, see [Customizing sign-in attributes](user-pool-settings-attributes.md#user-pool-settings-aliases).

**autoVerifyPhone**  
Set to `true` to set as verified the phone number of a user who is signing up, or `false` otherwise. If `autoVerifyPhone` is set to `true`, the `phone_number` attribute must have a valid, non-null value. Otherwise an error will occur and the user will not be able to complete sign-up.  
If the `phone_number` attribute is selected as an alias, an alias will be created for the user's phone number when `autoVerifyPhone` is set. If an alias with that phone number already exists, the alias will be moved to the new user and the previous user's phone number will be marked as unverified. For more information, see [Customizing sign-in attributes](user-pool-settings-attributes.md#user-pool-settings-aliases).

## Pre sign-up example: Auto-confirm users from a registered domain
<a name="aws-lambda-triggers-pre-registration-example"></a>

This is example Lambda trigger code. The pre sign-up trigger is invoked immediately before Amazon Cognito processes the sign-up request. It uses a custom attribute **custom:domain** to automatically confirm new users from a particular email domain. Any new users not in the custom domain will be added to the user pool, but not automatically confirmed.

------
#### [ Node.js ]

```
export const handler = async (event, context, callback) => {
  // Set the user pool autoConfirmUser flag after validating the email domain
  event.response.autoConfirmUser = false;

  // Split the email address so we can compare domains
  var address = event.request.userAttributes.email.split("@");

  // This example uses a custom attribute "custom:domain"
  if (event.request.userAttributes.hasOwnProperty("custom:domain")) {
    if (event.request.userAttributes["custom:domain"] === address[1]) {
      event.response.autoConfirmUser = true;
    }
  }

  // Return to Amazon Cognito
  callback(null, event);
};
```

------
#### [ Python ]

```
def lambda_handler(event, context):
    # It sets the user pool autoConfirmUser flag after validating the email domain
    event['response']['autoConfirmUser'] = False

    # Split the email address so we can compare domains
    address = event['request']['userAttributes']['email'].split('@')

    # This example uses a custom attribute 'custom:domain'
    if 'custom:domain' in event['request']['userAttributes']:
        if event['request']['userAttributes']['custom:domain'] == address[1]:
            event['response']['autoConfirmUser'] = True

    # Return to Amazon Cognito
    return event
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "email": "testuser@example.com",
            "custom:domain": "example.com"
        }
    },
    "response": {}
}
```

------

## Pre sign-up example: Auto-confirm and auto-verify all users
<a name="aws-lambda-triggers-pre-registration-example-2"></a>

This example confirms all users and sets the user's `email` and `phone_number` attributes to verified if the attribute is present. Also, if aliasing is enabled, aliases will be created for `phone_number` and `email` when auto-verify is set. 

**Note**  
If an alias with the same phone number already exists, the alias will be moved to the new user, and the previous user's `phone_number` will be marked as unverified. The same is true for email addresses. To prevent this from happening, you can use the user pools [ListUsers API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html) to see if there is an existing user who is already using the new user's phone number or email address as an alias.

------
#### [ Node.js ]

```
exports.handler = (event, context, callback) => {
  // Confirm the user
  event.response.autoConfirmUser = true;

  // Set the email as verified if it is in the request
  if (event.request.userAttributes.hasOwnProperty("email")) {
    event.response.autoVerifyEmail = true;
  }

  // Set the phone number as verified if it is in the request
  if (event.request.userAttributes.hasOwnProperty("phone_number")) {
    event.response.autoVerifyPhone = true;
  }

  // Return to Amazon Cognito
  callback(null, event);
};
```

------
#### [ Python ]

```
def lambda_handler(event, context):
    # Confirm the user
    event['response']['autoConfirmUser'] = True

    # Set the email as verified if it is in the request
    if 'email' in event['request']['userAttributes']:
        event['response']['autoVerifyEmail'] = True

    # Set the phone number as verified if it is in the request
    if 'phone_number' in event['request']['userAttributes']:
        event['response']['autoVerifyPhone'] = True

    # Return to Amazon Cognito
    return event
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
  "request": {
    "userAttributes": {
      "email": "user@example.com",
      "phone_number": "+12065550100"
    }
  },
  "response": {}
}
```

------

## Pre sign-up example: Deny sign-up if user name has fewer than five characters
<a name="aws-lambda-triggers-pre-registration-example-3"></a>

This example checks the length of the user name in a sign-up request. The example returns an error if the user has entered a name less than five characters long.

------
#### [ Node.js ]

```
export const handler = (event, context, callback) => {
    // Impose a condition that the minimum length of the username is 5 is imposed on all user pools.
    if (event.userName.length < 5) {
        var error = new Error("Cannot register users with username less than the minimum length of 5");
        // Return error to Amazon Cognito
        callback(error, event);
    }
    // Return to Amazon Cognito
    callback(null, event);
};
```

------
#### [ Python ]

```
def lambda_handler(event, context):
    if len(event['userName']) < 5:
        raise Exception("Cannot register users with username less than the minimum length of 5")
    # Return to Amazon Cognito
    return event
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
  "userName": "rroe",
  "response": {}
}
```

------

# Post confirmation Lambda trigger
<a name="user-pool-lambda-post-confirmation"></a>

Amazon Cognito invokes this trigger after a signed-up user confirms their user account. In your post confirmation Lambda function, you can send custom messages or add custom API requests. For example, you can query an external system and populate additional attributes to the user. Amazon Cognito invokes this trigger only for user who sign up in your user pool, not for user accounts that you create with your administrator credentials.

The request contains the current attributes for the confirmed user. Your user pool invokes your post confirmation function on [ConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html), [AdminConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminConfirmSignUp.html), and [ConfirmForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html). This trigger also runs when users confirm sign-up or password reset in [managed login](cognito-user-pools-managed-login.md).

**Topics**
+ [

## Post confirmation Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-post-confirmation)
+ [

## Post confirmation example
](#aws-lambda-triggers-post-confirmation-example)

## Post confirmation Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-post-confirmation"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
            "userAttributes": {
                "string": "string",
                . . .
            },
            "clientMetadata": {
            	"string": "string",
            	. . .
            }
        },
    "response": {}
}
```

------

### Post confirmation request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-post-confirmation-request"></a>

**userAttributes**  
One or more key-value pairs representing user attributes.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the post confirmation trigger. You can pass this data to your Lambda function by using the ClientMetadata parameter in the following API actions: [AdminConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminConfirmSignUp.html), [ConfirmForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html), [ConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html), and [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html).

### Post confirmation response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-post-confirmation-response"></a>

No additional return information is expected in the response.

## Post confirmation example
<a name="aws-lambda-triggers-post-confirmation-example"></a>

This example Lambda function sends a confirmation email message to your user using Amazon SES. For more information see [Amazon Simple Email Service Developer Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/). 

------
#### [ Node.js ]

```
// Import required AWS SDK clients and commands for Node.js. Note that this requires
// the `@aws-sdk/client-ses` module to be either bundled with this code or included
// as a Lambda layer.
import { SES, SendEmailCommand } from "@aws-sdk/client-ses";
const ses = new SES();

const handler = async (event) => {
  if (event.request.userAttributes.email) {
    await sendTheEmail(
      event.request.userAttributes.email,
      `Congratulations ${event.userName}, you have been confirmed.`,
    );
  }
  return event;
};

const sendTheEmail = async (to, body) => {
  const eParams = {
    Destination: {
      ToAddresses: [to],
    },
    Message: {
      Body: {
        Text: {
          Data: body,
        },
      },
      Subject: {
        Data: "Cognito Identity Provider registration completed",
      },
    },
    // Replace source_email with your SES validated email address
    Source: "<source_email>",
  };
  try {
    await ses.send(new SendEmailCommand(eParams));
  } catch (err) {
    console.log(err);
  }
};

export { handler };
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "email": "user@example.com",
            "email_verified": true
        }
    },
    "response": {}
}
```

------

# Pre authentication Lambda trigger
<a name="user-pool-lambda-pre-authentication"></a>

Amazon Cognito invokes this trigger when a user attempts to sign in so that you can create custom validation that performs preparatory actions. For example, you can deny the authentication request or record session data to an external system.

**Note**  
This Lambda trigger doesn't activate when a user doesn't exist unless the `PreventUserExistenceErrors` setting of a user pool app client is set to `ENABLED`. Renewal of an existing authentication session also doesn't activate this trigger.

**Topics**
+ [

## Flow overview
](#user-pool-lambda-pre-authentication-1)
+ [

## Pre authentication Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-pre-auth)
+ [

## Pre authentication example
](#aws-lambda-triggers-pre-authentication-example)

## Flow overview
<a name="user-pool-lambda-pre-authentication-1"></a>

![\[Pre authentication Lambda trigger - client flow\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/lambda-pre-authentication-1.png)


The request includes client validation data from the `ClientMetadata` values that your app passes to the user pool `InitiateAuth` and `AdminInitiateAuth` API operations.

For more information, see [An example authentication session](authentication.md#amazon-cognito-user-pools-authentication-flow).

## Pre authentication Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-auth"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        },
        "validationData": {
            "string": "string",
            . . .
        },
        "userNotFound": boolean
    },
    "response": {}
}
```

------

### Pre authentication request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-auth-request"></a>

**userAttributes**  
One or more name-value pairs that represent user attributes.

**userNotFound**  
When you set `PreventUserExistenceErrors` to `ENABLED` for your user pool client, Amazon Cognito populates this Boolean.

**validationData**  
One or more key-value pairs that contain the validation data in the user's sign-in request. To pass this data to your Lambda function, use the ClientMetadata parameter in the [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) API actions.

### Pre authentication response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-auth-response"></a>

Amazon Cognito doesn't process any added information that your function returns in the response. Your function can return an error to reject the sign-in attempt, or use API operations to query and modify your resources.

## Pre authentication example
<a name="aws-lambda-triggers-pre-authentication-example"></a>

This example function prevents users from signing in to your user pool with a specific app client. Because the pre authentication Lambda function doesn't invoke when your user has an existing session, this function only prevents *new* sessions with the app client ID that you want to block.

------
#### [ Node.js ]

```
const handler = async (event) => {
  if (
    event.callerContext.clientId === "user-pool-app-client-id-to-be-blocked"
  ) {
    throw new Error("Cannot authenticate users from this user pool app client");
  }

  return event;
};

export { handler };
```

------
#### [ Python ]

```
def lambda_handler(event, context):
    if event['callerContext']['clientId'] == "<user pool app client id to be blocked>":
        raise Exception("Cannot authenticate users from this user pool app client")

    # Return to Amazon Cognito
    return event
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample: 

------
#### [ JSON ]

```
{
    "callerContext": {
        "clientId": "<user pool app client id to be blocked>"
    },
    "response": {}
}
```

------

# Post authentication Lambda trigger
<a name="user-pool-lambda-post-authentication"></a>

The post authentication trigger doesn't change the authentication flow for a user. Amazon Cognito invokes this Lambda after authentication is complete, before a user has received tokens. Add a post authentication trigger when you want to add custom post-processing of authentication events, for example logging or user profile adjustments that will be reflected on the next sign-in.

A post authentication Lambda that doesn't return the request body to Amazon Cognito can still cause authentication to fail to complete. For more information, see [Things to know about Lambda triggers](cognito-user-pools-working-with-lambda-triggers.md#important-lambda-considerations).

**Topics**
+ [

## Authentication flow overview
](#user-pool-lambda-post-authentication-1)
+ [

## Post authentication Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-post-auth)
+ [

## Post authentication example
](#aws-lambda-triggers-post-authentication-example)

## Authentication flow overview
<a name="user-pool-lambda-post-authentication-1"></a>

![\[Post authentication Lambda trigger - client flow\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/lambda-post-authentication-1.png)


For more information, see [An example authentication session](authentication.md#amazon-cognito-user-pools-authentication-flow).

## Post authentication Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-post-auth"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
             "string": "string",
             . . .
         },
         "newDeviceUsed": boolean,
         "clientMetadata": {
             "string": "string",
             . . .
            }
        },
    "response": {}
}
```

------

### Post authentication request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-post-auth-request"></a>

**newDeviceUsed**  
This flag indicates if the user has signed in on a new device. Amazon Cognito only sets this flag if the remembered devices value of the user pool is `Always` or `User Opt-In`.

**userAttributes**  
One or more name-value pairs representing user attributes.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the post authentication trigger. To pass this data to your Lambda function, you can use the ClientMetadata parameter in the [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API actions. Amazon Cognito doesn't include data from the ClientMetadata parameter in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations in the request that it passes to the post authentication function.

### Post authentication response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-post-auth-response"></a>

Amazon Cognito doesn't expect any additional return information in the response. Your function can use API operations to query and modify your resources, or record event metadata to an external system.

## Post authentication example
<a name="aws-lambda-triggers-post-authentication-example"></a>

This post authentication sample Lambda function sends data from a successful sign-in to CloudWatch Logs.

------
#### [ Node.js ]

```
const handler = async (event) => {
  // Send post authentication data to Amazon CloudWatch logs
  console.log("Authentication successful");
  console.log("Trigger function =", event.triggerSource);
  console.log("User pool = ", event.userPoolId);
  console.log("App client ID = ", event.callerContext.clientId);
  console.log("User ID = ", event.userName);

  return event;
};

export { handler };
```

------
#### [ Python ]

```
import os
def lambda_handler(event, context):

    # Send post authentication data to Cloudwatch logs
    print ("Authentication successful")
    print ("Trigger function =", event['triggerSource'])
    print ("User pool = ", event['userPoolId'])
    print ("App client ID = ", event['callerContext']['clientId'])
    print ("User ID = ", event['userName'])

    # Return to Amazon Cognito
    return event
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
  "triggerSource": "testTrigger",
  "userPoolId": "testPool",
  "userName": "testName",
  "callerContext": {
      "clientId": "12345"
  },
  "response": {}
}
```

------

# Inbound federation Lambda trigger
<a name="user-pool-lambda-inbound-federation"></a>

The inbound federation trigger transforms federated user attributes during the authentication process with external identity providers. When users authenticate through configured identity providers, this trigger allows you to modify responses from external SAML and OIDC providers by intercepting and transforming data in the authentication process, providing programmatic control over how Amazon Cognito user pools handle federated users and their attributes.

Use this trigger to add, override, or suppress attributes before creating new users or updating existing federated user profiles. This trigger receives raw identity provider attributes as input and returns modified attributes that Amazon Cognito applies to the user profile.

**Topics**
+ [

## Flow overview
](#cognito-user-pools-lambda-trigger-inbound-federation-flow)
+ [

## Inbound federation Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-inbound-federation)
+ [

## Inbound federation example: Group membership management
](#aws-lambda-triggers-inbound-federation-example-groups)
+ [

## Inbound federation example: Truncate large attributes
](#aws-lambda-triggers-inbound-federation-example-truncate)
+ [

## Inbound federation example: Logging federation events
](#aws-lambda-triggers-inbound-federation-example-logging)

## Flow overview
<a name="cognito-user-pools-lambda-trigger-inbound-federation-flow"></a>

When a user authenticates with an external identity provider, Amazon Cognito invokes the inbound federation trigger before creating or updating the user profile. The trigger receives the raw attributes from the identity provider and can transform them before Amazon Cognito stores them. This flow occurs for both new federated users and existing users who sign in again through federation.

![\[Inbound federation Lambda trigger flow\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/lambda-inbound-federation.png)


## Inbound federation Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-inbound-federation"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "version": "string",
    "triggerSource": "InboundFederation_ExternalProvider",
    "region": AWSRegion,
    "userPoolId": "string",
    "userName": "string",
    "callerContext": {
        "awsSdkVersion": "string",
        "clientId": "string"
    },
    "request": {
        "providerName": "string",
        "providerType": "string",
        "attributes": {
            "tokenResponse": {
                "access_token": "string",
                "token_type": "string",
                "expires_in": "string"
            },
            "idToken": {
                "sub": "string",
                "email": "string",
                "email_verified": "string"
            },
            "userInfo": {
                "email": "string",
                "given_name": "string",
                "family_name": "string"
            },
            "samlResponse": {
                "string": "string"
            }
        }
    },
    "response": {
        "userAttributesToMap": {
            "string": "string"
        }
    }
}
```

------

### Inbound federation request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-inbound-federation-request"></a>

**providerName**  
The name of the external identity provider.

**providerType**  
The type of the external identity provider. Valid values: `OIDC`, `SAML`, `Facebook`, `Google`, `SignInWithApple`, `LoginWithAmazon`.

**attributes**  
The raw attributes received from the identity provider before processing. The structure varies based on provider type.

**attributes.tokenResponse**  
OAuth token response data from the `/token` endpoint. Available for OIDC and social providers only. Contains `access_token`, `id_token`, `refresh_token`, `token_type`, `expires_in`, and `scope`.

**attributes.idToken**  
Decoded and validated ID token JWT claims. Available for OIDC and social providers only. Contains verified user identity information including `sub` (unique user identifier), `email`, `name`, `iss` (issuer), `aud` (audience), `exp` (expiration), and `iat` (issued time).

**attributes.userInfo**  
Extended user profile information from the UserInfo endpoint. Available for OIDC and social providers only. Contains detailed profile attributes such as `given_name`, `family_name`, `picture`, `address`, and other provider-specific fields. May be empty if the IdP doesn't support the UserInfo endpoint or if the endpoint call fails.

**attributes.samlResponse**  
SAML assertion attributes. Available for SAML providers only. Contains attributes from the SAML response.

### Inbound federation response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-inbound-federation-response"></a>

**userAttributesToMap**  
The user attributes to apply to the user profile.

**Important**  
You must include ALL user attributes you want to retain in the response, including attributes you are not modifying. Any attributes not included in the `userAttributesToMap` response will be dropped and not stored in the user profile. This applies to both modified and unmodified attributes.

**Empty response behavior**  
If you return an empty object `{}` for `userAttributesToMap`, all original attributes from the identity provider are retained unchanged. This acts as a no-op, as if the Lambda function was never executed. This is different from omitting attributes, which drops them.

**Provider-specific attributes**  
The structure of `request.attributes` varies based on the `providerType`. OIDC and social providers include `tokenResponse`, `idToken`, and `userInfo` objects. SAML providers include only the `samlResponse` object.

## Inbound federation example: Group membership management
<a name="aws-lambda-triggers-inbound-federation-example-groups"></a>

This example shows how to map federated identity provider groups to Amazon Cognito user pools groups. This function extracts group membership from the federated response and automatically adds users to corresponding Amazon Cognito groups, eliminating the need for post-authentication triggers.

------
#### [ Node.js ]

```
exports.handler = async (event) => {
    const { providerType, attributes } = event.request;
    
    // Extract user attributes based on provider type
    let userAttributesFromIdp = {};
    if (providerType === 'SAML') {
        userAttributesFromIdp = attributes.samlResponse || {};
    } else {
        // For OIDC and Social providers, merge userInfo and idToken
        userAttributesFromIdp = {
            ...(attributes.userInfo || {}),
            ...(attributes.idToken || {})
        };
    }
    
    // Extract groups from federated response
    const federatedGroups = userAttributesFromIdp.groups?.split(',') || [];
    
    // Map federated groups to Cognito groups
    const groupMapping = {
        'Domain Admins': 'Administrators',
        'Engineering': 'Developers',
        'Sales': 'SalesTeam'
    };
    
    // Filter to only in-scope groups
    const mappedGroups = federatedGroups
        .map(group => groupMapping[group.trim()])
        .filter(group => group); // Remove undefined values
    
    // Pass through attributes with mapped groups as custom attribute
    const attributesToMap = {
        ...userAttributesFromIdp,
        'custom:user_groups': mappedGroups.join(',')
    };
    
    // Remove original groups attribute
    delete attributesToMap.groups;
    
    event.response.userAttributesToMap = attributesToMap;
    return event;
};
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
    "userPoolId": "us-east-1_XXXXXXXXX",
    "request": {
        "providerName": "CorporateAD",
        "providerType": "SAML",
        "attributes": {
            "samlResponse": {
                "email": "jane.smith@company.com",
                "given_name": "Jane",
                "family_name": "Smith",
                "groups": "Engineering,Domain Admins",
                "department": "Engineering"
            }
        }
    },
    "response": {
        "userAttributesToMap": {}
    }
}
```

------

## Inbound federation example: Truncate large attributes
<a name="aws-lambda-triggers-inbound-federation-example-truncate"></a>

This example shows how to truncate attribute values that exceed Amazon Cognito's storage limits. This function checks each attribute from the identity provider. If an attribute value exceeds 2048 characters, it truncates the value and adds ellipsis to indicate truncation. All other attributes pass through unchanged.

------
#### [ Node.js ]

```
exports.handler = async (event) => {
    const MAX_ATTRIBUTE_LENGTH = 2048;
    
    // Get the identity provider attributes based on provider type
    const { providerType, attributes } = event.request;
    let idpAttributes = {};
    
    if (providerType === 'SAML') {
        idpAttributes = attributes.samlResponse || {};
    } else {
        // For OIDC and Social providers, merge userInfo and idToken
        idpAttributes = {
            ...(attributes.userInfo || {}),
            ...(attributes.idToken || {})
        };
    }
    
    const userAttributes = {};
    
    // Process each attribute
    for (const [key, value] of Object.entries(idpAttributes)) {
        if (typeof value === 'string' && value.length > MAX_ATTRIBUTE_LENGTH) {
            // Truncate the value and add ellipsis
            userAttributes[key] = value.substring(0, MAX_ATTRIBUTE_LENGTH - 3) + '...';
            console.log(`Truncated attribute ${key} from ${value.length} to ${userAttributes[key].length} characters`);
        } else {
            // Keep the original value
            userAttributes[key] = value;
        }
    }
    
    // Return the modified attributes
    event.response.userAttributesToMap = userAttributes;
    return event;
};
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
    "version": "string",
    "triggerSource": "InboundFederation_ExternalProvider",
    "region": "us-east-1",
    "userPoolId": "us-east-1_XXXXXXXXX",
    "userName": "ExampleProvider_12345",
    "callerContext": {
        "awsSdkVersion": "string",
        "clientId": "string"
    },
    "request": {
        "providerName": "ExampleProvider",
        "providerType": "OIDC",
        "attributes": {
            "tokenResponse": {
                "access_token": "abcDE...",
                "token_type": "Bearer",
                "expires_in": "3600"
            },
            "idToken": {
                "sub": "12345",
                "email": "user@example.com"
            },
            "userInfo": {
                "email": "user@example.com",
                "given_name": "Example",
                "family_name": "User",
                "bio": "This is a very long biography that contains more than 2048 characters..."
            }
        }
    },
    "response": {
        "userAttributesToMap": {}
    }
}
```

------

## Inbound federation example: Logging federation events
<a name="aws-lambda-triggers-inbound-federation-example-logging"></a>

This example shows how to log federated authentication events for monitoring and debugging. This example function captures detailed information about federated users and their attributes, providing visibility into the authentication process.

------
#### [ Node.js ]

```
exports.handler = async (event) => {
    const { providerName, providerType, attributes } = event.request;
    
    // Extract user attributes based on provider type
    let userAttributesFromIdp = {};
    if (providerType === 'SAML') {
        userAttributesFromIdp = attributes.samlResponse || {};
    } else {
        // For OIDC and Social providers, merge userInfo and idToken
        userAttributesFromIdp = {
            ...(attributes.userInfo || {}),
            ...(attributes.idToken || {})
        };
    }
    
    // Log federated authentication details
    console.log(JSON.stringify({
        timestamp: new Date().toISOString(),
        providerName,
        providerType,
        userEmail: userAttributesFromIdp.email,
        attributeCount: Object.keys(userAttributesFromIdp).length,
        attributes: userAttributesFromIdp
    }));
    
    // Pass through all attributes unchanged
    event.response.userAttributesToMap = userAttributesFromIdp;
    return event;
};
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
    "version": "string",
    "triggerSource": "InboundFederation_ExternalProvider",
    "region": "us-east-1",
    "userPoolId": "us-east-1_XXXXXXXXX",
    "userName": "CorporateAD_john.doe",
    "callerContext": {
        "awsSdkVersion": "string",
        "clientId": "string"
    },
    "request": {
        "providerName": "CorporateAD",
        "providerType": "SAML",
        "attributes": {
            "samlResponse": {
                "email": "john.doe@company.com",
                "given_name": "John",
                "family_name": "Doe",
                "department": "Engineering",
                "employee_id": "EMP12345"
            }
        }
    },
    "response": {
        "userAttributesToMap": {}
    }
}
```

------

Expected CloudWatch Logs output:

------
#### [ JSON ]

```
{
    "timestamp": "2025-01-14T21:17:40.153Z",
    "providerName": "CorporateAD",
    "providerType": "SAML",
    "userEmail": "john.doe@company.com",
    "attributeCount": 5,
    "attributes": {
        "email": "john.doe@company.com",
        "given_name": "John",
        "family_name": "Doe",
        "department": "Engineering",
        "employee_id": "EMP12345"
    }
}
```

------

# Custom authentication challenge Lambda triggers
<a name="user-pool-lambda-challenge"></a>

As you build out your authentication flows for your Amazon Cognito user pool, you might find that you want to extend your authentication model beyond the built-in flows. One common use case for the custom challenge triggers is to implement additional security checks beyond username, password, and multi-factor authentication (MFA). A custom challenge is any question and response you can generate in a Lambda-supported programming language. For example, you might want to require users to solve a CAPTCHA or answer a security question before being allowed to authenticate. Another potential need is to integrate with specialized authentication factors or devices. Or you might have already developed software that authenticates users with a hardware security key or a biometric device. The definition of authentication success for a custom challenge is whatever answer your Lambda function accepts as correct: a fixed string, for example, or a satisfactory response from an external API.

You can start authentication with your custom challenge and control the authentication process entirely, or you can perform username-password authentication before your application receives your custom challenge.

The custom authentication challenge Lambda trigger:

**[Defines](user-pool-lambda-define-auth-challenge.md)**  
Initiates a challenge sequence. Determines whether you want to initiate a new challenge, mark authentication as complete, or halt the authentication attempt.

**[Creates](user-pool-lambda-create-auth-challenge.md)**  
Issues the question to your application that the user must answer. This function might present a security question or a link to a CAPTCHA that your application should display to your user.

**[Verifies](user-pool-lambda-verify-auth-challenge-response.md)**  
Knows the expected answer and compares it to the answer your application provides in the challenge response. The function might call the API of your CAPTCHA service to retrieve the expected results of your user's attempted solution.

These three Lambda functions chain together to present an authentication mechanism that is completely within your control and of your own design. Because custom authentication requires application logic in your client and in the Lambda functions, you can't process custom authentication within managed login. This authentication system requires additional developer effort. Your application must perform the authentication flow with the user pools API and handle the resulting challenge with a custom-built login interface that renders the question at the center of the custom authentication challenge.

![\[Challenge Lambda triggers\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/lambda-challenges.png)


For more information about implementing custom authentication, see [Custom authentication flow and challenges](amazon-cognito-user-pools-authentication-flow-methods.md#Custom-authentication-flow-and-challenges)

Authentication between the API operations [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html), and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) or [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html). In this flow, a user authenticates by answering successive challenges until authentication either fails or the user is issued tokens. A challenge response might be a new challenge. In this case, your application responds as many times as necessary to new challenges. Successful authentication happens when the define auth challenge function analyzes the results so far, determines all challenges have been answered, and returns `IssueTokens`.

**Topics**
+ [

## SRP authentication in custom challenge flows
](#user-pool-lambda-challenge-srp-authentication)
+ [

# Define Auth challenge Lambda trigger
](user-pool-lambda-define-auth-challenge.md)
+ [

# Create Auth challenge Lambda trigger
](user-pool-lambda-create-auth-challenge.md)
+ [

# Verify Auth challenge response Lambda trigger
](user-pool-lambda-verify-auth-challenge-response.md)

## SRP authentication in custom challenge flows
<a name="user-pool-lambda-challenge-srp-authentication"></a>

You can have Amazon Cognito verify user passwords before it issues your custom challenges. Any Lambda triggers associated in the Authentication category of [request-rate quotas](quotas.md#category_operations.title) will run when you perform SRP authentication in a custom challenge flow. Here is an overview of the process:

1. Your app initiates sign-in by calling `InitiateAuth` or `AdminInitiateAuth` with the `AuthParameters` map. Parameters must include `CHALLENGE_NAME: SRP_A,` and values for `SRP_A` and `USERNAME`.

1. Amazon Cognito invokes your define auth challenge Lambda trigger with an initial session that contains `challengeName: SRP_A` and `challengeResult: true`.

1. After receiving those inputs, your Lambda function responds with `challengeName: PASSWORD_VERIFIER`, `issueTokens: false`, `failAuthentication: false`.

1. If the password verification succeeds, Amazon Cognito invokes your Lambda function again with a new session containing `challengeName: PASSWORD_VERIFIER` and `challengeResult: true`.

1. To initiate your custom challenges, your Lambda function responds with `challengeName: CUSTOM_CHALLENGE`, `issueTokens: false`, and `failAuthentication: false`. If you don't want to start your custom auth flow with password verification, you can initiate sign-in with the `AuthParameters` map including `CHALLENGE_NAME: CUSTOM_CHALLENGE`.

1. The challenge loop repeats until all challenges are answered.

The following is an example of a starting `InitiateAuth` request that precedes custom authentication with an SRP flow.

```
{
    "AuthFlow": "CUSTOM_AUTH",
    "ClientId": "1example23456789",
    "AuthParameters": {
        "CHALLENGE_NAME": "SRP_A",
        "USERNAME": "testuser",
        "SRP_A": "[SRP_A]",
        "SECRET_HASH": "[secret hash]"
    }
}
```

### Password reset in the custom authentication SRP flow
<a name="user-pool-lambda-challenge-force-password-change"></a>

When users are in `FORCE_CHANGE_PASSWORD` status, your custom authentication flow must integrate the password change step while maintaining the integrity of your authentication challenges. Amazon Cognito invokes your [define auth challenge](user-pool-lambda-define-auth-challenge.md) Lambda trigger during the `NEW_PASSWORD_REQUIRED` challenge. In this scenario, a user signing in with a custom challenge flow and SRP authentication can set a new password if they are in a password-reset state.

When users are in the `RESET_REQUIRED` or `FORCE_CHANGE_PASSWORD` status, they must [respond](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html#API_RespondToAuthChallenge_RequestParameters) to a `NEW_PASSWORD_REQUIRED` challenge with a `NEW_PASSWORD`. In custom authentication with SRP, Amazon Cognito returns a `NEW_PASSWORD_REQUIRED` challenge after users complete the SRP `PASSWORD_VERIFIER` challenge. Your define auth challenge trigger receives both challenge results in the `session` array, and can proceed with additional custom challenges after the user successfully changes their password.

Your define auth challenge Lambda trigger must manage the challenge sequence through SRP authentication, password reset, and subsequent custom challenges. The trigger receives an array of completed challenges in the `session` parameter, including both `PASSWORD_VERIFIER` and `NEW_PASSWORD_REQUIRED` results. For an example implementation, see [Define Auth challenge example](user-pool-lambda-define-auth-challenge.md#aws-lambda-triggers-define-auth-challenge-example).

#### Authentication flow steps
<a name="user-pool-lambda-challenge-password-flow-steps"></a>

For users who need to verify their password before custom challenges, the process follows these steps:

1. Your app initiates sign-in by calling `InitiateAuth` or `AdminInitiateAuth` with the `AuthParameters` map. Parameters must include `CHALLENGE_NAME: SRP_A`, and values for `SRP_A` and `USERNAME`.

1. Amazon Cognito invokes your define auth challenge Lambda trigger with an initial session that contains `challengeName: SRP_A` and `challengeResult: true`.

1. After receiving those inputs, your Lambda function responds with `challengeName: PASSWORD_VERIFIER`, `issueTokens: false`, `failAuthentication: false`.

1. If the password verification succeeds, one of two things happens:  
**For users in normal status:**  
Amazon Cognito invokes your Lambda function again with a new session containing `challengeName: PASSWORD_VERIFIER` and `challengeResult: true`.  
To initiate your custom challenges, your Lambda function responds with `challengeName: CUSTOM_CHALLENGE`, `issueTokens: false`, and `failAuthentication: false`.  
**For users in `RESET_REQUIRED` or `FORCE_CHANGE_PASSWORD` status:**  
Amazon Cognito invokes your Lambda function with a session containing `challengeName: PASSWORD_VERIFIER` and `challengeResult: true`.  
Your Lambda function should respond with `challengeName: NEW_PASSWORD_REQUIRED`, `issueTokens: false`, and `failAuthentication: false`.  
After successful password change, Amazon Cognito invokes your Lambda function with a session containing both the `PASSWORD_VERIFIER` and `NEW_PASSWORD_REQUIRED` results.  
To initiate your custom challenges, your Lambda function responds with `challengeName: CUSTOM_CHALLENGE`, `issueTokens: false`, and `failAuthentication: false`.

1. The challenge loop repeats until all challenges are answered.

If you don't want to start your custom auth flow with password verification, you can initiate sign-in with the `AuthParameters` map including `CHALLENGE_NAME: CUSTOM_CHALLENGE`.

#### Session management
<a name="user-pool-lambda-challenge-session-management"></a>

The authentication flow maintains session continuity through a series of session IDs and challenge results. Each challenge response generates a new session ID to prevent session reuse errors, which is particularly important for multi-factor authentication flows.

Challenge results are stored chronologically in the session array that your Lambda triggers receive. For users in `FORCE_CHANGE_PASSWORD` status, the session array contains:

1. `session[0]` - Initial `SRP_A` challenge

1. `session[1]` - `PASSWORD_VERIFIER` result

1. `session[2]` - `NEW_PASSWORD_REQUIRED` result

1. Subsequent elements - Results of additional custom challenges

#### Example authentication flow
<a name="user-pool-lambda-challenge-example-flow"></a>

The following example demonstrates a complete custom authentication flow for a user in `FORCE_CHANGE_PASSWORD` status who must complete both password change and a custom CAPTCHA challenge.

1. **InitiateAuth request**

   ```
   {
       "AuthFlow": "CUSTOM_AUTH",
       "ClientId": "1example23456789",
       "AuthParameters": {
           "CHALLENGE_NAME": "SRP_A",
           "USERNAME": "testuser",
           "SRP_A": "[SRP_A]"
       }
   }
   ```

1. **InitiateAuth response**

   ```
   {
       "ChallengeName": "PASSWORD_VERIFIER",
       "ChallengeParameters": {
           "USER_ID_FOR_SRP": "testuser"
       },
       "Session": "[session_id_1]"
   }
   ```

1. **RespondToAuthChallenge request with `PASSWORD_VERIFIER`**

   ```
   {
       "ChallengeName": "PASSWORD_VERIFIER",
       "ClientId": "1example23456789",
       "ChallengeResponses": {
           "PASSWORD_CLAIM_SIGNATURE": "[claim_signature]",
           "PASSWORD_CLAIM_SECRET_BLOCK": "[secret_block]",
           "TIMESTAMP": "[timestamp]",
           "USERNAME": "testuser"
       },
       "Session": "[session_id_1]"
   }
   ```

1. **RespondToAuthChallenge response with `NEW_PASSWORD_REQUIRED` challenge**

   ```
   {
       "ChallengeName": "NEW_PASSWORD_REQUIRED",
       "ChallengeParameters": {},
       "Session": "[session_id_2]"
   }
   ```

1. **RespondToAuthChallenge request with `NEW_PASSWORD_REQUIRED`**

   ```
   {
       "ChallengeName": "NEW_PASSWORD_REQUIRED",
       "ClientId": "1example23456789",
       "ChallengeResponses": {
           "NEW_PASSWORD": "[password]",
           "USERNAME": "testuser"
       },
       "Session": "[session_id_2]"
   }
   ```

1. **RespondToAuthChallenge response with CAPTCHA custom challenge**

   ```
   {
       "ChallengeName": "CUSTOM_CHALLENGE",
       "ChallengeParameters": {
           "captchaUrl": "url/123.jpg"
       },
       "Session": "[session_id_3]"
   }
   ```

1. **RespondToAuthChallenge request with answer to CAPTCHA custom challenge**

   ```
   {
       "ChallengeName": "CUSTOM_CHALLENGE",
       "ClientId": "1example23456789",
       "ChallengeResponses": {
           "ANSWER": "123",
           "USERNAME": "testuser"
       },
       "Session": "[session_id_3]"
   }
   ```

**6. Final success response**

```
{
    "AuthenticationResult": {
        "AccessToken": "eyJra456defEXAMPLE",
        "ExpiresIn": 3600,
        "IdToken": "eyJra789ghiEXAMPLE",
        "RefreshToken": "eyJjd123abcEXAMPLE",
        "TokenType": "Bearer"
    },
    "ChallengeParameters": {}
}
```

# Define Auth challenge Lambda trigger
<a name="user-pool-lambda-define-auth-challenge"></a>

The define auth challenge trigger is a Lambda function that maintains the challenge sequence in a custom authentication flow. It declares success or failure of the challenge sequence, and sets the next challenge if the sequence isn't yet complete.

![\[Challenge Lambda triggers\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/lambda-challenges1.png)


**Define auth challenge**  
 Amazon Cognito invokes this trigger to initiate the [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).

The request for this Lambda trigger contains `session`. The `session` parameter is an array that contains all of the challenges that are presented to the user in the current authentication process. The request also includes the corresponding result. The `session` array stores challenge details (`ChallengeResult`) in chronological order. The challenge `session[0]` represents the first challenge that the user receives.

**Topics**
+ [

## Define Auth challenge Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-define-auth-challenge)
+ [

## Define Auth challenge example
](#aws-lambda-triggers-define-auth-challenge-example)

## Define Auth challenge Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-define-auth-challenge"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
                . . .
        },
        "session": [
            ChallengeResult,
            . . .
        ],
        "clientMetadata": {
            "string": "string",
            . . .
        },
        "userNotFound": boolean
    },
    "response": {
        "challengeName": "string",
        "issueTokens": boolean,
        "failAuthentication": boolean
    }
}
```

------

### Define Auth challenge request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-define-auth-challenge-request"></a>

 When Amazon Cognito invokes your Lambda function, Amazon Cognito provides the following parameters:

**userAttributes**  
One or more name-value pairs that represent user attributes.

**userNotFound**  
A Boolean that Amazon Cognito populates when `PreventUserExistenceErrors` is set to `ENABLED` for your user pool client. A value of `true` means that the user id (username, email address, and other details) did not match any existing users. When `PreventUserExistenceErrors` is set to `ENABLED`, the service doesn't inform the app of nonexistent users. We recommend that your Lambda functions maintain the same user experience and account for latency. This way, the caller can't detect different behavior when the user exists or doesn’t exist.

**session**  
An array of `ChallengeResult` elements. Each contains the following elements:    
**challengeName**  
One of the following challenge types: `CUSTOM_CHALLENGE`, `SRP_A`, `PASSWORD_VERIFIER`, `SMS_MFA`, `EMAIL_OTP`, `SOFTWARE_TOKEN_MFA`, `DEVICE_SRP_AUTH`, `DEVICE_PASSWORD_VERIFIER`, or `ADMIN_NO_SRP_AUTH`.  
When your define auth challenge function issues a `PASSWORD_VERIFIER` challenge for a user who has set up multifactor authentication, Amazon Cognito follows it up with an `SMS_MFA`, `EMAIL_OTP`, or `SOFTWARE_TOKEN_MFA` challenge. These are the prompts for a multi-factor authentication code. In your function, include handling for input events from `SMS_MFA`, `EMAIL_OTP`, and `SOFTWARE_TOKEN_MFA` challenges. You don't need to invoke any MFA challenges in your define auth challenge function.  
When your function is determining whether a user has successfully authenticated and you should issue them tokens, always check `challengeName` in your define auth challenge function and verify that it matches the expected value.  
**challengeResult**  
Set to `true` if the user successfully completed the challenge, or `false` otherwise.  
**challengeMetadata**  
Your name for the custom challenge. Used only if `challengeName` is `CUSTOM_CHALLENGE`.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the define auth challenge trigger. To pass this data to your Lambda function, you can use the `ClientMetadata` parameter in the [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API operations. The request that invokes the define auth challenge function doesn't include data passed in the ClientMetadata parameter in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations.

### Define Auth challenge response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-define-auth-challenge-response"></a>

In the response, you can return the next stage of the authentication process.

**challengeName**  
A string that contains the name of the next challenge. If you want to present a new challenge to your user, specify the challenge name here.

**issueTokens**  
If you determine that the user has completed the authentication challenges sufficiently, set to `true`. If the user has not met the challenges sufficiently, set to `false`.

**failAuthentication**  
If you want to end the current authentication process, set to `true`. To continue the current authentication process, set to `false`.

## Define Auth challenge example
<a name="aws-lambda-triggers-define-auth-challenge-example"></a>

This example defines a series of challenges for authentication and issues tokens only if the user has completed all of the challenges successfully. When users complete SRP authentication with the `SRP_A` and `PASSWORD_VERIFIER` challenges, this function passes them a `CUSTOM_CHALLENGE` that invokes the create auth challenge trigger. In combination with our [create auth challenge example](user-pool-lambda-create-auth-challenge.md#aws-lambda-triggers-create-auth-challenge-example), this sequence delivers a CAPTCHA challenge for challenge three and a security question for challenge four.

After the user solves the CAPTCHA and answers the security question, this function confirms that your user pool can issue tokens. SRP authentication isn't required; you can also set the CAPTCHA and security question as challenges one & two. In the case where your define auth challenge function doesn't declare SRP challenges, your users' success is determined entirely by their responses to your custom prompts.

------
#### [ Node.js ]

```
const handler = async (event) => {
  if (
    event.request.session.length === 1 &&
    event.request.session[0].challengeName === "SRP_A"
  ) {
    event.response.issueTokens = false;
    event.response.failAuthentication = false;
    event.response.challengeName = "PASSWORD_VERIFIER";
  } else if (
    event.request.session.length === 2 &&
    event.request.session[1].challengeName === "PASSWORD_VERIFIER" &&
    event.request.session[1].challengeResult === true
  ) {
    event.response.issueTokens = false;
    event.response.failAuthentication = false;
    event.response.challengeName = "CUSTOM_CHALLENGE";
  } else if (
    event.request.session.length === 3 &&
    event.request.session[2].challengeName === "CUSTOM_CHALLENGE" &&
    event.request.session[2].challengeResult === true
  ) {
    event.response.issueTokens = false;
    event.response.failAuthentication = false;
    event.response.challengeName = "CUSTOM_CHALLENGE";
  } else if (
    event.request.session.length === 4 &&
    event.request.session[3].challengeName === "CUSTOM_CHALLENGE" &&
    event.request.session[3].challengeResult === true
  ) {
    event.response.issueTokens = true;
    event.response.failAuthentication = false;
  } else {
    event.response.issueTokens = false;
    event.response.failAuthentication = true;
  }

  return event;
};

export { handler };
```

------

# Create Auth challenge Lambda trigger
<a name="user-pool-lambda-create-auth-challenge"></a>

The create auth challenge trigger is a Lambda function that has the details of each challenge declared by the define auth challenge trigger. It processes the challenge name declared by the define auth challenge trigger and returns a `publicChallengeParameters` that your application must present to the user. This function then provides your user pool with the answer to the challenge, `privateChallengeParameters`, that your user pool passes to the verify auth challenge trigger. Where your define auth challenge trigger manages the challenge sequence, your create auth challenge trigger manages the challenge contents.

![\[Challenge Lambda triggers\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/lambda-challenges2.png)


**Create auth challenge**  
Amazon Cognito invokes this trigger after **Define Auth Challenge** if a custom challenge has been specified as part of the **Define Auth Challenge** trigger. It creates a [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).

This Lambda trigger is invoked to create a challenge to present to the user. The request for this Lambda trigger includes the `challengeName` and `session`. The `challengeName` is a string and is the name of the next challenge to the user. The value of this attribute is set in the Define Auth Challenge Lambda trigger.

The challenge loop will repeat until all challenges are answered.

**Topics**
+ [

## Create Auth challenge Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-create-auth-challenge)
+ [

## Create Auth challenge example
](#aws-lambda-triggers-create-auth-challenge-example)

## Create Auth challenge Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-create-auth-challenge"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        },
        "challengeName": "string",
        "session": [
            ChallengeResult,
            . . .
        ],
        "clientMetadata": {
            "string": "string",
            . . .
        },
        "userNotFound": boolean
    },
    "response": {
        "publicChallengeParameters": {
            "string": "string",
            . . .
        },
        "privateChallengeParameters": {
            "string": "string",
            . . .
        },
        "challengeMetadata": "string"
    }
}
```

------

### Create Auth challenge request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-create-auth-challenge-request"></a>

**userAttributes**  
One or more name-value pairs representing user attributes.

**userNotFound**  
This boolean is populated when `PreventUserExistenceErrors` is set to `ENABLED` for your User Pool client.

**challengeName**  
The name of the new challenge.

**session**  
The session element is an array of `ChallengeResult` elements, each of which contains the following elements:    
**challengeName**  
The challenge type. One of: `"CUSTOM_CHALLENGE"`, `"PASSWORD_VERIFIER"`, `"SMS_MFA"`, `"DEVICE_SRP_AUTH"`, `"DEVICE_PASSWORD_VERIFIER"`, `"NEW_PASSWORD_REQUIRED"`, or `"ADMIN_NO_SRP_AUTH"`.   
**challengeResult**  
Set to `true` if the user successfully completed the challenge, or `false` otherwise.  
**challengeMetadata**  
Your name for the custom challenge. Used only if `challengeName` is `"CUSTOM_CHALLENGE"`.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the create auth challenge trigger. You can use the ClientMetadata parameter in the [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API actions to pass this data to your Lambda function. The request that invokes the create auth challenge function does not include data passed in the ClientMetadata parameter in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations.

### Create Auth challenge response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-create-auth-challenge-response"></a>

**publicChallengeParameters**  
One or more key-value pairs for the client app to use in the challenge to be presented to the user. This parameter should contain all of the necessary information to present the challenge to the user accurately.

**privateChallengeParameters**  
This parameter is only used by the Verify Auth Challenge Response Lambda trigger. This parameter should contain all of the information that is required to validate the user's response to the challenge. In other words, the `publicChallengeParameters` parameter contains the question that is presented to the user and `privateChallengeParameters` contains the valid answers for the question.

**challengeMetadata**  
Your name for the custom challenge, if this is a custom challenge.

## Create Auth challenge example
<a name="aws-lambda-triggers-create-auth-challenge-example"></a>

This function has two custom challenges that correspond to the challenge sequence in our [define auth challenge example](user-pool-lambda-define-auth-challenge.md#aws-lambda-triggers-define-auth-challenge-example). The first two challenges are SRP authentication. For the third challenge, this function returns a CAPTCHA URL to your application in the challenge response. Your application renders the CAPTCHA at the given URL and returns the user's input. The URL for the CAPTCHA image is added to the public challenge parameters as "`captchaUrl`", and the expected answer is added to the private challenge parameters.

For the fourth challenge, this function returns a security question. Your application renders the question and prompts the user for their answer. After users solve both custom challenges, the define auth challenge trigger confirms that your user pool can issue tokens.

------
#### [ Node.js ]

```
const handler = async (event) => {
  if (event.request.challengeName !== "CUSTOM_CHALLENGE") {
    return event;
  }

  if (event.request.session.length === 2) {
    event.response.publicChallengeParameters = {};
    event.response.privateChallengeParameters = {};
    event.response.publicChallengeParameters.captchaUrl = "url/123.jpg";
    event.response.privateChallengeParameters.answer = "5";
  }

  if (event.request.session.length === 3) {
    event.response.publicChallengeParameters = {};
    event.response.privateChallengeParameters = {};
    event.response.publicChallengeParameters.securityQuestion =
      "Who is your favorite team mascot?";
    event.response.privateChallengeParameters.answer = "Peccy";
  }

  return event;
};

export { handler };
```

------

# Verify Auth challenge response Lambda trigger
<a name="user-pool-lambda-verify-auth-challenge-response"></a>

The verify auth challenge trigger is a Lambda function that compares a user's provided response to a known answer. This function tells your user pool whether the user answered the challenge correctly. When the verify auth challenge trigger responds with an `answerCorrect` of `true`, the authentication sequence can continue.

![\[Challenge Lambda triggers\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/lambda-challenges3.png)


**Verify auth challenge response**  
Amazon Cognito invokes this trigger to verify if the response from the user for a custom Auth Challenge is valid or not. It is part of a user pool [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).

The request for this trigger contains the `privateChallengeParameters` and `challengeAnswer` parameters. The Create Auth Challenge Lambda trigger returns `privateChallengeParameters` values, and contains the expected response from the user. The `challengeAnswer` parameter contains the user's response for the challenge.

The response contains the `answerCorrect` attribute. If the user successfully completes the challenge, Amazon Cognito sets the attribute value to `true`. If the user doesn't successfully complete the challenge, Amazon Cognito sets the value to `false`.

The challenge loop repeats until the users answers all challenges.

**Topics**
+ [

## Verify Auth challenge Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-verify-auth-challenge)
+ [

## Verify Auth challenge response example
](#aws-lambda-triggers-verify-auth-challenge-response-example)

## Verify Auth challenge Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-verify-auth-challenge"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        },
        "privateChallengeParameters": {
            "string": "string",
            . . .
        },
        "challengeAnswer": "string",
        "clientMetadata": {
            "string": "string",
            . . .
        },
        "userNotFound": boolean
    },
    "response": {
        "answerCorrect": boolean
    }
}
```

------

### Verify Auth challenge request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-verify-auth-challenge-request"></a>

**userAttributes**  
This parameter contains one or more name-value pairs that represent user attributes.

**userNotFound**  
When Amazon Cognito sets `PreventUserExistenceErrors` to `ENABLED` for your user pool client, Amazon Cognito populates this Boolean .

**privateChallengeParameters**  
This parameter comes from the Create Auth Challenge trigger. To determine whether the user passed a challenge, Amazon Cognito compares the parameters against a user’s **challengeAnswer**.  
This parameter contains all of the information that is required to validate the user's response to the challenge. That information includes the question that Amazon Cognito presents to the user (`publicChallengeParameters`), and the valid answers for the question (`privateChallengeParameters`). Only the Verify Auth Challenge Response Lambda trigger uses this parameter. 

**challengeAnswer**  
This parameter value is the answer from the user's response to the challenge.

**clientMetadata**  
This parameter contains one or more key-value pairs that you can provide as custom input to the Lambda function for the verify auth challenge trigger. To pass this data to your Lambda function, use the ClientMetadata parameter in the [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API operations. Amazon Cognito doesn't include data from the ClientMetadata parameter in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations in the request that it passes to the verify auth challenge function.

### Verify Auth challenge response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-verify-auth-challenge-response"></a>

**answerCorrect**  
If the user successfully completes the challenge, Amazon Cognito sets this parameter to `true`. If the user doesn't successfully complete the challenge, Amazon Cognito sets the parameter to `false`. 

## Verify Auth challenge response example
<a name="aws-lambda-triggers-verify-auth-challenge-response-example"></a>

This verify auth challenge function checks whether the user's response to a challenge matches the expected response. The user's answer is defined by input from your application and the preferred answer is defined by `privateChallengeParameters.answer` in the response from the [create auth challenge trigger response](user-pool-lambda-create-auth-challenge.md#aws-lambda-triggers-create-auth-challenge-example). Both the correct answer and the given answer are part of the input event to this function.

In this example, if the user's response matches the expected response, Amazon Cognito sets the `answerCorrect` parameter to `true`.

------
#### [ Node.js ]

```
const handler = async (event) => {
  if (
    event.request.privateChallengeParameters.answer ===
    event.request.challengeAnswer
  ) {
    event.response.answerCorrect = true;
  } else {
    event.response.answerCorrect = false;
  }

  return event;
};

export { handler };
```

------

# Pre token generation Lambda trigger
<a name="user-pool-lambda-pre-token-generation"></a>

Because Amazon Cognito invokes this trigger before token generation, you can customize the claims in user pool tokens. With the **Basic features** of the version one or `V1_0` pre token generation trigger event, you can customize the identity (ID) token. In user pools with the Essentials or Plus feature plan, you can generate the version two or `V2_0` trigger event with access token customization, and the version three or `V3_0` trigger event with access token customization for machine-to-machine (M2M) client-credentials grants.

Amazon Cognito sends a `V1_0` event as a request to your function with data that it would write to the ID token. A `V2_0` or `V3_0` event is a single request with the data that Amazon Cognito would write to both the identity and access tokens. To customize both tokens, you must update your function to use trigger version two or three, and send data for both tokens in the same response.

Amazon Cognito applies version two event responses to access tokens from user authentication, where a human user has presented credentials to your user pool. Version three event responses apply to access tokens from user authentication and machine authentication, where automated systems authorize access token requests with app client secrets. Aside from the circumstances of the resulting access tokens, version two and three events are identical.

This Lambda trigger can add, remove, and modify some claims in identity and access tokens before Amazon Cognito issues them to your app. To use this feature, associate a Lambda function from the Amazon Cognito user pools console or update your user pool `LambdaConfig` through the AWS Command Line Interface (AWS CLI).

## Event versions
<a name="user-pool-lambda-pre-token-generation-event-versions"></a>

Your user pool can deliver different versions of a pre token generation trigger event to your Lambda function. A `V1_0` trigger delivers the parameters for modification of ID tokens. A `V2_0` or `V3_0` trigger delivers parameters for the following.

1. The functions of a `V1_0` trigger.

1. The ability to customize access tokens.

1. The ability to pass complex datatypes to ID and access token claim values:
   + String
   + Number
   + Boolean
   + Array of strings, numbers, booleans, or a combination of any of these
   + JSON

**Note**  
In the ID token, you can populate complex objects to the values of claims except for `phone_number_verified`, `email_verified`, `updated_at`, and `address`.

User pools deliver `V1_0` events by default. To configure your user pool to send a `V2_0` event, choose a **Trigger event version** of **Basic features \$1 access token customization for user identities** when you configure your trigger in the Amazon Cognito console. To produce `V3_0` events, choose ****Basic features \$1 access token customization for user and machine identities****. You can also set the value of `LambdaVersion` in the [LambdaConfig](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html#CognitoUserPools-UpdateUserPool-request-LambdaConfig) parameters in an [UpdateUserPool ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) or [CreateUserPool ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) API request. Event versions one, two, and three are available in the **Essentials** and **Plus** feature plans. M2M operations for version three events have a pricing structure separate from the monthly active users (MAU) formula. For more information, see [Amazon Cognito Pricing](https://aws.amazon.com/cognito/pricing/).

**Note**  
User pools that were operational with the **Advanced security features** option on or before November 22, 2024 at 1800 GMT, and that remain on the **Lite** feature tier have access to event versions one and two of the pre token generation trigger. User pools in this legacy tier *without* advanced security features have access to event version one. Version three is *only* available in Essentials and Plus.

## Claims and scopes reference
<a name="user-pool-lambda-pre-token-generation-excluded-claims"></a>

Amazon Cognito limits the claims and scopes that you can add, modify, or suppress in access and identity tokens. The following table describes the claims that your Lambda function can and can't modify, and the trigger event parameters that affect the presence or value of the claim.


| Claim | Default token type | Can add? | Can modify? | Can suppress? | Event parameter - add or modify | Event parameter - suppress | Identity type | Event version | 
| --- | --- | --- | --- | --- | --- | --- | --- | --- | 
| Any claim not in the user pool token schema | None | Yes | Yes | N/A | claimsToAddOrOverride | claimsToSuppress | User, machine[1](#cognito-pretoken-machine-ids-tier-note) | All[2](#cognito-pretoken-id-access-versions-note) | 
| scope | Access | Yes | Yes | Yes | scopesToAdd | scopesToSuppress | User, machine[1](#cognito-pretoken-machine-ids-tier-note) | v2\$10, v3\$10 | 
| cognito:groups | ID, Access | Yes | Yes | Yes | groupsToOverride | claimsToSuppress | User | All[2](#cognito-pretoken-id-access-versions-note) | 
| cognito:preferred\$1role | ID | Yes | Yes | Yes | preferredRole | claimsToSuppress[3](#cognito-pretoken-suppress-groups-note) | User | All | 
| cognito:roles | ID | Yes | Yes | Yes | iamRolesToOverride | claimsToSuppress[3](#cognito-pretoken-suppress-groups-note) | User | All | 
| cognito:username | ID | No | No | No | N/A | N/A | User | N/A | 
| Any other claim with a cognito: prefix | None | No | No | No | N/A | N/A | N/A | N/A | 
| username | Access | No | No | No | N/A | N/A | User | v2\$10, v3\$10 | 
| sub | ID, Access | No | No | No | N/A | N/A | User | N/A | 
| standard OIDC attribute | ID | Yes | Yes | Yes | claimsToAddOrOverride | claimsToSuppress | User | All | 
| custom: attribute | ID | Yes | Yes | Yes | claimsToAddOrOverride | claimsToSuppress | User | All | 
| dev: attribute | ID | No | No | Yes | N/A | claimsToSuppress | User | All | 
| identities | ID | No | No | No | N/A | N/A | User | N/A | 
| aud[4](#cognito-pretoken-aud-note) | ID | No | No | No | N/A | N/A | User, machine | N/A | 
| client\$1id | Access | No | No | No | N/A | N/A | User, machine | N/A | 
| event\$1id | Access | No | No | No | N/A | N/A | User, machine | N/A | 
| device\$1key | Access | No | No | No | N/A | N/A | User | N/A | 
| version | Access | No | No | No | N/A | N/A | User, machine | N/A | 
| acr | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| amr | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| at\$1hash | ID | No | No | No | N/A | N/A | User, machine | N/A | 
| auth\$1time | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| azp | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| exp | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| iat | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| iss | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| jti | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| nbf | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| nonce | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| origin\$1jti | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 
| token\$1use | ID, Access | No | No | No | N/A | N/A | User, machine | N/A | 

 1 Access tokens for machine identities are only available with `v3_0` of the trigger input event. Event version three is only available in the **Essentials** and **Plus** feature tiers. User pools on the **Lite** tier can receive `v1_0` events. User pools on the **Lite** tier with advanced security features can receive `v1_0` and `v2_0` events.

2 Configure your pre token generation trigger to event version `v1_0` for ID token only, `v2_0` for ID and access token, `v3_0` for ID and access token with capabilities for machine identities.

 3 To suppress the `cognito:preferred_role` and `cognito:roles` claims, add `cognito:groups` to `claimsToSuppress`.

 4 You can add an `aud` claim to access tokens, but its value must match the app client ID of the current session. You can derive the client ID in the request event from `event.callerContext.clientId`.

## Customizing the identity token
<a name="user-pool-lambda-pre-token-generation-idtoken"></a>

With all event versions of the pre token generation Lambda trigger, you can customize the content of an identity (ID) token from your user pool. The ID token provides user attributes from a trusted identity source for sign-in to a web or mobile app. For more information about ID tokens, see [Understanding the identity (ID) token](amazon-cognito-user-pools-using-the-id-token.md).

The uses of the pre token generation Lambda trigger with an ID token include the following.
+ Make a change at runtime to the IAM role that your user requests from an identity pool.
+ Add user attributes from an external source.
+ Add or replace existing user attribute values.
+ Suppress disclosure of user attributes that, because of your user's authorized scopes and the read access to attributes that you granted to your app client, would otherwise be passed to your app.

## Customizing the access token
<a name="user-pool-lambda-pre-token-generation-accesstoken"></a>

With event versions two and three of the pre token generation Lambda trigger, you can customize the content of an access token from your user pool. The access token authorizes users to retrieve information from access-protected resources like Amazon Cognito token-authorized API operations and third-party APIs. For machine-to-machine (M2M) authorization with a client credentials grant, Amazon Cognito only invokes the pre token generation trigger when your user pool is configured for a version three (`V3_0`) event. For more information about access tokens, see [Understanding the access token](amazon-cognito-user-pools-using-the-access-token.md).

The uses of the pre token generation Lambda trigger with an access token include the following.
+ Add or suppress scopes in the `scope` claim. For example, you can add scopes to an access token that resulted from Amazon Cognito user pools API authentication, which only assigns the scope `aws.cognito.signin.user.admin`.
+ Change a user's membership in user pool groups.
+ Add claims that aren't already present in an Amazon Cognito access token.
+ Suppress disclosure of claims that would otherwise be passed to your app.

To support access customization in your user pool, you must configure the user pool to generate an updated version of the trigger request. Update your user pool as shown in the following procedure.

------
#### [ AWS Management Console ]

**To support access token customization in a pre token generation Lambda trigger**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home), and then choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Extensions** menu and locate **Lambda triggers**.

1. Add or edit a **Pre token generation trigger**.

1. Choose a Lambda function under **Assign Lambda function**. 

1. Choose a **Trigger event version** of **Basic features \$1 access token customization for user identities** or **Basic features \$1 access token customization for user and machine identities**. This setting updates the request parameters that Amazon Cognito sends to your function to include fields for access token customization.

------
#### [ User pools API ]

**To support access token customization in a pre token generation Lambda trigger**

Generate a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request. You must specify a value for all parameters that you don't want set to a default value. For more information, see [Updating user pool and app client configuration](cognito-user-pool-updating.md).

Include the following content in the `LambdaVersion` parameter of your request. A `LambdaVersion` value of `V2_0` causes your user pool to add parameters for, and apply changes to, access tokens. A `LambdaVersion` value of `V3_0` produces the same event as `V2_0`, but causes your user pool to *also* apply changes to M2M access tokens. To invoke a specific function version, use a Lambda function ARN with a function version as the value of `LambdaArn`.

```
"PreTokenGenerationConfig": { 
   "LambdaArn": "arn:aws:lambda:us-west-2:123456789012:function:MyFunction",
   "LambdaVersion": "V3_0"
},
```

------

**Client metadata for machine-to-machine (M2M) client credentials**  
You can pass [client metadata](cognito-user-pools-working-with-lambda-triggers.md#working-with-lambda-trigger-client-metadata) in M2M requests. Client metadata is additional information from a user or application environment that can contribute to the outcomes of a [Pre token generation Lambda trigger](#user-pool-lambda-pre-token-generation). In authentication operations with a user principal, you can pass client metadata to the pre token generation trigger in the body of [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API requests. Because applications conduct the flow for generation of access tokens for M2M with direct requests to the [Token endpoint](token-endpoint.md), they have a different model. In the POST body of token requests for client credentials, pass an `aws_client_metadata` parameter with the client metadata object URL-encoded (`x-www-form-urlencoded`) to string. For an example request, see [Client credentials with basic authorizationClient credentials with POST body authorization](token-endpoint.md#exchanging-client-credentials-for-an-access-token-in-request-body). The following is an example parameter that passes the key-value pairs `{"environment": "dev", "language": "en-US"}`.

```
aws_client_metadata=%7B%22environment%22%3A%20%22dev%22,%20%22language%22%3A%20%22en-US%22%7D
```

**More resources**
+ [How to customize access tokens in Amazon Cognito user pools](https://aws.amazon.com/blogs/security/how-to-customize-access-tokens-in-amazon-cognito-user-pools/)

**Topics**
+ [

## Event versions
](#user-pool-lambda-pre-token-generation-event-versions)
+ [

## Claims and scopes reference
](#user-pool-lambda-pre-token-generation-excluded-claims)
+ [

## Customizing the identity token
](#user-pool-lambda-pre-token-generation-idtoken)
+ [

## Customizing the access token
](#user-pool-lambda-pre-token-generation-accesstoken)
+ [

## Pre token generation Lambda trigger sources
](#user-pool-lambda-pre-token-generation-trigger-source)
+ [

## Pre token generation Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-pre-token-generation)
+ [

## Pre token trigger event version two example: Add and suppress claims, scopes, and groups
](#aws-lambda-triggers-pre-token-generation-example-version-2-overview)
+ [

## Pre token generation event version two example: Add claims with complex objects
](#aws-lambda-triggers-pre-token-generation-example-version-2-complex-objects)
+ [

## Pre token generation event version one example: Add a new claim and suppress an existing claim
](#aws-lambda-triggers-pre-token-generation-version-1-add-claim)
+ [

## Pre token generation event version one example: Modify the user's group membership
](#aws-lambda-triggers-pre-token-generation-version-1-change-group)

## Pre token generation Lambda trigger sources
<a name="user-pool-lambda-pre-token-generation-trigger-source"></a>


| triggerSource value | Event | 
| --- | --- | 
| TokenGeneration\$1HostedAuth | Called during authentication from the Amazon Cognito managed login sign-in page. | 
| TokenGeneration\$1Authentication | Called after user authentication flows have completed. | 
| TokenGeneration\$1NewPasswordChallenge | Called after the user is created by an admin. This flow is invoked when the user has to change a temporary password. | 
| TokenGeneration\$1ClientCredentials | Called after an M2M client credentials grant. Your user pool only sends this event when your event version is V3\$10. | 
| TokenGeneration\$1AuthenticateDevice | Called at the end of the authentication of a user device. | 
| TokenGeneration\$1RefreshTokens | Called when a user tries to refresh the identity and access tokens. | 

## Pre token generation Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-token-generation"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests. When you add a pre token generation Lambda trigger to your user pool, you can choose a trigger version. This version determines whether Amazon Cognito passes a request to your Lambda function with additional parameters for access-token customization.

------
#### [ Version one ]

The version one token can set group membership, IAM roles, and new claims in ID tokens. Group membership overrides also apply to the `cognito:groups` claim in access tokens.

```
{
    "request": {
        "userAttributes": {"string": "string"},
        "groupConfiguration": {
                "groupsToOverride": [
                    "string",
                    "string"
                ],
                "iamRolesToOverride": [
                    "string",
                    "string"
                ],
                "preferredRole": "string"
        },
        "clientMetadata": {"string": "string"}
    },
    "response": {
        "claimsOverrideDetails": {
            "claimsToAddOrOverride": {"string": "string"},
            "claimsToSuppress": [
                "string",
                "string"
            ],
            "groupOverrideDetails": {
                "groupsToOverride": [
                    "string",
                    "string"
                ],
                "iamRolesToOverride": [
                    "string",
                    "string"
                ],
                "preferredRole": "string"
            }
        }
    }
}
```

------
#### [ Versions two and three ]

The versions two and three request events add fields that customize the access token. User pools apply changes from version three events to access tokens for machine identities. These versions also add support for complex `claimsToOverride` data types in the response object. Your Lambda function can return the following types of data in the value of `claimsToOverride`:
+ String
+ Number
+ Boolean
+ Array of strings, numbers, booleans, or a combination of any of these
+ JSON

```
{
    "request": {
        "userAttributes": {
            "string": "string"
        },
        "scopes": ["string", "string"],
        "groupConfiguration": {
            "groupsToOverride": ["string", "string"],
            "iamRolesToOverride": ["string", "string"],
            "preferredRole": "string"
        },
        "clientMetadata": {
            "string": "string"
        }
    },
    "response": {
        "claimsAndScopeOverrideDetails": {
            "idTokenGeneration": {
                "claimsToAddOrOverride": {
                    "string": [accepted datatype]
                },
                "claimsToSuppress": ["string", "string"]
            },
            "accessTokenGeneration": {
                "claimsToAddOrOverride": {
                    "string": [accepted datatype]
                },
                "claimsToSuppress": ["string", "string"],
                "scopesToAdd": ["string", "string"],
                "scopesToSuppress": ["string", "string"]
            },
            "groupOverrideDetails": {
                "groupsToOverride": ["string", "string"],
                "iamRolesToOverride": ["string", "string"],
                "preferredRole": "string"
            }
        }
    }
}
```

------

### Pre token generation request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-token-generation-request"></a>


| Name | Description | Minimum trigger event version | 
| --- |--- |--- |
| userAttributes |  The attributes of your user's profile in your user pool.  | 1 | 
| groupConfiguration |  The input object that contains the current group configuration. The object includes `groupsToOverride`, `iamRolesToOverride`, and `preferredRole`.  | 1 | 
| groupsToOverride |  The [user pool groups](cognito-user-pools-user-groups.md#cognito-user-pools-user-groups.title) that your user is a member of.  | 1 | 
| iamRolesToOverride |  You can associate a user pool group with an AWS Identity and Access Management (IAM) role. This element is a list of all IAM roles from the groups that your user is a member of.  | 1 | 
| preferredRole |  You can set a [precedence](cognito-user-pools-user-groups.md#assigning-precedence-values-to-groups.title) for user pool groups. This element contains the name of the IAM role from the group with the highest precendence in the `groupsToOverride` element.  | 1 | 
| clientMetadata |  One or more key-value pairs that you can specify and provide as custom input to the Lambda function for the pre token generation trigger. To pass this data to your Lambda function, use the ClientMetadata parameter in the [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API operations. Amazon Cognito doesn't include data from the `ClientMetadata` parameter in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations in the request that it passes to the pre token generation function.  | 1 | 
| scopes |  Access token scopes. The scopes that are present in an access token are the user pool standard and custom scopes that your user requested, and that you authorized your app client to issue.  | 2 | 

### Pre token generation response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-pre-token-generation-response"></a>


| Name | Description | Minimum trigger event version | 
| --- |--- |--- |
| claimsOverrideDetails | A container for all elements in a V1\$10 trigger event. | 1 | 
| claimsAndScopeOverrideDetails |  A container for all elements in a `V2_0` or `V3_0` trigger event.  | 2 | 
| idTokenGeneration |  The claims that you want to override, add, or suppress in your user’s ID token. This parent to ID token customization values appears only in event version 2 and above, but the child elements appear in version 1 events.  | 2 | 
| accessTokenGeneration |  The claims and scopes that you want to override, add, or suppress in your user’s access token. This parent to access token customization values appears only in event version 2 and above.  | 2 | 
| claimsToAddOrOverride |  A map of one or more claims and their values that you want to add or modify. For group-related claims, use `groupOverrideDetails` instead. In event version 2 and above, this element appears under both `accessTokenGeneration` and `idTokenGeneration`.  | 1[*](#cognito-pretoken-complex-objects-note) | 
| claimsToSuppress |  A list of claims that you want Amazon Cognito to suppress. If your function both suppresses and replaces a claim value, then Amazon Cognito suppresses the claim. In event version 2 and above, this element appears under both `accessTokenGeneration` and `idTokenGeneration`.  | 1 | 
| groupOverrideDetails |  The output object that contains the current group configuration. The object includes `groupsToOverride`, `iamRolesToOverride`, and `preferredRole`. Your function replaces the `groupOverrideDetails` object with the object that you provide. If you provide an empty or null object in the response, then Amazon Cognito suppresses the groups. To keep the existing group configuration the same, copy the value of the `groupConfiguration` object of the request to the `groupOverrideDetails` object in the response. Then pass it back to the service. Amazon Cognito ID and access tokens both contain the `cognito:groups` claim. Your `groupOverrideDetails` object replaces the `cognito:groups` claim in access tokens and ID tokens. Group overrides are the only changes to the access token that version 1 events can make.  | 1 | 
| scopesToAdd |  A list of scopes that you want to add to the `scope` claim in your user's access token. You can't add scope values that contain one or more blank-space characters.  | 2 | 
| scopesToSuppress |  A list of scopes that you want to remove from the `scope` claim in your user's access token.  | 2 | 

 \$1 Response objects to version one events can return strings. Response objects to version two and three events can return [complex objects](#user-pool-lambda-pre-token-generation-event-versions).

## Pre token trigger event version two example: Add and suppress claims, scopes, and groups
<a name="aws-lambda-triggers-pre-token-generation-example-version-2-overview"></a>

This example makes the following modifications to a user's tokens.

1. Sets their `family_name` as `Doe` in the ID token.

1. Prevents `email` and `phone_number` claims from appearing in the ID token.

1. Sets their ID token `cognito:roles` claim to `"arn:aws:iam::123456789012:role\/sns_callerA","arn:aws:iam::123456789012:role\/sns_callerC","arn:aws:iam::123456789012:role\/sns_callerB"`.

1. Sets their ID token `cognito:preferred_role` claim to `arn:aws:iam::123456789012:role/sns_caller`.

1. Adds the scopes `openid`, `email`, and `solar-system-data/asteroids.add` to the access token.

1. Suppresses the scope `phone_number` and `aws.cognito.signin.user.admin` from the access token. Removal of `phone_number` prevents retrieval of the user's phone number from `userInfo`. Removal of `aws.cognito.signin.user.admin` prevents API requests by the user to read and modify their own profile with the Amazon Cognito user pools API.
**Note**  
The removal of `phone_number` from scopes only prevents retrieval of a user's phone number if the remaining scopes in the access token include `openid` and at least one more standard scope. For more information, see [About scopes](cognito-user-pools-define-resource-servers.md#cognito-user-pools-define-resource-servers-about-scopes).

1. Sets their ID and access token `cognito:groups` claim to `"new-group-A","new-group-B","new-group-C"`.

------
#### [ JavaScript ]

```
export const handler = function(event, context) {
  event.response = {
    "claimsAndScopeOverrideDetails": {
      "idTokenGeneration": {
        "claimsToAddOrOverride": {
          "family_name": "Doe"
        },
        "claimsToSuppress": [
          "email",
          "phone_number"
        ]
      },
      "accessTokenGeneration": {
        "scopesToAdd": [
          "openid",
          "email",
          "solar-system-data/asteroids.add"
        ],
        "scopesToSuppress": [
          "phone_number",
          "aws.cognito.signin.user.admin"
        ]
      },
      "groupOverrideDetails": {
        "groupsToOverride": [
          "new-group-A",
          "new-group-B",
          "new-group-C"
        ],
        "iamRolesToOverride": [
          "arn:aws:iam::123456789012:role/new_roleA",
          "arn:aws:iam::123456789012:role/new_roleB",
          "arn:aws:iam::123456789012:role/new_roleC"
        ],
        "preferredRole": "arn:aws:iam::123456789012:role/new_role",
      }
    }
  };
  // Return to Amazon Cognito
  context.done(null, event);
};
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
    "version": "2",
    "triggerSource": "TokenGeneration_Authentication",
    "region": "us-east-1",
    "userPoolId": "us-east-1_EXAMPLE",
    "userName": "JaneDoe",
    "callerContext": {
        "awsSdkVersion": "aws-sdk-unknown-unknown",
        "clientId": "1example23456789"
    },
    "request": {
        "userAttributes": {
            "sub": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "cognito:user_status": "CONFIRMED",
            "email_verified": "true",
            "phone_number_verified": "true",
            "phone_number": "+12065551212",
            "family_name": "Zoe",
            "email": "Jane.Doe@example.com"
        },
        "groupConfiguration": {
            "groupsToOverride": ["group-1", "group-2", "group-3"],
            "iamRolesToOverride": ["arn:aws:iam::123456789012:role/sns_caller1", "arn:aws:iam::123456789012:role/sns_caller2", "arn:aws:iam::123456789012:role/sns_caller3"],
            "preferredRole": ["arn:aws:iam::123456789012:role/sns_caller"]
        },
        "scopes": [
            "aws.cognito.signin.user.admin", "openid", "email", "phone"
        ]
    },
    "response": {
        "claimsAndScopeOverrideDetails": []
    }
}
```

------

## Pre token generation event version two example: Add claims with complex objects
<a name="aws-lambda-triggers-pre-token-generation-example-version-2-complex-objects"></a>

This example makes the following modifications to a user's tokens.

1. Adds claims of number, string, boolean, and JSON types to the ID token. This is the only change that version two trigger events makes available to the ID token.

1. Adds claims of number, string, boolean, and JSON types to the access token.

1. Adds three scopes to the access token.

1. Suppresses the `email` claim in the ID and access tokens.

1. Suppresses the `aws.cognito.signin.user.admin` scope in the access token.

------
#### [ JavaScript ]

```
export const handler = function(event, context) {

    var scopes = ["MyAPI.read", "MyAPI.write", "MyAPI.admin"]
    var claims = {}
    claims["aud"]= event.callerContext.clientId;
    claims["booleanTest"] = false;
    claims["longTest"] = 9223372036854775807;
    claims["exponentTest"] = 1.7976931348623157E308;
    claims["ArrayTest"] = ["test", 9223372036854775807, 1.7976931348623157E308, true];
    claims["longStringTest"] = "\{\
        \"first_json_block\": \{\
            \"key_A\": \"value_A\",\
            \"key_B\": \"value_B\"\
        \},\
        \"second_json_block\": \{\
            \"key_C\": \{\
                \"subkey_D\": [\
                    \"value_D\",\
                    \"value_E\"\
                ],\
                \"subkey_F\": \"value_F\"\
            \},\
            \"key_G\": \"value_G\"\
        \}\
    \}";
    claims["jsonTest"] = {
    	"first_json_block": {
    		"key_A": "value_A",
    		"key_B": "value_B"
    	},
    	"second_json_block": {
    		"key_C": {
    			"subkey_D": [
    				"value_D",
    				"value_E"
    			],
    			"subkey_F": "value_F"
    		},
    		"key_G": "value_G"
    	}
    };
    event.response = {
        "claimsAndScopeOverrideDetails": {
            "idTokenGeneration": {
                "claimsToAddOrOverride": claims,
                "claimsToSuppress": ["email"]
            },
            "accessTokenGeneration": {
                "claimsToAddOrOverride": claims,
                "claimsToSuppress": ["email"],
                "scopesToAdd": scopes,
                "scopesToSuppress": ["aws.cognito.signin.user.admin"]
            }
        }
    };
    console.info("EVENT response\n" + JSON.stringify(event, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2))
    console.info("EVENT response size\n" + JSON.stringify(event, (_, v) => typeof v === 'bigint' ? v.toString() : v).length)
    // Return to Amazon Cognito
    context.done(null, event);
};
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
    "version": "2",
    "triggerSource": "TokenGeneration_HostedAuth",
    "region": "us-west-2",
    "userPoolId": "us-west-2_EXAMPLE",
    "userName": "JaneDoe",
    "callerContext": {
        "awsSdkVersion": "aws-sdk-unknown-unknown",
        "clientId": "1example23456789"
    },
    "request": {
        "userAttributes": {
            "sub": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "cognito:user_status": "CONFIRMED"
            "email_verified": "true",
            "phone_number_verified": "true",
            "phone_number": "+12065551212",
            "email": "Jane.Doe@example.com"
        },
        "groupConfiguration": {
            "groupsToOverride": ["group-1", "group-2", "group-3"],
            "iamRolesToOverride": ["arn:aws:iam::123456789012:role/sns_caller1"],
            "preferredRole": ["arn:aws:iam::123456789012:role/sns_caller1"]
        },
        "scopes": [
            "aws.cognito.signin.user.admin",
            "phone",
            "openid",
            "profile",
            "email"
        ]
    },
    "response": {
        "claimsAndScopeOverrideDetails": []
    }
}
```

------

## Pre token generation event version one example: Add a new claim and suppress an existing claim
<a name="aws-lambda-triggers-pre-token-generation-version-1-add-claim"></a>

This example uses a version 1 trigger event with a pre token generation Lambda function to add a new claim and suppresses an existing claim.

------
#### [ Node.js ]

```
const handler = async (event) => {
  event.response = {
    claimsOverrideDetails: {
      claimsToAddOrOverride: {
        my_first_attribute: "first_value",
        my_second_attribute: "second_value",
      },
      claimsToSuppress: ["email"],
    },
  };

  return event;
};

export { handler };
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample: Because the code example doesn't process any request parameters, you can use a test event with an empty request. For more information about common request parameters, see [User pool Lambda trigger event](cognito-user-pools-working-with-lambda-triggers.md#cognito-user-pools-lambda-trigger-event-parameter-shared).

------
#### [ JSON ]

```
{
  "request": {},
  "response": {}
}
```

------

## Pre token generation event version one example: Modify the user's group membership
<a name="aws-lambda-triggers-pre-token-generation-version-1-change-group"></a>

This example uses a version 1 trigger event with a pre token generation Lambda function to modify the user's group membership.

------
#### [ Node.js ]

```
const handler = async (event) => {
  event.response = {
    claimsOverrideDetails: {
      groupOverrideDetails: {
        groupsToOverride: ["group-A", "group-B", "group-C"],
        iamRolesToOverride: [
          "arn:aws:iam::XXXXXXXXXXXX:role/sns_callerA",
          "arn:aws:iam::XXXXXXXXX:role/sns_callerB",
          "arn:aws:iam::XXXXXXXXXX:role/sns_callerC",
        ],
        preferredRole: "arn:aws:iam::XXXXXXXXXXX:role/sns_caller",
      },
    },
  };

  return event;
};

export { handler };
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
  "request": {},
  "response": {}
}
```

------

# Migrate user Lambda trigger
<a name="user-pool-lambda-migrate-user"></a>

When a user doesn't exist in the user pool at sign-in with a password, or in the forgot-password flow, Amazon Cognito invokes this trigger. After the Lambda function returns successfully, Amazon Cognito creates the user in the user pool. For details on the authentication flow with the user migration Lambda trigger, see [Importing users with a user migration Lambda trigger](cognito-user-pools-import-using-lambda.md).

To migrate users from your existing user directory into Amazon Cognito user pools at sign-in, or during the forgot-password flow, use this Lambda trigger.

**Topics**
+ [

## Migrate user Lambda trigger sources
](#user-pool-lambda-migrate-user-trigger-source)
+ [

## Migrate user Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-user-migration)
+ [

## Example: Migrate a user with an existing password
](#aws-lambda-triggers-user-migration-example-1)

## Migrate user Lambda trigger sources
<a name="user-pool-lambda-migrate-user-trigger-source"></a>


| triggerSource value | Event | 
| --- | --- | 
| UserMigration\$1Authentication[1](#cognito-migrate-user-passwordless-note) | User migration at sign-in. | 
| UserMigration\$1ForgotPassword | User migration during forgot-password flow. | 

1 Amazon Cognito doesn't invoke this trigger when users authenticate with [passwordless sign-in](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless).

## Migrate user Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-user-migration"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "userName": "string",
    "request": {
        "password": "string",
        "validationData": {
            "string": "string",
            . . .
        },
        "clientMetadata": {
            "string": "string",
      	. . .
        }
    },
    "response": {
        "userAttributes": {
            "string": "string",
            . . .
        },
        "finalUserStatus": "string",
        "messageAction": "string",
        "desiredDeliveryMediums": [ "string", . . .],
        "forceAliasCreation": boolean,
        "enableSMSMFA": boolean
    }
}
```

------

### Migrate user request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-user-migration-request"></a>

**userName**  
The username that the user enters at sign-in.

**password**  
The password that the user enters at sign-in. Amazon Cognito doesn't send this value in a request that's initiated by a forgot-password flow.

**validationData**  
One or more key-value pairs that contain the validation data in the user's sign-in request. To pass this data to your Lambda function, you can use the ClientMetadata parameter in the [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) API actions.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the Lambda function for the migrate user trigger. To pass this data to your Lambda function, you can use the ClientMetadata parameter in the [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html) API actions.

### Migrate user response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-user-migration-response"></a>

**userAttributes**  
This field is required.   
This field must contain one or more name-value pairs that Amazon Cognito stores in the user profile in your user pool and uses as user attributes. You can include both standard and custom user attributes. Custom attributes require the `custom:` prefix to distinguish them from standard attributes. For more information, see [Custom attributes](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-custom-attributes.html).  
To reset their passwords in the forgot-password flow, a user must have either a verified email address or a verified phone number. Amazon Cognito sends a message containing a reset password code to the email address or phone number in the user attributes.     
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html)

**finalUserStatus**  
You can set this parameter to `CONFIRMED` to auto-confirm your users so that they can sign in with their previous passwords. When you set a user to `CONFIRMED`, they do not need to take additional action before they can sign in. If you don't set this attribute to `CONFIRMED`, it's set to `RESET_REQUIRED`.  
A `finalUserStatus` of `RESET_REQUIRED` means that the user must change their password immediately after migration at sign-in, and your client app must handle the `PasswordResetRequiredException` during the authentication flow.  
Amazon Cognito doesn't enforce the password strength policy that you configured for the user pool during migration using Lambda trigger. If the password doesn't meet the password policy that you configured, Amazon Cognito still accepts the password so that it can continue to migrate the user. To enforce password strength policy and reject passwords that don't meet the policy, validate the password strength in your code. Then, if the password doesn't meet the policy, set finalUserStatus to `RESET_REQUIRED`.

**messageAction**  
You can set this parameter to `SUPPRESS` to decline to send the welcome message that Amazon Cognito usually sends to new users. If your function doesn't return this parameter, Amazon Cognito sends the welcome message.

**desiredDeliveryMediums**  
You can set this parameter to `EMAIL` to send the welcome message by email, or `SMS` to send the welcome message by SMS. If your function doesn't return this parameter, Amazon Cognito sends the welcome message by SMS.

**forceAliasCreation**  
If you set this parameter to `TRUE` and the phone number or email address in the UserAttributes parameter already exists as an alias with a different user, the API call migrates the alias from the previous user to the newly created user. The previous user can no longer log in using that alias.  
If you set this parameter to `FALSE` and the alias exists, Amazon Cognito doesn't migrate the user and returns an error to the client app.  
If you don't return this parameter, Amazon Cognito assumes its value is "false".

**enableSMSMFA**  
Set this parameter to `true` to require that your migrated user complete SMS text message multi-factor authentication (MFA) to sign in. Your user pool must have MFA enabled. Your user's attributes in the request parameters must include a phone number, or else the migration of that user will fail.

## Example: Migrate a user with an existing password
<a name="aws-lambda-triggers-user-migration-example-1"></a>

This example Lambda function migrates the user with an existing password and suppresses the welcome message from Amazon Cognito.

------
#### [ Node.js ]

```
exports.handler = (event, context, callback) => {
  var user;

  if (event.triggerSource == "UserMigration_Authentication") {
    // authenticate the user with your existing user directory service
    user = authenticateUser(event.userName, event.request.password);
    if (user) {
      event.response.userAttributes = {
        email: user.emailAddress,
        email_verified: "true",
      };
      event.response.finalUserStatus = "CONFIRMED";
      event.response.messageAction = "SUPPRESS";
      context.succeed(event);
    } else {
      // Return error to Amazon Cognito
      callback("Bad password");
    }
  } else if (event.triggerSource == "UserMigration_ForgotPassword") {
    // Lookup the user in your existing user directory service
    user = lookupUser(event.userName);
    if (user) {
      event.response.userAttributes = {
        email: user.emailAddress,
        // required to enable password-reset code to be sent to user
        email_verified: "true",
      };
      event.response.messageAction = "SUPPRESS";
      context.succeed(event);
    } else {
      // Return error to Amazon Cognito
      callback("Bad password");
    }
  } else {
    // Return error to Amazon Cognito
    callback("Bad triggerSource " + event.triggerSource);
  }
};
```

------

# Custom message Lambda trigger
<a name="user-pool-lambda-custom-message"></a>

When you have an external standard for the email and SMS messages that you want to send to your users, or when you want to apply your own logic at runtime to the formatting of user messages, add a custom message trigger to your user pool. The custom message Lambda receives the contents of all email and SMS messages before your user pool sends them. Your Lambda function then has the opportunity to modify the message contents and subject.

Amazon Cognito invokes this trigger before it sends an email or phone verification message or a multi-factor authentication (MFA) code. You can customize the message dynamically with your custom message trigger.

The request includes `codeParameter`. This is a string that acts as a placeholder for the code that Amazon Cognito delivers to the user. Insert the `codeParameter` string into the message body where you want the verification code to appear. When Amazon Cognito receives this response, Amazon Cognito replaces the `codeParameter` string with the actual verification code. 

**Note**  
The input event for a custom message Lambda function with the `CustomMessage_AdminCreateUser` trigger source includes a username and verification code. Because an admin-created user must receive both their user name and code, the response from your function must include placeholder variables for the username and code. The placeholders for your message are the values of `request.usernameParameter` and `request.codeParameter`. These values are typically `{username}` and `{####}`; as a best practice, reference the input values instead of hardcoding the variable names.

**Topics**
+ [

## Custom message Lambda trigger sources
](#cognito-user-pools-lambda-trigger-syntax-custom-message-trigger-source)
+ [

## Custom message Lambda trigger parameters
](#cognito-user-pools-lambda-trigger-syntax-custom-message)
+ [

## Custom message for sign-up example
](#aws-lambda-triggers-custom-message-example)
+ [

## Custom message for admin create user example
](#aws-lambda-triggers-custom-message-admin-example)

## Custom message Lambda trigger sources
<a name="cognito-user-pools-lambda-trigger-syntax-custom-message-trigger-source"></a>


| triggerSource value | Event | 
| --- | --- | 
| CustomMessage\$1SignUp | Custom message – To send the confirmation code post sign-up. | 
| CustomMessage\$1AdminCreateUser | Custom message – To send the temporary password to a new user. | 
| CustomMessage\$1ResendCode | Custom message – To resend the confirmation code to an existing user. | 
| CustomMessage\$1ForgotPassword | Custom message – To send the confirmation code for Forgot Password request. | 
| CustomMessage\$1UpdateUserAttribute | Custom message – When a user's email or phone number is changed, this trigger sends a verification code automatically to the user. Cannot be used for other attributes. | 
| CustomMessage\$1VerifyUserAttribute | Custom message – This trigger sends a verification code to the user when they manually request it for a new email or phone number. | 
| CustomMessage\$1Authentication | Custom message – To send MFA code during authentication. | 

## Custom message Lambda trigger parameters
<a name="cognito-user-pools-lambda-trigger-syntax-custom-message"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        }
        "codeParameter": "####",
        "usernameParameter": "string",
        "clientMetadata": {
            "string": "string",
            . . .
        }
    },
    "response": {
        "smsMessage": "string",
        "emailMessage": "string",
        "emailSubject": "string"
    }
}
```

------

### Custom message request parameters
<a name="cognito-user-pools-lambda-trigger-syntax-custom-message-request"></a>

**userAttributes**  
One or more name-value pairs representing user attributes.

**codeParameter**  
A string for you to use as the placeholder for the verification code in the custom message.

**usernameParameter**  
The user name. Amazon Cognito includes this parameter in requests that result from admin-created users.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the custom message trigger. The request that invokes a custom message function doesn't include data passed in the ClientMetadata parameter in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations. To pass this data to your Lambda function, you can use the ClientMetadata parameter in the following API actions:  
+  [AdminResetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html) 
+  [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) 
+  [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html)
+  [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html)
+  [GetUserAttributeVerificationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html)
+  [ResendConfirmationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html)
+  [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html)
+  [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html)

### Custom message response parameters
<a name="cognito-user-pools-lambda-trigger-syntax-custom-message-response"></a>

In the response, specify the custom text to use in messages to your users. For the string constraints that Amazon Cognito applies to these parameters, see [MessageTemplateType](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_MessageTemplateType.html).

**smsMessage**  
The custom SMS message to be sent to your users. Must include the `codeParameter` value that you received in the request.

**emailMessage**  
The custom email message to send to your users. You can use HTML formatting in the `emailMessage` parameter. Must include the `codeParameter` value that you received in the request as the variable `{####}`. Amazon Cognito can use the `emailMessage` parameter only if the `EmailSendingAccount` attribute of the user pool is `DEVELOPER`. If the `EmailSendingAccount` attribute of the user pool isn't `DEVELOPER` and an `emailMessage` parameter is returned, Amazon Cognito generates a 400 error code `com.amazonaws.cognito.identity.idp.model.InvalidLambdaResponseException`. When you choose Amazon Simple Email Service (Amazon SES) to send email messages, the `EmailSendingAccount` attribute of a user pool is `DEVELOPER`. Otherwise, the value is `COGNITO_DEFAULT`.

**emailSubject**  
The subject line for the custom message. You can only use the `emailSubject` parameter if the EmailSendingAccount attribute of the user pool is `DEVELOPER`. If the `EmailSendingAccount` attribute of the user pool isn't `DEVELOPER` and Amazon Cognito returns an `emailSubject` parameter, Amazon Cognito generates a 400 error code `com.amazonaws.cognito.identity.idp.model.InvalidLambdaResponseException`. The `EmailSendingAccount` attribute of a user pool is `DEVELOPER` when you choose to use Amazon Simple Email Service (Amazon SES) to send email messages. Otherwise, the value is `COGNITO_DEFAULT`.

## Custom message for sign-up example
<a name="aws-lambda-triggers-custom-message-example"></a>

This example Lambda function customizes an email or SMS message when the service requires an app to send a verification code to the user.

Amazon Cognito can invoke a Lambda trigger at multiple events: post-registration, resending a verification code, recovering a forgotten password, or verifying a user attribute. The response includes messages for both SMS and email. The message must include the code parameter `"####"`. This parameter is the placeholder for the verification code that the user receives.

The maximum length for an email message is 20,000 UTF-8 characters,. This length includes the verification code. You can use HTML tags in these email messages.

The maximum length of SMS messages is 140 UTF-8 characters. This length includes the verification code.

------
#### [ Node.js ]

```
const handler = async (event) => {
  if (event.triggerSource === "CustomMessage_SignUp") {
    const message = `Thank you for signing up. Your confirmation code is ${event.request.codeParameter}.`;
    event.response.smsMessage = message;
    event.response.emailMessage = message;
    event.response.emailSubject = "Welcome to the service.";
  }
  return event;
};

export { handler };
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
	"version": "1",
	"region": "us-west-2",
	"userPoolId": "us-west-2_EXAMPLE",
	"userName": "test-user",
	"callerContext": {
		"awsSdkVersion": "aws-sdk-unknown-unknown",
		"clientId": "1example23456789"
	},
	"triggerSource": "CustomMessage_SignUp",
	"request": {
		"userAttributes": {
			"sub": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
			"cognito:user_status": "CONFIRMED",
			"email_verified": "true",
			"phone_number_verified": "true",
			"phone_number": "+12065551212",
			"email": "test-user@example.com"
		},
		"codeParameter": "{####}",
		"linkParameter": "{##Click Here##}",
		"usernameParameter": "None"
	},
	"response": {
		"smsMessage": "None",
		"emailMessage": "None",
		"emailSubject": "None"
	}
}
```

------

## Custom message for admin create user example
<a name="aws-lambda-triggers-custom-message-admin-example"></a>

The request that Amazon Cognito sent to this example custom message Lambda function has a `triggerSource` value of `CustomMessage_AdminCreateUser` and a username and temporary password. The function populates `${event.request.codeParameter}` from the temporary password in the request, and `${event.request.usernameParameter}` from the username in the request.

Your custom messages must insert the values of `codeParameter` and `usernameParameter` into `smsMessage` and `emailMessage` in the response object. In this example, the function writes the same message to the response fields `event.response.smsMessage` and `event.response.emailMessage`.

The maximum length of an email message is 20,000 UTF-8 characters. This length includes the verification code. You can use HTML tags in these emails. The maximum length of SMS messages is 140 UTF-8 characters. This length includes the verification code.

The response includes messages for both SMS and email. 

------
#### [ Node.js ]

```
const handler = async (event) => {
  if (event.triggerSource === "CustomMessage_AdminCreateUser") {
    const message = `Welcome to the service. Your user name is ${event.request.usernameParameter}. Your temporary password is ${event.request.codeParameter}`;
    event.response.smsMessage = message;
    event.response.emailMessage = message;
    event.response.emailSubject = "Welcome to the service";
  }
  return event;
};

export { handler };
```

------

Amazon Cognito passes event information to your Lambda function. The function then returns the same event object to Amazon Cognito, with any changes in the response. In the Lambda console, you can set up a test event with data that is relevant to your Lambda trigger. The following is a test event for this code sample:

------
#### [ JSON ]

```
{
  "version": 1,
  "triggerSource": "CustomMessage_AdminCreateUser",
  "region": "<region>",
  "userPoolId": "<userPoolId>",
  "userName": "<userName>",
  "callerContext": {
      "awsSdk": "<calling aws sdk with version>",
      "clientId": "<apps client id>",
      ...
  },
  "request": {
      "userAttributes": {
          "phone_number_verified": false,
          "email_verified": true,
           ...
      },
      "codeParameter": "####",
      "usernameParameter": "username"
  },
  "response": {
      "smsMessage": "<custom message to be sent in the message with code parameter and username parameter>"
      "emailMessage": "<custom message to be sent in the message with code parameter and username parameter>"
      "emailSubject": "<custom email subject>"
  }
}
```

------

# Custom sender Lambda triggers
<a name="user-pool-lambda-custom-sender-triggers"></a>

The Lambda triggers `CustomEmailSender` and `CustomSMSSender` support third-party email and SMS notifications in user pools. You can choose SMS and email providers to send notifications to users from within your Lambda function code. When Amazon Cognito sends invitations, MFA codes, confirmation codes, verification codes, and temporary passwords to users, the events activate your configured Lambda functions. Amazon Cognito sends the code and temporary passwords (secrets) to your activated Lambda functions. Amazon Cognito encrypts these secrets with an AWS KMS customer managed key and the AWS Encryption SDK. The AWS Encryption SDK is a client-side encryption library that helps you to encrypt and decrypt generic data.

**[CustomEmailSender](user-pool-lambda-custom-email-sender.md)**  
Amazon Cognito invokes this trigger to send email notifications to users. 

**[CustomSMSSender](user-pool-lambda-custom-sms-sender.md)**  
Amazon Cognito invokes this trigger to send SMS notifications to users.

## Encryption concepts
<a name="user-pool-lambda-custom-sender-triggers-resources"></a>

Amazon Cognito doesn't send users' codes in plaintext in the events that it sends to custom sender triggers. The Lambda functions must decrypt codes in the events. The following concepts are the encryption architecture that your function must use to get codes that it can deliver to users.

**AWS KMS**  
AWS KMS is a managed service to create and control AWS KMS keys. These keys encrypt your data. For more information see, [What is AWS Key Management Service?](/kms/latest/developerguide/overview.html).

**KMS key**  
A KMS key is a logical representation of a cryptographic key. The KMS key includes metadata, such as the key ID, creation date, description, and key state. The KMS key also contains the key material used to encrypt and decrypt data. For more information see, [AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys).

**Symmetric KMS key**  
A symmetric KMS key is a 256-bit encryption key that doesn't exit AWS KMS unencrypted. To use a symmetric KMS key, you must call AWS KMS. Amazon Cognito uses symmetric keys. The same key encrypts and decrypts. For more information see, [Symmetric KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#symmetric-cmks). 

## Things to know about custom sender Lambda triggers
<a name="user-pool-lambda-custom-sender-triggers-things-to-know"></a>
+ To configure your user pools to use these Lambda triggers, you can use the AWS CLI or SDK. These configurations aren't available from Amazon Cognito console.

  The `UpdateUserPool` operation sets Lambda configuration. Requests to this operation require all the parameters of your user pool *and* the parameters that you want to change. If you don't provide all relevant parameters, Amazon Cognito sets the values of any missing parameters to their defaults. As demonstrated in the AWS CLI example that follows, include entries for all Lambda functions that you want to add to or keep in your user pool. For more information, see [Updating user pool and app client configuration](cognito-user-pool-updating.md).

  ```
      #Send this parameter in an 'aws cognito-idp update-user-pool' CLI command, including any existing 
      #user pool configurations. This snippet also includes a pre sign-up trigger for syntax reference. The pre sign-up trigger
      #doesn't have a role in custom sender triggers.
                
        --lambda-config "PreSignUp=lambda-arn, \
                         CustomSMSSender={LambdaVersion=V1_0,LambdaArn=lambda-arn}, \
                         CustomEmailSender={LambdaVersion=V1_0,LambdaArn=lambda-arn}, \
                         KMSKeyID=key-id"
  ```

  For requests that use the JSON body of `UpdateUserPool` the following `LambdaConfig` snippet assigns custom SMS and email sender functions.

  ```
  "LambdaConfig": {
     "KMSKeyID": "arn:aws:kms:us-east-1:111122223333:key/a6c4f8e2-0c45-47db-925f-87854bc9e357",
     "CustomEmailSender": {
        "LambdaArn": "arn:aws:lambda:us-east-1:111122223333:function:MyFunction",
        "LambdaVersion": "V1_0"
     },
     "CustomSMSSender": {
        "LambdaArn": "arn:aws:lambda:us-east-1:111122223333:function:MyFunction",
        "LambdaVersion": "V1_0"
     }
  ```
+ To remove a custom sender Lambda trigger with an `update-user-pool` AWS CLI command, omit the `CustomSMSSender` or `CustomEmailSender` parameter from `--lambda-config`, and include all other triggers that you want to use with your user pool.

  To remove a custom sender Lambda trigger with an `UpdateUserPool` API request, omit the `CustomSMSSender` or `CustomEmailSender` parameter from the request body that contains the rest of your user pool configuration.
+ Amazon Cognito HTML-escapes reserved characters like `<` (`&lt;`) and `>` (`&gt;`) in your user's temporary password. These characters might appear in temporary passwords that Amazon Cognito sends to your custom email sender function, but don't appear in temporary verification codes. To send temporary passwords, your Lambda function must unescape these characters after it decrypts the password, and before it sends the message to your user.

## Activating custom sender Lambda triggers
<a name="enable-custom-sender-lambda-trigger"></a>

To use custom logic to send SMS or email messages for your user pool, set up custom sender triggers. The following procedure assigns a custom SMS trigger, a custom email trigger, or both to your user pool. After you add your custom sender trigger, Amazon Cognito always sends user attributes, including the phone number, and the one-time code to your Lambda function instead of the default behavior that sends an SMS or email message.

1. Create a [symmetric encryption key](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#symmetric-cmks) in AWS Key Management Service (AWS KMS). Amazon Cognito generates secrets—temporary passwords, verification codes, authentication one-time passwords, and confirmation codes—then uses this KMS key to encrypt the secrets with [AWS Encryption SDK](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html). You can then use the AWS Encryption SDK in your Lambda function to decrypt the secrets and send them to the user in plaintext.

1. The IAM principal that creates or updates your user pool creates a one-time grant against the KMS key that Amazon Cognito uses to encrypt the code. Grant this principal `CreateGrant` permissions for your KMS key. For this example KMS key policy to be effective, the administrator who updates the user pool must be signed in with an assumed-role session for the IAM role `arn:aws:iam::111222333444:role/my-example-administrator-role`. 

   Apply the following resource-based policy, modified for your environment, to your KMS key.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
       {
           "Effect": "Allow",
           "Principal": {
               "AWS": "arn:aws:iam::111122223333:role/my-example-administrator-role"
           },
           "Action": "kms:CreateGrant",
           "Resource": "arn:aws:kms:us-west-2:111122223333:key/1example-2222-3333-4444-999example",
           "Condition": {
               "StringEquals": {
                  "kms:EncryptionContext:userpool-id": "us-west-2_EXAMPLE"
               }
           }
       },
       {
           "Sid": "Allow Lambda to decrypt",
           "Effect": "Allow",
           "Principal": {
               "AWS": "arn:aws:iam::111122223333:role/my-lambda-function-role"
           },
           "Action": "kms:Decrypt",
           "Resource": "*"
       }]
   }
   ```

------

1. Create a Lambda function for the custom sender trigger. Amazon Cognito uses the [AWS encryption SDK](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/introduction.html) to encrypt the secrets, temporary passwords and codes that authorize your users' API requests.

   1. Assign a [Lambda execution role](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html) that has, at minimum, `kms:Decrypt` permissions for your KMS key.

   1. Compose Lambda function code to send your messages. The input event to your function contains a secret. In your function, decrypt the secret with the AWS Encryption SDK and process any relevant metadata. Then send the code, your own custom message, and destination phone number to the custom API that delivers your message.

   1. Add the AWS Encryption SDK to your Lambda function. For more information, see [AWS Encryption SDK programming languages](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/programming-languages.html). To update the Lambda package, complete the following steps.

      1. Export your Lambda function as a .zip file in the AWS Management Console.

      1. Open your function and add the AWS Encryption SDK. For more information and download links, see [AWS Encryption SDK programming languages](https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/programming-languages.html) in the *AWS Encryption SDK Developer Guide*.

      1. Zip your function with your SDK dependencies, and upload the function to Lambda. For more information, see [Deploying Lambda functions as .zip file archives](https://docs.aws.amazon.com/lambda/latest/dg/configuration-function-zip.html#configuration-function-create) in the *AWS Lambda Developer Guide*.

1. Grant Amazon Cognito service principal `cognito-idp.amazonaws.com` access to invoke the Lambda function.

   The following AWS CLI command grants Amazon Cognito permission to invoke your Lambda function:

   ```
   aws lambda add-permission --function-name lambda_arn --statement-id "CognitoLambdaInvokeAccess" --action lambda:InvokeFunction --principal cognito-idp.amazonaws.com
   ```

1. Generate an [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request with a `LambdaConfig` parameter that adds custom sender Lambda triggers. You can't add triggers of this type in the Amazon Cognito console. Custom sender triggers require `LambdaConfig` parameters of `KMSKeyID` and `CustomSMSSender` or `CustomEmailSender` (or both).

# Custom email sender Lambda trigger
<a name="user-pool-lambda-custom-email-sender"></a>

When you assign a custom email sender trigger to your user pool, Amazon Cognito invokes a Lambda function instead of its default behavior when a user event requires that it send an email message. With a custom sender trigger, your AWS Lambda function can send email notifications to your users through a method and provider that you choose. The custom code of your function must process and deliver all email messages from your user pool.

This trigger serves scenarios where you might want to have greater control over how your user pool sends email messages. Your Lambda function can customize the call to Amazon SES API operations, for example when you want to manage multiple verified identities or cross AWS Regions. Your function also might redirect messages to another delivery medium or third-party service.

To learn how to configure a custom email sender trigger, see [Activating custom sender Lambda triggers](user-pool-lambda-custom-sender-triggers.md#enable-custom-sender-lambda-trigger).

## Custom email sender Lambda trigger sources
<a name="trigger-source"></a>

The following table shows the triggering events for custom email trigger sources in your Lambda code.


| `TriggerSource value` | Event | 
| --- | --- | 
| CustomEmailSender\$1SignUp | A user signs up and Amazon Cognito sends a welcome message. | 
| CustomEmailSender\$1Authentication | A user signs in and Amazon Cognito sends an email OTP or MFA code. | 
| CustomEmailSender\$1ForgotPassword | A user requests a code to reset their password. | 
| CustomEmailSender\$1ResendCode | A user requests a replacement account-confirmation code. | 
| CustomEmailSender\$1UpdateUserAttribute | A user updates an email address or phone number attribute and Amazon Cognito sends a code to verify the attribute. | 
| CustomEmailSender\$1VerifyUserAttribute | A user creates a new email address or phone number attribute and Amazon Cognito sends a code to verify the attribute. | 
| CustomEmailSender\$1AdminCreateUser | You create a new user in your user pool and Amazon Cognito sends them a temporary password. | 
| CustomEmailSender\$1AccountTakeOverNotification | Amazon Cognito detects an attempt to take over a user account and sends the user a notification. | 

## Custom email sender Lambda trigger parameters
<a name="custom-email-sender-parameters"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "type": "customEmailSenderRequestV1",
        "code": "string",
        "clientMetadata": {
            "string": "string",
             . . .
            },
        "userAttributes": {
            "string": "string",
            . . .
         }
}
```

------

### Custom email sender request parameters
<a name="custom-email-sender-request-parameters"></a>

**type**  
The request version. For a custom email sender event, the value of this string is always `customEmailSenderRequestV1`.

**code**  
The encrypted code that your function can decrypt and send to your user.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the custom email sender Lambda function trigger. To pass this data to your Lambda function, you can use the ClientMetadata parameter in the [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API actions. Amazon Cognito doesn't include data from the ClientMetadata parameter in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations in the request that it passes to the post authentication function.  
Amazon Cognito sends `ClientMetadata` to custom email trigger functions in events with the following trigger sources:  
+ `CustomEmailSender_ForgotPassword`
+ `CustomEmailSender_SignUp`
+ `CustomEmailSender_Authentication`
Amazon Cognito doesn't send `ClientMetadata` in trigger events with source `CustomEmailSender_AccountTakeOverNotification`.

**userAttributes**  
One or more key-value pairs that represent user attributes.

### Custom email sender response parameters
<a name="custom-email-sender-response-parameters"></a>

Amazon Cognito doesn't expect any additional return information in the custom email sender response. Your Lambda function must interpret the event and decrypt the code, then deliver the message contents. A typical function assembles an email message and directs it to a third-party SMTP relay.

## Code example
<a name="custom-email-sender-code-examples"></a>

The following Node.js example processes an email message event in your custom email sender Lambda function. This example assumes your function has two environment variables defined.

**`KEY_ID`**  
The ID of the KMS key that you want to use to encrypt and decrypt your users' codes.

**`KEY_ARN`**  
The Amazon Resource Name (ARN) of the KMS key that you want to use to encrypt and decrypt your users' codes.

**To deploy this function**

1. Install the latest version of NodeJS in your developer workspace.

1. Create a new NodeJS project in your workspace.

1. Initialize your project with `npm init -y`.

1. Create the script for the Lambda function: `touch index.mjs`.

1. Paste the contents of the below example into `index.mjs`.

1. Download the project dependency, AWS Encryption SDK: `npm install @aws-crypto/client-node`.

1. Zip the project directory into a file: `zip -r my_deployment_package.zip .`.

1. [Deploy the ZIP file to your function](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html).

This example function decrypts the code and, for sign-up events, simulates sending an email message to the user's email address.

```
import { KmsKeyringNode, buildClient, CommitmentPolicy } from '@aws-crypto/client-node';

// Configure the encryption SDK client with the KMS key from the environment variables
const { encrypt, decrypt } = buildClient(
    CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT
);

const generatorKeyId = process.env.KEY_ID;
const keyIds = [process.env.KEY_ARN];
const keyring = new KmsKeyringNode({ generatorKeyId, keyIds });

// Example function to simulate sending email.
// This example logs message details to CloudWatch Logs from your Lambda function.
// Update this function with custom logic that sends an email message to 'emailaddress' with body 'message'.
const sendEmail = async (emailAddress, message) => {
    // Log the destination with the email address masked.
    console.log(`Simulating email send to ${emailAddress.replace(/[^@.]/g, '*')}`);
    // Log the message with the code masked.
    console.log(`Message content: ${message.replace(/\b\d{6,8}\b/g, '********')}`);
    // Simulate API delay
    await new Promise(resolve => setTimeout(resolve, 100));
    console.log('Email sent successfully');
    return true;
};

export const handler = async (event) => {
    try {
        // Decrypt the secret code using encryption SDK
        let plainTextCode;
        if (event.request.code) {
            const { plaintext, messageHeader } = await decrypt(keyring, Buffer.from(event.request.code, 'base64'));
            plainTextCode = Buffer.from(plaintext).toString('utf-8');
        }

        // Handle different trigger sources
        if (event.triggerSource == 'CustomEmailSender_SignUp') {
            const emailAddress = event.request.userAttributes.email;
            const message = `Welcome! Your verification code is: ${plainTextCode}`;
            await sendEmail(emailAddress, message);
        }
        else if (event.triggerSource == 'CustomEmailSender_ResendCode') {
            // Handle resend code
        }
        else if (event.triggerSource == 'CustomEmailSender_ForgotPassword') {
            // Handle forgot password
        }
        else if (event.triggerSource == 'CustomEmailSender_UpdateUserAttribute') {
            // Handle update attribute
        }
        else if (event.triggerSource == 'CustomEmailSender_VerifyUserAttribute') {
            // Handle verify attribute
        }
        else if (event.triggerSource == 'CustomEmailSender_AdminCreateUser') {
            // Handle admin create user
        }
        else if (event.triggerSource == 'CustomEmailSender_Authentication') {
            // Handle authentication
        }
        else if (event.triggerSource == 'CustomEmailSender_AccountTakeOverNotification') {
            // Handle account takeover notification
        }

        return;
    } catch (error) {
        console.error('Error in custom email sender:', error);
        throw error;
    }
};
```

# Custom SMS sender Lambda trigger
<a name="user-pool-lambda-custom-sms-sender"></a>

When you assign a custom SMS sender trigger to your user pool, Amazon Cognito invokes a Lambda function instead of its default behavior when a user event requires that it send an SMS message. With a custom sender trigger, your AWS Lambda function can send SMS notifications to your users through a method and provider that you choose. The custom code of your function must process and deliver all SMS messages from your user pool.

This trigger serves scenarios where you might want to have greater control over how your user pool sends SMS messages. Your Lambda function can customize the call to Amazon SNS API operations, for example when you want to manage multiple origination IDs or cross AWS Regions. Your function also might redirect messages to another delivery medium or third-party service.

To learn how to configure a custom email sender trigger, see [Activating custom sender Lambda triggers](user-pool-lambda-custom-sender-triggers.md#enable-custom-sender-lambda-trigger).

## Custom SMS sender Lambda trigger sources
<a name="trigger-source"></a>

The following table shows the triggering event for custom SMS trigger sources in your Lambda code.


| `TriggerSource value` | Event | 
| --- | --- | 
| CustomSMSSender\$1SignUp | A user signs up and Amazon Cognito sends a welcome message. | 
| CustomSMSSender\$1ForgotPassword | A user requests a code to reset their password. | 
| CustomSMSSender\$1ResendCode | A user requests a new code to confirm their registration. | 
| CustomSMSSender\$1VerifyUserAttribute | A user creates a new email address or phone number attribute and Amazon Cognito sends a code to verify the attribute. | 
| CustomSMSSender\$1UpdateUserAttribute | A user updates an email address or phone number attribute and Amazon Cognito sends a code to verify the attribute. | 
| CustomSMSSender\$1Authentication | A user signs in and Amazon Cognito sends an SMS OTP or MFA code. | 
| CustomSMSSender\$1AdminCreateUser | You create a new user in your user pool and Amazon Cognito sends them a temporary password. | 

## Custom SMS sender Lambda trigger parameters
<a name="custom-sms-sender-parameters"></a>

The request that Amazon Cognito passes to this Lambda function is a combination of the parameters below and the [common parameters](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared) that Amazon Cognito adds to all requests.

------
#### [ JSON ]

```
{
    "request": {
        "type": "customSMSSenderRequestV1",
        "code": "string",
        "clientMetadata": {
            "string": "string",
             . . .
            },
        "userAttributes": {
            "string": "string",
            . . .
         }
}
```

------

### Custom SMS sender request parameters
<a name="custom-sms-sender-request-parameters"></a>

**type**  
The request version. For a custom SMS sender event, the value of this string is always `customSMSSenderRequestV1`.

**code**  
The encrypted code that your function can decrypt and send to your user.

**clientMetadata**  
One or more key-value pairs that you can provide as custom input to the custom SMS sender Lambda function trigger. To pass this data to your Lambda function, you can use the ClientMetadata parameter in the [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API actions. Amazon Cognito doesn't include data from the ClientMetadata parameter in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations in the request that it passes to the post authentication function.

**userAttributes**  
One or more key-value pairs that represent user attributes.

### Custom SMS sender response parameters
<a name="custom-sms-sender-response-parameters"></a>

Amazon Cognito doesn't expect any additional return information in the response. Your function can use API operations to query and modify your resources, or record event metadata to an external system.

## Code example
<a name="custom-sms-sender-code-examples"></a>

The following Node.js example processes an SMS message event in your custom SMS sender Lambda function. This example assumes your function has two environment variables defined.

**`KEY_ID`**  
The ID of the KMS key that you want to use to encrypt and decrypt your users' codes.

**`KEY_ARN`**  
The Amazon Resource Name (ARN) of the KMS key that you want to use to encrypt and decrypt your users' codes.

**To deploy this function**

1. Install the latest version of NodeJS in your developer workspace.

1. Create a new NodeJS project in your workspace.

1. Initialize your project with `npm init -y`.

1. Create the script for the Lambda function: `touch index.mjs`.

1. Paste the contents of the below example into `index.mjs`.

1. Download the project dependency, AWS Encryption SDK: `npm install @aws-crypto/client-node`.

1. Zip the project directory into a file: `zip -r my_deployment_package.zip .`.

1. [Deploy the ZIP file to your function](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html).

```
import { KmsKeyringNode, buildClient, CommitmentPolicy } from '@aws-crypto/client-node';

// Configure the encryption SDK client with the KMS key from the environment variables
const { encrypt, decrypt } = buildClient(
    CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT
);

const generatorKeyId = process.env.KEY_ID;
const keyIds = [process.env.KEY_ARN];
const keyring = new KmsKeyringNode({ generatorKeyId, keyIds });

// Example function to simulate sending SMS.
// This example logs message details to CloudWatch Logs from your Lambda function.
// Update this function with custom logic that sends an SMS message to 'phoneNumber' with body 'message'.
const sendSMS = async (phoneNumber, message) => {
    // Log the destination with the phone number masked.
    console.log(`Simulating SMS send to ${phoneNumber.replace(/[^+]/g, '*')}`);
    // Log the message with the code masked.
    console.log(`Message content: ${message.replace(/\b\d{6,8}\b/g, '********')}`);    
    // Simulate API delay
    await new Promise(resolve => setTimeout(resolve, 100));
    console.log('SMS sent successfully');
    return true;
};

export const handler = async (event) => {
    try {
        // Decrypt the secret code using encryption SDK
        let plainTextCode;
        if (event.request.code) {
            const { plaintext, messageHeader } = await decrypt(keyring, Buffer.from(event.request.code, 'base64'));
            plainTextCode = Buffer.from(plaintext).toString('utf-8');
        }

        // Handle different trigger sources
        if (event.triggerSource == 'CustomSMSSender_SignUp') {
            const phoneNumber = event.request.userAttributes.phone_number;
            const message = `Welcome! Your verification code is: ${plainTextCode}`;
            await sendSMS(phoneNumber, message);
        }
        else if (event.triggerSource == 'CustomSMSSender_ResendCode') {
            // Handle resend code
        }
        else if (event.triggerSource == 'CustomSMSSender_ForgotPassword') {
            // Handle forgot password
        }
        else if (event.triggerSource == 'CustomSMSSender_UpdateUserAttribute') {
            // Handle update attribute
        }
        else if (event.triggerSource == 'CustomSMSSender_VerifyUserAttribute') {
            // Handle verify attribute
        }
        else if (event.triggerSource == 'CustomSMSSender_AdminCreateUser') {
            // Handle admin create user
        }
        return;
    } catch (error) {
        console.error('Error in custom SMS sender:', error);
        throw error;
    }
};
```

**Topics**
+ [

## Custom SMS sender Lambda trigger sources
](#trigger-source)
+ [

## Custom SMS sender Lambda trigger parameters
](#custom-sms-sender-parameters)
+ [

## Code example
](#custom-sms-sender-code-examples)
+ [

## Evaluate SMS message capabilities with a custom SMS sender function
](#sms-to-email-example)

## Evaluate SMS message capabilities with a custom SMS sender function
<a name="sms-to-email-example"></a>

A custom SMS sender Lambda function accepts the SMS messages that your user pool would send, and the function delivers the content based on your custom logic. Amazon Cognito sends the [Custom SMS sender Lambda trigger parameters](#custom-sms-sender-parameters) to your function. Your function can do what you want with this information. For example, you can send the code to an Amazon Simple Notification Service (Amazon SNS) topic. An Amazon SNS topic subscriber can be an SMS message, an HTTPS endpoint, or an email address.

To create a test environment for Amazon Cognito SMS messaging with a custom SMS sender Lambda function, see [amazon-cognito-user-pool-development-and-testing-with-sms-redirected-to-email](https://github.com/aws-samples/amazon-cognito-user-pool-development-and-testing-with-sms-redirected-to-email) in the [aws-samples library on GitHub](https://github.com/aws-samples). The repository contains AWS CloudFormation templates that can create a new user pool, or work with a user pool that you already have. These templates create Lambda functions and an Amazon SNS topic. The Lambda function that the template assigns as a custom SMS sender trigger, redirects your SMS messages to the subscribers to the Amazon SNS topic. 

When you deploy this solution to a user pool, all messages that Amazon Cognito usually sends through SMS messaging, the Lambda function instead sends to a central email address. Use this solution to customize and preview SMS messages, and to test the user pool events that cause Amazon Cognito to send an SMS message. After you complete your tests, roll back the CloudFormation stack, or remove the custom SMS sender function assignment from your user pool.

**Important**  
Don't use the templates in [amazon-cognito-user-pool-development-and-testing-with-sms-redirected-to-email](https://github.com/aws-samples/amazon-cognito-user-pool-development-and-testing-with-sms-redirected-to-email) to build a production environment. The custom SMS sender Lambda function in the solution *simulates* SMS messages, but the Lambda function sends them all to a single central email address. Before you can send SMS messages in a production Amazon Cognito user pool, you must complete the requirements shown at [SMS message settings for Amazon Cognito user pools](user-pool-sms-settings.md).

# Managing users in your user pool
<a name="managing-users"></a>

After you create a user pool, you can create, confirm, and manage user accounts. With Amazon Cognito user pools groups you can manage your users and their access to resources by mapping IAM roles to groups.

Managing users in your Amazon Cognito user pool involves a variety of configuration options and administrative tasks. User pools can scale to millions of users. A user directory of this scale requires equally scalable and repeatable administrative tools. You might want to create many user profiles, manage inactive users, produce governance and compliance reports, or set up self-service tools where users do most of the work. After you create a user pool, you can control how users sign up and confirm their accounts, including requiring email or phone number verification. Administrators can also create user accounts directly and customize the welcome messages and password requirements.

User pools have user groups, where you can manage access to resources based on a user's group membership. You can assign IAM roles to these groups to manage access to AWS services with identity pools. Users' group membership is present in both ID and access tokens. With this information, you can make access-control decisions at runtime in your application or with a policy engine like Amazon Verified Permissions.

User pools often have many users. You will frequently find yourself searching for and updating user accounts. The Amazon Cognito console and API support querying users based on standard attributes like username, email, and phone number. Administrators can also reset passwords, disable accounts, and view user event history.

For migrating existing user data, Amazon Cognito has options to import users from a CSV file and to use a [Lambda trigger](user-pool-lambda-migrate-user.md) to automatically migrate users when they first sign in. These options support user transitions from other user directories to your user pool.

You can use the user-management features in user pools to have fine-grained control over the user lifecycle and authentication experience. The combination of self-service sign-up, admin-created accounts, groups, and migration tools makes Amazon Cognito user pools a flexible user directory.

**Topics**
+ [

# Configuring policies for user creation
](user-pool-settings-admin-create-user-policy.md)
+ [

# Signing up and confirming user accounts
](signing-up-users-in-your-app.md)
+ [

# Creating user accounts as administrator
](how-to-create-user-accounts.md)
+ [

# Adding groups to a user pool
](cognito-user-pools-user-groups.md)
+ [

# Managing and searching for user accounts
](how-to-manage-user-accounts.md)
+ [

# Passwords, account recovery, and password policies
](managing-users-passwords.md)
+ [

# Importing users into a user pool
](cognito-user-pools-import-users.md)
+ [

# Working with user attributes
](user-pool-settings-attributes.md)

# Configuring policies for user creation
<a name="user-pool-settings-admin-create-user-policy"></a>

Your user pool can allow users to sign up, or you can create them as an administrator. You can also control how much of the process of verification and confirmation after sign-up is in the hands of your users. For example, you might want to review sign-ups and accept them based on an external validation process. This configuration, or *admin create user policy*, also sets the amount of time before a user can no longer confirm their user account.

Amazon Cognito can serve the needs of your public customers as the customer identity and access management (CIAM) platform for your software. A user pool that accepts sign-up and has an app client, with or without managed login, creates a user profile for anyone on the internet who knows your publicly-discoverable app client ID and requests to sign up. A signed-up user profile can receive access and identity tokens and can access resources that you've authorized for your app. Before you activate sign-up in your user pool, review your options and ensure that your configuration complies with your security standards. Set **Enable self-registration** and `AllowAdminCreateUserOnly`, described in the following procedures, with care.

------
#### [ AWS Management Console ]

The **Sign-up** menu of your user pool contains some of the settings for sign-up and administrative creation of users in your user pool.

**To configure the sign-up experience**

1. In **Cognito-assisted verification and confirmation**, choose whether you want to **Allow Cognito to automatically send messages to verify and confirm**. With this setting enabled, Amazon Cognito sends an email or SMS message to new users with a code that they must present to your user pool. This confirms their ownership of the email address or phone number, setting the equivalent attribute as verified and confirming the user account for sign-in. The **Attributes to verify** that you choose determine the delivery methods and destinations of the verification messages.

1. **Verifying attribute changes** isn't significant when you're creating users, but relates to attribute verification. You can permit users who have changed but not yet verified their [sign-in attributes](user-pool-settings-attributes.md#user-pool-settings-aliases.title) to continue to sign in either with their new attribute value or with their original. For more information, see [Verifying when users change their email or phone number](signing-up-users-in-your-app.md#verifying-when-users-change-their-email-or-phone-number).

1. **Required attributes** displays the attributes that must be provided a value before a user can sign up or you can create a user. You can only set required attributes when you create a user pool.

1. **Custom attributes** are important to the user creation and sign-up process because you can only set a value for *immutable* custom attributes when you first create a user. For more information about custom attributes, see [Custom attributes](user-pool-settings-attributes.md#user-pool-settings-custom-attributes).

1. In **Self-service sign-up**, select **Enable self-registration** if you want users to be able to generate a new account with the [unauthenticated](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html#user-pool-apis-auth-unauth) `SignUp` API. If you disable self-registration, you can only create new users as an administrator, in the Amazon Cognito console or with [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) API requests. In a user pool where self-registration is inactive, [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) API requests return `NotAuthorizedException` and managed login doesn't display a **Sign up** link.

For user pools where you plan to create users as an administrator, you can configure the duration of their temporary passwords in the setting in the **Authentication methods** menu under **Temporary passwords set by administrators expire in**.

Another important element of the creation of users as an administrator is the invitation message. When you create a new user, Amazon Cognito sends them a message with a link to your app so that they can sign in for the first time. Customize this message template in the **Authentication methods** menu under **Message templates**.

You can configure [confidential app clients](user-pool-settings-client-apps.md#user-pool-settings-client-app-client-types.title), typically web applications, with a client secret that prevents sign-up without the app client secret. As a security best practice, do not distribute app client secrets in public app clients, typically mobile apps. You can create app clients with client secrets in the **App clients** menu of the Amazon Cognito console.

------
#### [ Amazon Cognito user pools API ]

You can programmatically set the parameters for creation of users in a user pool in a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request.

The [AdminCreateUserConfig](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-AdminCreateUserConfig) element sets values for the following properties of a user pool.

1. Enable self-service sign-up

1. The invitation message that you send to new admin-created users

The following example, when added to a full API request body, sets a user pool with self-service sign-up inactive and a basic invitation email.

```
"AdminCreateUserConfig": { 
      "AllowAdminCreateUserOnly": true,
      "InviteMessageTemplate": { 
         "EmailMessage": "Your username is {username} and temporary password is {####}.",
         "EmailSubject": "Welcome to ExampleApp",
         "SMSMessage": "Your username is {username} and temporary password is {####}."
      }
   }
```

The following additional parameters of a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request govern the creation of new users.

[AutoVerifiedAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-AutoVerifiedAttributes)  
The attributes, email addresses or phone numbers, that you want to [automatically send a message to](user-pool-settings-email-phone-verification.md#user-pool-settings-email-phone-verification.title) when you register a new user.

[Policies](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-Policies)  
The user pool [password policy](managing-users-passwords.md#user-pool-settings-policies.title).

[Schema](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-Schema)  
The user pool [custom attributes](user-pool-settings-attributes.md#user-pool-settings-custom-attributes.title). They are important to the user creation and sign-up process because you can only set a value for *immutable* custom attributes when you first create a user.  
This parameter also sets the required attributes for your user pool. The following text, when inserted into the `Schema` element of a full API request body, set the `email` attribute as required.  

```
{
            "Name": "email",
            "Required": true
}
```

------

# Signing up and confirming user accounts
<a name="signing-up-users-in-your-app"></a>

User accounts are added to your user pool in one of the following ways:
+ The user signs up in your user pool's client app. This can be a mobile or web app.
+ You can import the user's account into your user pool. For more information, see [Importing users into user pools from a CSV file](cognito-user-pools-using-import-tool.md).
+ You can create the user's account in your user pool and invite the user to sign in. For more information, see [Creating user accounts as administrator](how-to-create-user-accounts.md).

Users who sign themselves up must be confirmed before they can sign in. Imported and created users are already confirmed, but they must create their password the first time they sign in. The following sections explain the confirmation process and email and phone verification.

**Passwords at sign-up**  
Amazon Cognito requires passwords from all users when they sign up, except under the following conditions. If *all* of these conditions are met, you can omit passwords in sign-up operations.

1. [Passwordless sign-in](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless) is active in your user pool and app client.

1. Your application is custom-built with authentication modules in an AWS SDK. Managed login and the hosted UI always require passwords.

1. Users provide attribute values for the passwordless sign-in methods—email or SMS message one-time passwords (OTPs)—that you permit. For example, if you allow sign-in with email and phone OTP, users can provide either a phone number or email address, but if you only allow sign-in with email, they must provide an email address.

1. Your user pool [automatically verifies](#allowing-users-to-sign-up-and-confirm-themselves) the attributes that users can use with passwordless sign-in.

1. For any given [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) request, the user doesn't provide a value for the [Password](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html#CognitoUserPools-SignUp-request-Password) parameter.

## Overview of user account confirmation
<a name="signup-confirmation-verification-overview"></a>

The following diagram illustrates the confirmation process:

![\[When users enter the confirmation code, they automatically verify email or phone.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/amazon-cognito-sign-in-confirm-user.png)


A user account can be in any of the following states:

**Registered (Unconfirmed)**  
The user has successfully signed up, but cannot sign in until the user account is confirmed. The user is enabled but not confirmed in this state.  
New users who sign themselves up start in this state.

**Confirmed**  
The user account is confirmed and the user can sign in. When a user enters a code or follows an email link to confirm their user account, that email or phone number is automatically verified. The code or link is valid for 24 hours.  
If the user account was confirmed by the administrator or a pre sign-up Lambda trigger, there might not be a verified email or phone number associated with the account.

**Password Reset Required**  
The user account is confirmed, but the user must request a code and reset their password before they can sign in.  
User accounts that are imported by an administrator or developer start in this state.

**Force Change Password**  
The user account is confirmed and the user can sign in using a temporary password, but on first sign-in, the user must change their password to a new value before doing anything else.  
User accounts that are created by an administrator or developer start in this state.

**Disabled**  
Before you can delete a user account, you must disable sign-in access for that user.

**More resources**
+ [Detecting and remediating inactive user accounts with Amazon Cognito](https://aws.amazon.com/blogs/security/detecting-and-remediating-inactive-user-accounts-with-amazon-cognito/)

## Verifying contact information at sign-up
<a name="allowing-users-to-sign-up-and-confirm-themselves"></a>

When new users sign up in your app, you probably want them to provide at least one contact method. For example, with your users' contact information, you might:
+ Send a temporary password when a user chooses to reset their password.
+ Notify users when their personal or financial information is updated.
+ Send promotional messages, such as special offers or discounts.
+ Send account summaries or billing reminders.

For use cases like these, it's important that you send your messages to a verified destination. Otherwise, you might send your messages to an invalid email address or phone number that was typed incorrectly. Or worse, you might send sensitive information to bad actors who pose as your users.

To help ensure that you send messages only to the right individuals, configure your Amazon Cognito user pool so that users must provide the following when they sign up:

1. An email address or phone number.

1. A verification code that Amazon Cognito sends to that email address or phone number. If 24 hours have passed and your user's code or link is no longer valid, call the [ResendConfirmationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html) API operation to generate and send a new code or link.

By providing the verification code, a user proves that they have access to the mailbox or phone that received the code. After the user provides the code, Amazon Cognito updates the information about the user in your user pool by:
+ Setting the user's status to `CONFIRMED`.
+ Updating the user's attributes to indicate that the email address or phone number is verified.

To view this information, you can use the Amazon Cognito console. Or, you can use the `AdminGetUser` API operation, the `admin-get-user` command with the AWS CLI, or a corresponding action in one of the AWS SDKs.

If a user has a verified contact method, Amazon Cognito automatically sends a message to the user when the user requests a password reset.

### Other actions that confirm and verify user attributes
<a name="allowing-users-to-sign-up-and-confirm-themselves-other-actions"></a>

The following user activity verifies user attributes. You're not required to set these attributes to automatically verify: the listed actions mark them as verified in all cases.

**Email address**  

1. Successfully completing [passwordless authentication](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless) with an email one-time password (OTP).

1. Successfully completing [multi-factor authentication (MFA)](user-pool-settings-mfa.md) with an email OTP.

**Phone number**  

1. Successfully completing [passwordless authentication](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless) with an SMS OTP.

1. Successfully completing [MFA](user-pool-settings-mfa.md) with an SMS OTP.

### To configure your user pool to require email or phone verification
<a name="verification-configure"></a>

When you verify your users' email addresses and phone numbers, you ensure that you can contact your users. Complete the following steps in the AWS Management Console to configure your user pool to require that your users confirm their email addresses or phone numbers.

**Note**  
If you don't yet have a user pool in your account, see [Getting started with user pools](getting-started-user-pools.md).

**To configure your user pool**

1. Navigate to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. From the navigation pane, choose **User Pools**. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Sign-up** menu and locate **Attribute verification and user account confirmation**. Choose **Edit**.

1. Under **Cognito-assisted verification and confirmation**, choose whether you will **Allow Cognito to automatically send messages to verify and confirm**. With this setting enabled, Amazon Cognito sends messages to the user contact attributes you choose when a user signs up, or you create a user profile. To verify attributes and confirm user profiles for sign-in, Amazon Cognito sends a code or link in messages to users. The users must then enter the code in your UI so that your app can confirm them in a `ConfirmSignUp` or `AdminConfirmSignUp` API request.
**Note**  
You can also disable **Cognito-assisted verification and confirmation** and use authenticated API actions or Lambda triggers to verify attributes and confirm users.  
If you choose this option, Amazon Cognito doesn't send verification codes when users sign up. Choose this option if you are using a custom authentication flow that verifies at least one contact method without using verification codes from Amazon Cognito. For example, you might use a pre sign-up Lambda trigger that automatically verifies email addresses that belong to a specific domain.  
If you don't verify your users' contact information, they may be unable to use your app. Remember that users require verified contact information to:  
**Reset their passwords** — When a user chooses an option in your app that calls the `ForgotPassword` API action, Amazon Cognito sends a temporary password to the user's email address or phone number. Amazon Cognito sends this password only if the user has at least one verified contact method.
**Sign in by using an email address or phone number as an alias** — If you configure your user pool to allow these aliases, then a user can sign in with an alias only if the alias is verified. For more information, see [Customizing sign-in attributes](user-pool-settings-attributes.md#user-pool-settings-aliases).

1. Choose your **Attributes to verify**:  
**Send SMS message, verify phone number**  
Amazon Cognito sends a verification code in an SMS message when the user signs up. Choose this option if you typically communicate with your users through SMS messages. For example, you will want to use verified phone numbers if you send delivery notifications, appointment confirmations, or alerts. User phone numbers will be the verified attribute when accounts are confirmed; you must take additional action to verify and communicate with user email addresses.  
**Send email message, verify email address**  
Amazon Cognito sends a verification code through an email message when the user signs up. Choose this option if you typically communicate with your users through email. For example, you will want to use verified email addresses if you send billing statements, order summaries, or special offers. User email addresses will be the verified attribute when accounts are confirmed; you must take additional action to verify and communicate with user phone numbers.  
**Send SMS message if phone number is available, otherwise send email message**  
Choose this option if you don't require all users to have the same verified contact method. In this case, the sign-up page in your app could ask users to verify only their preferred contact method. When Amazon Cognito sends a verification code, it sends the code to the contact method provided in the `SignUp` request from your app. If a user provides both an email address and a phone number, and your app provides both contact methods in the `SignUp` request, Amazon Cognito sends a verification code only to the phone number.  
If you require users to verify both an email address and a phone number, choose this option. Amazon Cognito verifies one contact method when the user signs up, and your app must verify the other contact method after the user signs in. For more information, see [If you require users to confirm both email addresses and phone numbers](#verification-email-plus-phone).

1. Choose **Save changes**.

### Authentication flow with email or phone verification
<a name="verification-flow"></a>

If your user pool requires users to verify their contact information, your app must facilitate the following flow when a user signs up:

1. A user signs up in your app by entering a username, phone number and/or email address, and possibly other attributes.

1. The Amazon Cognito service receives the sign-up request from the app. After verifying that the request contains all attributes required for sign-up, the service completes the sign-up process and sends a confirmation code to the user's phone (in an SMS message) or email. The code is valid for 24 hours.

1. The service returns to the app that sign-up is complete and that the user account is pending confirmation. The response contains information about where the confirmation code was sent. At this point the user's account is in an unconfirmed state, and the user's email address and phone number are unverified.

1. The app can now prompt the user to enter the confirmation code. It is not necessary for the user to enter the code immediately. However, the user will not be able to sign in until after they enter the confirmation code.

1. The user enters the confirmation code in the app.

1. The app calls [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html) to send the code to the Amazon Cognito service, which verifies the code and, if the code is correct, sets the user's account to the confirmed state. After successfully confirming the user account, the Amazon Cognito service automatically marks the attribute that was used to confirm (email address or phone number) as verified. Unless the value of this attribute is changed, the user will not have to verify it again.

1. At this point the user's account is in a confirmed state, and the user can sign in.

### If you require users to confirm both email addresses and phone numbers
<a name="verification-email-plus-phone"></a>

Amazon Cognito verifies only one contact method when a user signs up. In cases where Amazon Cognito must choose between verifying an email address or phone number, it chooses to verify the phone number by sending a verification code through SMS message. For example, if you configure your user pool to allow users to verify either email addresses or phone numbers, and if your app provides both of these attributes upon sign-up, Amazon Cognito verifies only the phone number. After a user verifies their phone number, Amazon Cognito sets the user's status to `CONFIRMED`, and the user is allowed to sign in to your app.

After the user signs in, your app can provide the option to verify the contact method that wasn't verified during sign-up. To verify this second method, your app calls the `VerifyUserAttribute` API action. Note that this action requires an `AccessToken` parameter, and Amazon Cognito only provides access tokens for authenticated users. Therefore, you can verify the second contact method only after the user signs in.

If you require your users to verify both email addresses and phone numbers, do the following:

1. Configure your user pool to allow users to verify email address or phone numbers.

1. In the sign-up flow for your app, require users to provide both an email address and a phone number. Call the [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) API action, and provide the email address and phone number for the `UserAttributes` parameter. At this point, Amazon Cognito sends a verification code to the user's phone.

1. In your app interface, present a confirmation page where the user enters the verification code. Confirm the user by calling the [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html) API action. At this point, the user's status is `CONFIRMED`, and the user's phone number is verified, but the email address is not verified.

1. Present the sign-in page, and authenticate the user by calling the [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API action. After the user is authenticated, Amazon Cognito returns an access token to your app.

1. Call the [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html) API action. Specify the following parameters in the request:
   + `AccessToken` – The access token returned by Amazon Cognito when the user signed in.
   + `AttributeName` – Specify `"email"` as the attribute value.

   Amazon Cognito sends a verification code to the user's email address.

1. Present a confirmation page where the user enters the verification code. When the user submits the code, call the [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html) API action. Specify the following parameters in the request:
   + `AccessToken` – The access token returned by Amazon Cognito when the user signed in.
   + `AttributeName` – Specify `"email"` as the attribute value.
   + `Code` – The verification code that the user provided.

   At this point, the email address is verified.

## Allowing users to sign up in your app but confirming them as a user pool administrator
<a name="signing-up-users-in-your-app-and-confirming-them-as-admin"></a>

You might not want your user pool to automatically send verification messages in your user pool, but still want to allow anyone to sign up for an account. This model leaves room, for example, for human review of new sign-up requests, and for batch validation and processing of sign-ups. You can confirm new user accounts in the Amazon Cognito console or with the IAM-authenticated API operation [AdminConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminConfirmSignUp.html). You can confirm user accounts as an administrator whether or not your user pool sends verification messages.

You can only confirm a user self-service sign-up with this technique. To confirm a user that you create as an administrator, create an [AdminSetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html) API request with `Permanent` set to `True`.

1. A user signs up in your app by entering a username, phone number and/or email address, and possibly other attributes.

1. The Amazon Cognito service receives the sign-up request from the app. After verifying that the request contains all attributes required for sign-up, the service completes the sign-up process and returns to the app that sign-up is complete, pending confirmation. At this point the user's account is in an unconfirmed state. The user cannot sign in until the account is confirmed.

1. Confirm the user's account. You must sign in to the AWS Management Console or sign your API request with AWS credentials to confirm the account. 

   1. To confirm a user in the Amazon Cognito console, navigate to the **Users** menu, choose the user who you want to confirm, and from the **Actions** menu select **Confirm**.

   1. To confirm a user in the AWS API or CLI, create a [AdminConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminConfirmSignUp.html) API request, or [admin-confirm-sign-up](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-confirm-sign-up.html) in the AWS CLI.

1. At this point the user's account is in a confirmed state, and the user can sign in.

## Computing secret hash values
<a name="cognito-user-pools-computing-secret-hash"></a>

Assign a client secret to your confidential app client as a best practice. When you assign a client secret to your app client, your Amazon Cognito user pools API requests must include a hash that includes the client secret in the request body. To validate your knowledge of the client secret for the API operations in the following lists, concatenate the client secret with your app client ID and your user's username, then base64-encode that string.

When your app signs in users to a client that has a secret hash, you can use the value of any user pool sign-in attribute as the username element of the secret hash. When your app requests new tokens in an authentication operation with `REFRESH_TOKEN_AUTH`, the value of the username element depends on your sign-in attributes. When your user pool doesn’t have `username` as a sign-in attribute, set the secret hash username value from the user’s `sub` claim from their access or ID token. When `username` is a sign-in attribute, set the secret hash username value from the `username` claim.

The following Amazon Cognito user pools APIs accept a client-secret hash value in a `SecretHash` parameter.
+ [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html)
+ [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html)
+ [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html)
+ [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html)
+ [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html)

Additionally, the following APIs accept a client-secret hash value in a `SECRET_HASH` parameter, either in authentication parameters or in a challenge response.


| API operation | Parent parameter for SECRET\$1HASH | 
| --- |--- |
| InitiateAuth | AuthParameters | 
| AdminInitiateAuth | AuthParameters | 
| RespondToAuthChallenge | ChallengeResponses | 
| AdminRespondToAuthChallenge | ChallengeResponses | 

The secret hash value is a Base 64-encoded keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message. The following pseudocode shows how this value is calculated. In this pseudocode, `+` indicates concatenation, `HMAC_SHA256` represents a function that produces an HMAC value using HmacSHA256, and `Base64` represents a function that produces Base-64-encoded version of the hash output.

```
Base64 ( HMAC_SHA256 ( "Client Secret Key", "Username" + "Client Id" ) )
```

For a detailed overview of how to calculate and use the `SecretHash` parameter, see [How do I troubleshoot "Unable to verify secret hash for client <client-id>" errors from my Amazon Cognito user pools API?](https://aws.amazon.com/premiumsupport/knowledge-center/cognito-unable-to-verify-secret-hash/) in the AWS Knowledge Center.

You can use the following code examples in your server-side app code.

------
#### [ Shell ]

```
echo -n "[username][app client ID]" | openssl dgst -sha256 -hmac [app client secret] -binary | openssl enc -base64
```

------
#### [ Java ]

```
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
 
public static String calculateSecretHash(String userPoolClientId, String userPoolClientSecret, String userName) {
    final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
    
    SecretKeySpec signingKey = new SecretKeySpec(
            userPoolClientSecret.getBytes(StandardCharsets.UTF_8),
            HMAC_SHA256_ALGORITHM);
    try {
        Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
        mac.init(signingKey);
        mac.update(userName.getBytes(StandardCharsets.UTF_8));
        byte[] rawHmac = mac.doFinal(userPoolClientId.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(rawHmac);
    } catch (Exception e) {
        throw new RuntimeException("Error while calculating ");
    }
}
```

------
#### [ Python ]

```
import sys
import hmac, hashlib, base64 
username = sys.argv[1] 
app_client_id = sys.argv[2] 
key = sys.argv[3] 
message = bytes(sys.argv[1]+sys.argv[2],'utf-8') 
key = bytes(sys.argv[3],'utf-8') 
secret_hash = base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode() 
print("SECRET HASH:",secret_hash)
```

------

## Confirming user accounts without verifying email or phone number
<a name="confirming-user-without-verification-of-email-or-phone-number"></a>

The pre sign-up Lambda trigger can be used to auto-confirm user accounts at sign-up, without requiring a confirmation code or verifying email or phone number. Users who are confirmed this way can immediately sign in without having to receive a code.

You can also mark a user's email or phone number verified through this trigger. 

**Note**  
While this approach is convenient for users when they're getting started, we recommend auto-verifying at least one of email or phone number. Otherwise the user can be left unable to recover if they forget their password.

If you don't require the user to receive and enter a confirmation code at sign-up and you don't auto-verify email and phone number in the pre sign-up Lambda trigger, you risk not having a verified email address or phone number for that user account. The user can verify the email address or phone number at a later time. However, if the user forgets his or her password and doesn't have a verified email address or phone number, the user is locked out of the account, because the forgot-password flow requires a verified email or phone number in order to send a verification code to the user.

## Verifying when users change their email or phone number
<a name="verifying-when-users-change-their-email-or-phone-number"></a>

In user pools that you configure with multiple sign-in names, users can enter a phone number or an email address as their username at sign-in. When they update their email address or phone number in your app, Amazon Cognito can immediately send them a message with a code that verifies their ownership of the new attribute value. To enable automatic sending of these verification codes, see [Configuring email or phone verification](user-pool-settings-email-phone-verification.md).

Users who receive a verification code must provide that code back to Amazon Cognito in a [VerifyUserAttribute](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html) request. After they provide the code, their attribute is marked as verified. Typically, when users update their email address or phone number, you'll want to verify that they own the new value before they can use it to sign in and receive messages. User pools have a configurable option that determines whether users must verify updates to their email address or phone number.

This option is the user pool property `AttributesRequireVerificationBeforeUpdate`. Configure it in a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-UserAttributeUpdateSettings) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html#CognitoUserPools-UpdateUserPool-request-UserAttributeUpdateSettings) request, or with the setting **Keep original attribute value active when an update is pending** in the **Sign-up** menu of the Amazon Cognito console.

How your user pool treats updates to email addresses and phone numbers is connected to the username configuration of your user pool. User pool usernames can be in a *username attributes* configuration where sign-in names are email address, phone number, or both. They can also be in an *alias attributes* configuration where the `username` attribute is a sign-in name along with email address, phone number, or preferred username as alternative sign-in names. For more information, see [Customizing sign-in attributes](user-pool-settings-attributes.md#user-pool-settings-aliases).

 You can also use a custom message Lambda trigger to customize the verification message. For more information, see [Custom message Lambda trigger](user-pool-lambda-custom-message.md). When a user's email address or phone number is unverified, your application should inform the user that they must verify the attribute, and provide a button or link for users to enter their verification code.

The following table describes how `AttributesRequireVerificationBeforeUpdate` and alias settings determine the outcome when users change the value of their sign-in attributes.


| Username configuration | Behavior when users must verify new attributes | Behavior when users aren't required to verify new attributes | 
| --- | --- | --- | 
| Username attributes | Original attribute remains verified, eligible for sign-in, and at original value. When user verifies new value, Amazon Cognito updates the attribute value, marks it verified, and makes it eligible for sign-in. | Amazon Cognito updates attribute to new value. New value is eligible for sign-in. When user verifies new value, Amazon Cognito marks it as verified. | 
| Alias attributes | Original attribute remains verified, eligible for sign-in, and at original value. When user verifies new value, Amazon Cognito updates the attribute value, marks it verified, and makes it eligible for sign-in. | Amazon Cognito updates attribute to new value. Neither original or new attribute value is eligible for sign-in. When user verifies new value, Amazon Cognito updates the attribute value, marks it verified, and makes it eligible for sign-in. | 

**Example 1**  
User 1 signs into your application with the email address `user1@example.com` and has the username `user1` (alias attributes). Your user pool is configured to verify updates to sign-in attributes and to automatically send verification messages. They request to update their email address to `user1+foo@example.com`. They receive a verification email at `user1+foo@example.com` and *can sign in again* only with the email address `user1@example.com`. Later, they enter their verification code and can sign in again only with the email address `user1+foo@example.com`.

**Example 2**  
User 2 signs into your application with the email address `user2@example.com` and has a username (alias attributes). Your user pool is configured *not* to verify updates to sign-in attributes and to automatically send verification messages. They request to update their email address to `user2+bar@example.com`. They receive a verification email at `user2+bar@example.com` and *can't sign in again*. Later, they enter their verification code and can sign in again only with the email address `user2+bar@example.com`.

**Example 3**  
User 3 signs into your application with the email address `user3@example.com` and doesn't have a username (username attributes). Your user pool is configured *not* to verify updates to sign-in attributes and to automatically send verification messages. They request to update their email address to `user3+baz@example.com`. They receive a verification email at `user3+baz@example.com`, but they *can immediately sign in* with no additional action taken with the verification code.

## Confirmation and verification processes for user accounts created by administrators or developers
<a name="confirmation-and-verification-of-users-whose-accounts-youve-created"></a>

User accounts that are created by an administrator or developer are already in the confirmed state, so users aren't required to enter a confirmation code. The invitation message that the Amazon Cognito service sends to these users includes the username and a temporary password. The user is required to change the password before signing in. For more information, see the [Customize email and SMS messages](how-to-create-user-accounts.md#creating-a-new-user-customize-messages) in [Creating user accounts as administrator](how-to-create-user-accounts.md) and the Custom Message trigger in [Customizing user pool workflows with Lambda triggers](cognito-user-pools-working-with-lambda-triggers.md).

## Confirmation and verification processes for imported user accounts
<a name="confirmation-and-verification-of-users-whose-accounts-youve-imported"></a>

User accounts that are created by using the user import feature in the AWS Management Console, CLI, or API (see [Importing users into user pools from a CSV file](cognito-user-pools-using-import-tool.md)) are already in the confirmed state, so users aren't required to enter a confirmation code. No invitation message is sent. However, imported user accounts require users to first request a code by calling the `ForgotPassword` API and then create a password using the delivered code by calling `ConfirmForgotPassword` API before they sign in. For more information, see [Requiring imported users to reset their passwords](cognito-user-pools-using-import-tool.md#cognito-user-pools-using-import-tool-password-reset).

Either the user's email or phone number must be marked as verified when the user account is imported, so no verification is required when the user signs in.

## Sending emails while testing your app
<a name="managing-users-accounts-email-testing"></a>

Amazon Cognito sends email messages to your users when they create and manage their accounts in the client app for your user pool. If you configure your user pool to require email verification, Amazon Cognito sends an email when:
+ A user signs up.
+ A user updates their email address.
+ A user performs an action that calls the `ForgotPassword` API action.
+ You create a user account as an administrator.

Depending on the action that initiates the email, the email contains a verification code or a temporary password. Your users must receive these emails and understand the message. Otherwise, they might be unable to sign in and use your app.

To ensure that emails send successfully and that the message looks correct, test the actions in your app that initiate email deliveries from Amazon Cognito. For example, by using the sign-up page in your app, or by using the `SignUp` API action, you can initiate an email by signing up with a test email address. When you test in this way, remember the following:

**Important**  
When you use an email address to test actions that initiate emails from Amazon Cognito, don't use a fake email address (one that has no mailbox). Use a real email address that will receive the email from Amazon Cognito without creating a *hard bounce*.  
A hard bounce occurs when Amazon Cognito fails to deliver the email to the recipient's mailbox, which always happens if the mailbox doesn't exist.  
Amazon Cognito limits the number of emails that can be sent by AWS accounts that persistently incur hard bounces.

When you test actions that initiate emails, use one of the following email addresses to prevent hard bounces:
+ An address for an email account that you own and use for testing. When you use your own email address, you receive the email that Amazon Cognito sends. With this email, you can use the verification code to test the sign-up experience in your app. If you customized the email message for your user pool, you can check that your customizations look correct.
+ The mailbox simulator address, *success@simulator.amazonses.com*. If you use the simulator address, Amazon Cognito sends the email successfully, but you're not able to view it. This option is useful when you don't need to use the verification code and you don't need to check the email message.
+ The mailbox simulator address with the addition of an arbitrary label, such as *success\$1user1@simulator.amazonses.com* or *success\$1user2@simulator.amazonses.com*. Amazon Cognito emails these addresses successfully, but you're not able to view the emails that it sends. This option is useful when you want to test the sign-up process by adding multiple test users to your user pool, and each test user has a unique email address.

# Configuring email or phone verification
<a name="user-pool-settings-email-phone-verification"></a>

You can choose settings for email or phone verification under the **Authentication methods** menu. For more information on multi-factor authentication (MFA), see [SMS Text Message MFA](user-pool-settings-mfa-sms-email-message.md).

Amazon Cognito uses Amazon SNS to send SMS messages. If you haven't sent an SMS message from Amazon Cognito or any other AWS service before, Amazon SNS might place your account in the SMS sandbox. We recommend that you send a test message to a verified phone number before you remove your account from the sandbox to production. Additionally, if you plan to send SMS messages to US destination phone numbers, you must obtain an origination or Sender ID from Amazon Pinpoint. To configure your Amazon Cognito user pool for SMS messages, see [SMS message settings for Amazon Cognito user pools](user-pool-sms-settings.md).

Amazon Cognito can automatically verify email addresses or phone numbers. To do this verification, Amazon Cognito sends a verification code or a verification link. For email addresses, Amazon Cognito can send a code or a link in an email message. You can choose a **Verification type** of **Code** or **Link** when you edit your **Verification message** template in the **Message templates** menu in the Amazon Cognito console. For more information, see [Customizing email verification messages](cognito-user-pool-settings-message-customizations.md#cognito-user-pool-settings-email-verification-message-customization).

For phone numbers, Amazon Cognito sends a code in an SMS text message.

Amazon Cognito must verify a phone number or email address to confirm users and help them to recover forgotten passwords. Alternatively, you can automatically confirm users with the pre sign-up Lambda trigger or use the [AdminConfirmSignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminConfirmSignUp.html) API operation. For more information, see [Signing up and confirming user accounts](signing-up-users-in-your-app.md).

The verification code or link is valid for 24 hours.

If you choose to require verification for an email address or phone number, Amazon Cognito automatically sends the verification code or link when a user signs up. If the user pool has a [Custom SMS sender Lambda trigger](user-pool-lambda-custom-sms-sender.md) or [Custom email sender Lambda trigger](user-pool-lambda-custom-email-sender.md) configured, that function is invoked instead.

**Notes**  
Amazon SNS charges separately for SMS text messaging that it uses to verify phone numbers. There is no charge to send email messages. For information about Amazon SNS pricing, see [Worldwide SMS pricing](https://aws.amazon.com/sns/sms-pricing/). For the current list of countries where SMS messaging is available, see [Supported regions and countries](https://docs.aws.amazon.com/sns/latest/dg/sms_supported-countries.html). 
When you test actions in your app that generate email messages from Amazon Cognito, use a real email address that Amazon Cognito can reach without hard bounces. For more information, see [Sending emails while testing your app](signing-up-users-in-your-app.md#managing-users-accounts-email-testing).
The forgotten password flow requires either the user's email or the user's phone number to verify the user.

**Important**  
If a user signs up with both a phone number and an email address, and your user pool settings require verification of both attributes, Amazon Cognito sends a verification code to the phone number through SMS message. Amazon Cognito hasn't yet verified the email address, so your app must call [GetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html) to see if an email address awaits verification. If it does require verification, the app must call [GetUserAttributeVerificationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html) to initiate the email verification flow. Then it must submit the verification code by calling [VerifyUserAttribute](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html).

You can adjust your SMS message spend quota for an AWS account and for individual messages. The limits apply only to the cost to send SMS messages. For more information, see **What are account-level and message-level spend quotas and how do they work?** in the [Amazon SNS FAQs](https://aws.amazon.com/sns/faqs/).

Amazon Cognito sends SMS messages using Amazon SNS resources in either the AWS Region where you created the user pool or in a **Legacy Amazon SNS alternate Region** from the following table. The exception is Amazon Cognito user pools in the Asia Pacific (Seoul) Region. These user pools use your Amazon SNS configuration in the Asia Pacific (Tokyo) Region. For more information, see [Choose the AWS Region for SMS messages](user-pool-sms-settings.md#sms-choose-a-region).


| Amazon Cognito Region | Legacy Amazon SNS alternate Region | 
| --- | --- | 
| US East (Ohio) | US East (N. Virginia) | 
| Asia Pacific (Mumbai) | Asia Pacific (Singapore) | 
| Asia Pacific (Seoul) | Asia Pacific (Tokyo) | 
| Canada (Central) | US East (N. Virginia) | 
| Europe (Frankfurt) | Europe (Ireland) | 
| Europe (London) | Europe (Ireland) | 

**Example: **If your Amazon Cognito user pool is in Asia Pacific (Mumbai), and you have increased your spend limit in ap-southeast-1, you might not want to request a separate increase in ap-south-1. Instead, you can use your Amazon SNS resources in Asia Pacific (Singapore). 

## Verifying updates to email addresses and phone numbers
<a name="user-pool-settings-verifications-verify-attribute-updates"></a>

An email address or phone number attribute can become active and unverified immediately after your user changes its value. Amazon Cognito can also require that your user verifies the new value before Amazon Cognito updates the attribute. When you require that your users first verify the new value, they can use the original value for sign-in and to receive messages until they verify the new value.

When your users can use their email address or phone number as a sign-in alias in your user pool, their sign-in name for an updated attribute depends on whether you require verification of updated attributes. When you require that users verify an updated attribute, a user can sign in with the original attribute value until they verify the new value. When you don’t require that users verify an updated attribute, a user can’t sign in or receive messages at either the new or the original attribute value until they verify the new value. 

For example, your user pool allows sign-in with an email address alias, and requires that users verify their email address when they update. Sue, who signs in as `sue@example.com`, wants to change her email address to `sue2@example.com` but accidentally enters `ssue2@example.com`. Sue doesn’t receive the verification email, so she can’t verify `ssue2@example.com`. Sue signs in as `sue@example.com` and resubmits the form in your app to update her email address to `sue2@example.com`. She receives this email, provides the verification code to your app, and begins signing in as `sue2@example.com`. 

**When a user updates an attribute and your user pool verifies new attribute values**
+ They can sign in with the original attribute value before they have confirmed the code to verify the new value.
+ They can only sign in with the new attribute value after they have confirmed the code to verify the new value.
+ If you set `email_verified` or `phone_number_verified` to `true` in an [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) API request, they can sign in before they have confirmed the code that Amazon Cognito sent to them.

**When a user updates an attribute and your user pool doesn't verify new attribute values**
+ They can’t sign in with, or receive messages at, the original attribute value.
+ They can’t sign in with, or receive messages other than a confirmation code at, the new attribute value before they have confirmed the code to verify the new value.
+ If you set `email_verified` or `phone_number_verified` to `true` in an [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) API request, they can sign in before they have confirmed the code that Amazon Cognito sent to them.

## To require attribute verification when users update their email address or phone number


1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. In the navigation pane, choose **User Pools**, and choose the user pool you want to edit.

1. In the **Sign-up** menu, choose **Edit** under **Attribute verification and user account confirmation**.

1. Choose **Keep original attribute value active when an update is pending**.

1. Under **Active attribute values when an update is pending**, choose the attributes that you want to require your users verify before Amazon Cognito updates the value.

1. Choose **Save changes**.

To require attribute update verification with the Amazon Cognito API, you can set the `AttributesRequireVerificationBeforeUpdate` parameter in an [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) request.

## Authorizing Amazon Cognito to send SMS messages on your behalf
<a name="user-pool-settings-verifications-iam-role-for-sms"></a>

To send SMS messages to your users on your behalf, Amazon Cognito needs your permission. To grant that permission, you can create an AWS Identity and Access Management (IAM) role. In the **Authentication methods** menu of the Amazon Cognito console under SMS, choose **Edit** to set a role.

# Configuring MFA, authentication, verification and invitation messages
<a name="cognito-user-pool-settings-message-customizations"></a>

With Amazon Cognito, you can customize SMS and email authentication, verification, and user invitation messages to enhance the security and user experience of your application. You can choose between code-based and one-click link verifications for some messages. This topic discusses how you can personalize authentication and verification communications in the Amazon Cognito console. 

In the **Message templates** menu, you can customize:
+ Your email and SMS message templates for one-time password (OTP) and multi-factor (MFA) authentication
+ Your SMS and email verification messages
+ The verification type for email—code or link
**Note**  
Amazon Cognito sends links with your link-based template in the verification messages when users sign up or resend a confirmation code. Emails from attribute-update and password-reset operations use the code template.
+ Your user invitation messages
+ FROM and REPLY-TO email addresses for emails going through your user pool

**Note**  
The SMS and email verification message templates only appear if you have chosen to require phone number and email verification. Similarly, the SMS MFA message template only appears if the MFA setting is **required** or **optional**.

**Topics**
+ [

## Message templates
](#cognito-user-pool-settings-message-templates)
+ [

## Customizing email and SMS MFA messages
](#cognito-user-pool-settings-SMS-message-customization)
+ [

## Customizing email verification messages
](#cognito-user-pool-settings-email-verification-message-customization)
+ [

## Customizing user invitation messages
](#cognito-user-pool-settings-user-invitation-message-customization)
+ [

## Customizing your email address
](#cognito-user-pool-settings-email-address-customization)
+ [

## Authorizing Amazon Cognito to send Amazon SES email on your behalf (from a custom FROM email address)
](#cognito-user-pool-settings-ses-authorization-to-send-email)

## Message templates
<a name="cognito-user-pool-settings-message-templates"></a>

You can use message templates to insert placeholders into your messages. Amazon Cognito replace the placeholders with the corresponding values. You can reference *Universal template placeholders* in message templates of any type, although these values won't be present in all message types.


**Universal template placeholders**  

|  Description  |  Token  | Message type | 
| --- | --- | --- | 
| Verification code | \$1\$1\$1\$1\$1\$1 | Verification, confirmation, and MFA messages | 
| Temporary password | \$1\$1\$1\$1\$1\$1 | Forgot-password and invitation messages | 
| User name | \$1username\$1 | Invitation and advanced security messages | 

One of the available automated responses with [threat protection](cognito-user-pool-settings-threat-protection.md) is to notify the user that Amazon Cognito detected potentially-malicious activity. You can use advanced security template placeholders to do the following:
+ Include specific details about an event such as IP address, city, country, sign-in time, and device name. Amazon Cognito threat protection can analyze these details.
+ Verify whether a one-click link is valid.
+ Use event ID, feedback token, and user name to build your own one-click link.

**Note**  
To generate one-click links and use the `{one-click-link-valid}` and `{one-click-link-invalid}` placeholders in advanced security email templates, you must already have a domain configured for your user pool.

Threat protection adds the following placeholders that you can insert into the message templates. These placeholders apply to **Adaptive authentication messages**, notifications that Amazon Cognito sends to users whose sessions have been evaluated for a level of risk. To configure message templates with these variables, update the **Full-function** configuration of your threat protection in the Amazon Cognito console, or submit templates in a [SetRiskConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetRiskConfiguration.html) request.


**Advanced security template placeholders**  

|  Description  |  Token  | 
| --- | --- | 
| IP address | \$1ip-address\$1 | 
| City | \$1city\$1 | 
| Country | \$1country\$1 | 
| Log-in time | \$1login-time\$1 | 
| Device name | \$1device-name\$1 | 
| One-click link is valid | \$1one-click-link-valid\$1 | 
| One-click link is not valid | \$1one-click-link-invalid\$1 | 
| Event ID | \$1event-id\$1 | 
| Feedback token | \$1feedback-token\$1 | 

## Customizing email and SMS MFA messages
<a name="cognito-user-pool-settings-SMS-message-customization"></a>

To customize the SMS and email messages for [multi-factor authentication (MFA)](user-pool-settings-mfa.md), edit **MFA message** from the **Message templates** menu in the Amazon Cognito user pools console.

**Important**  
Your custom message must contain the `{####}` placeholder. This placeholder is replaced with the authentication code before the message is sent.

Amazon Cognito sets a maximum length for SMS messages, including the authentication code, of 140 UTF-8 characters.

### Customizing SMS verification messages
<a name="cognito-user-pool-settings-SMS-verification-message-customization"></a>

To customize the SMS message for phone number verification, edit the **Verification message** template from the **Message templates** menu of your user pool.

**Important**  
Your custom message must contain the `{####}` placeholder. This placeholder is replaced with the verification code before the message is sent.

The maximum length for the message, including the verification code, is 140 UTF-8 characters.

## Customizing email verification messages
<a name="cognito-user-pool-settings-email-verification-message-customization"></a>

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

To customize the email subject and message content for email address verification messages, edit the **Verification message** template in the **Message templates** menu of your user pool. You can choose a **Verification type** of **Code** or **Link** when you edit your **Verification message** template.

When you choose **Code** as the verification type, your custom message must contain the `{####}` placeholder. When you send the message, the verification code replaces this placeholder.

When you choose **Link** as the verification type, your custom message must include a placeholder in the format `{##Verify Your Email##}`. You can change the text string between the placeholder characters, for example `{##Click here##}`. A verification link titled *Verify Your Email* replaces this placeholder.

The link for an email verification message directs your user to a URL like the following example.

```
https://<your user pool domain>/confirmUser/?client_id=abcdefg12345678&user_name=emailtest&confirmation_code=123456
```

The maximum length for the message, including the verification code (if present), is 20,000 UTF-8 characters. You can use HTML tags in this message to format the contents.

## Customizing user invitation messages
<a name="cognito-user-pool-settings-user-invitation-message-customization"></a>

You can customize the user invitation message that Amazon Cognito sends to new users by SMS or email message by editing the **Invitation messages** template in the **Message templates** menu.

**Important**  
Your custom message must contain the `{username}` and `{####}` placeholders. When Amazon Cognito sends the invitation message, it replaces these placeholders with your user's user name and password.

The maximum length of an SMS message, including the verification code, is 140 UTF-8 characters. The maximum length of an email message, including the verification code, is 20,000 UTF-8 characters. You may use HTML tags in your email messages to format the contents.

## Customizing your email address
<a name="cognito-user-pool-settings-email-address-customization"></a>

By default, Amazon Cognito sends email messages to users in your user pools from the address **no-reply@verificationemail.com**. You can choose to specify custom FROM and REPLY-TO email addresses instead of **no-reply@verificationemail.com**.

**To customize the FROM and REPLY-TO email addresses**

1. Navigate to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home), and choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Authentication methods** menu. Under **Email**, choose **Edit**.

1. Choose an **SES Region**.

1. Choose a **FROM email address** from the list of email addresses you have verified with Amazon SES in the **SES Region** you selected. To use an email address from a verified domain, configure email settings in the AWS Command Line Interface or the AWS API. For more information, see [Verifying email addresses and domains in Amazon SES](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html) in the *Amazon Simple Email Service Developer Guide*.

1. Choose a **Configuration set** from the list of configuration sets in your chosen **SES Region**.

1. Enter a friendly **FROM sender name** for your email messages, in the format `John Stiles <johnstiles@example.com>`.

1. To customize the REPLY-TO email address, enter a valid email address in the **REPLY-TO email address** field.

## Authorizing Amazon Cognito to send Amazon SES email on your behalf (from a custom FROM email address)
<a name="cognito-user-pool-settings-ses-authorization-to-send-email"></a>

You can configure Amazon Cognito to send email from a custom FROM email address instead of its default address. To use a custom address, you must give Amazon Cognito permission to send email message from an Amazon SES verified identity. In most cases, you can grant permission by creating a sending authorization policy. For more information, see [Using sending authorization with Amazon SES](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html) in the *Amazon Simple Email Service Developer Guide*. 

When you configure a user pool to use Amazon SES for email messages, Amazon Cognito creates the `AWSServiceRoleForAmazonCognitoIdpEmailService` role in your account to grant access to Amazon SES. No sending authorization policy is needed when the `AWSServiceRoleForAmazonCognitoIdpEmailService` service-linked role is used. You only need to add a sending authorization policy when you use both the default email functionality in your user pool *and* a verified Amazon SES identity as the FROM address.

For more information about the service-linked role that Amazon Cognito creates, see [Using service-linked roles for Amazon Cognito](using-service-linked-roles.md).

The following example sending authorization policy grants Amazon Cognito a limited ability to use an Amazon SES verified identity. Amazon Cognito can only send email messages when it does so on behalf of both the user pool in the `aws:SourceArn` condition and the account in the `aws:SourceAccount` condition. For more examples, see [Amazon SES sending authorization policy examples](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policy-examples.html) in the *Amazon Simple Email Service Developer Guide*.

**Note**  
In this example, the "Sid" value is an arbitrary string that uniquely identifies the statement. For more information about policy syntax, see [Amazon SES sending authorization policies](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html) in the *Amazon Simple Email Service Developer Guide*.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "stmnt1234567891234",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "email.cognito-idp.amazonaws.com"
                ]
            },
            "Action": [
                "SES:SendEmail",
                "SES:SendRawEmail"
            ],
            "Resource": "arn:aws:ses:us-east-1:111122223333:identity/support@example.com",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                },
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_EXAMPLE"
                }
            }
        }
    ]
}
```

------

The Amazon Cognito console adds a similar policy for you when you select an Amazon SES identity from the drop-down menu. If you use the CLI or API to configure the user pool, you must attach a policy structured like the previous example to your Amazon SES Identity.

# Creating user accounts as administrator
<a name="how-to-create-user-accounts"></a>

User pools aren't only a customer identity and access management (CIAM) user directory, where anyone on the internet can sign up for a user profile in your application. You can disable self-service sign-up. You might already know your customers and want to only admit those who have been authorized in advance. You can put manual authentication guardrails around your application with a [private SAML 2.0 or OIDC identity provider](cognito-user-pools-identity-federation.md), by [importing users](cognito-user-pools-import-users.md), by [screening users at sign-up](user-pool-lambda-pre-sign-up.md)—or by creating users with administrative API operations. Your workflow for administrative creation of users can be programmatic, provisioning users after they register in another system, or it can be on a case-by-case or testing basis in the Amazon Cognito console.

When you create users as an administrator, Amazon Cognito sets a temporary password for them and sends a welcome, or invitation, message. They can follow the link in their invitation message and sign in for the first time, setting a password and confirming their account. The page that follows describes how to create new users and configure the welcome message. For more information about user creation with the user pools API and an AWS SDK or CDK, see [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html).

After you create your user pool, you can create users using the AWS Management Console, as well as the AWS Command Line Interface or the Amazon Cognito API. You can create a profile for a new user in a user pool and send a welcome message with sign-up instructions to the user via SMS or email.

The following are some examples of how administrators can manage users in user pools.
+ Create a new user profile in the Amazon Cognito console or with the `AdminCreateUser` API operation.
+ Make username-and-password, passwordless, passkey, and custom [authentication flows](amazon-cognito-user-pools-authentication-flow-methods.md) available to your user pool and app client.
+ Set user attribute values.
+ Create custom attributes.
+ Set the value of immutable [custom attributes](user-pool-settings-attributes.md#user-pool-settings-custom-attributes) in `AdminCreateUser` API requests. This feature isn't available in the Amazon Cognito console.
+ Specify a temporary password, create a user without a password, or allow Amazon Cognito to automatically generate a password.
+ Create new users and automatically confirm their accounts, verify their email addresses, or verify their phone numbers.
+ Specify custom SMS and email invitation messages for new users via the AWS Management Console or Lambda triggers like [custom message](user-pool-lambda-custom-message.md), [custom SMS sender](user-pool-lambda-custom-sms-sender.md), and [custom email sender](user-pool-lambda-custom-email-sender.md).
+ Specify whether invitation messages are sent via SMS, email, or both.
+ Resend the welcome message to an existing user by calling the `AdminCreateUser` API, specifying `RESEND` for the `MessageAction` parameter.
+ [Suppress](#admincreateuserwalkthrough-step-invitationmessage) the sending of the invitation message when the user is created.
+ Specify an expiration time limit of up to 90 days for new user accounts.
+ Allow users to sign themselves up or require that new users only be added by the administrator.

Administrators can also sign users in with AWS credentials in a server-side application. For more information, see [Authorization models for API and SDK authentication](authentication-flows-public-server-side.md).

## User authentication flows and creating users
<a name="how-to-create-user-accounts-flows"></a>

Administrative creation of users has options that differ based on the configuration of your user pool. The *authentication flows*, or methods available to users for sign-in and MFA, can change how you create users and the messages that you send to them. The following are some authentication flows that are available in user pools.
+ Username and password
+ Passkeys
+ Sign-in with third-party IdPs
+ Passwordless with email and SMS one-time passwords (OTPs)
+ Multi-factor authentication with email, SMS, and authenticator-app OTPs
+ Custom authentication with Lambda triggers

For more information about how to configure these sign-in factors, see [Authentication with Amazon Cognito user pools](authentication.md).

## Create users without passwords
<a name="how-to-create-user-accounts-thingstoknow-passwordless"></a>

If you have enabled passwordless sign-in for your user pool, you can create users without passwords. To create a user without a password, you must provide attribute values for an available passwordless sign-in factor. For example, if email OTP passwordless sign-in is available in your user pool, you can create a user with no password and an email address attribute. If the only authentication flows available to new users require a password, for example passkey or username-password, you must create or generate a temporary password for each new user.

**To create a new user without a password**
+ Choose **Don't set a password** in the Amazon Cognito console
+ Omit or leave blank the `TemporaryPassword` parameter of your `AdminCreateUser` API request

**Users without passwords are automatically confirmed**  
Normally new users get a temporary password and go into a `FORCE_CHANGE_PASSWORD` status when you create them. When you create users without passwords, they immediately go into a `CONFIRMED` state. You can't resend confirmation codes to these users in the `CONFIRMED` state.

**Invitation messages change for users without passwords.**  
By default, Amazon Cognito sends an [invitation message](cognito-user-pool-settings-message-customizations.md#cognito-user-pool-settings-user-invitation-message-customization) to new users that says `Your username is {userName} and your password is {####}.` When you create users with no password, the message says `Your username is {userName}.` Customize your invitation message to reflect whether you will set passwords for users. Omit out the `{####}` password variable in passwordless authentication models.

**You can't autogenerate passwords when passwordless factors are available**  
If you have configured your user pool to support email or phone OTP passwordless sign-in, you can't automatically generate a password. For each user who will have a password, you must set a temporary password when you create their profile.

**Passwordless users must have values for all required attributes**  
When you create a user *without* a password, your request only succeeds if the user provides values for all attributes that you have marked as required in your user pool. This applies to any required attribute, not only the phone number and email attributes required for OTP delivery.

## Creating users who will provide required-attribute values later
<a name="how-to-create-user-accounts-thingstoknow-password-restrictions"></a>

You might want to require attributes in your user pool but collect those attributes after you administratively create users, during user interaction in your application. Administrators can omit values for required attributes when they create users *with temporary passwords*. You can't omit required-attribute values for passwordless users.

Users with missing values for required attributes and a temporary password get a [NEW\$1PASSWORD\$1REQUIRED](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html#CognitoUserPools-RespondToAuthChallenge-request-ChallengeResponses) challenge at first sign-in. They can then provide a value for the missing required attributes in the `requiredAttributes` parameter. You can create users with passwords and without required attributes only if all required attributes are [mutable](user-pool-settings-attributes.md#user-pool-settings-custom-attributes). Users can only complete sign-in with `NEW_PASSWORD_REQUIRED` challenges and required-attribute values if the required attributes are [writeable](user-pool-settings-client-apps.md#cognito-user-pools-app-idp-settings-about) from the app client they sign in with.

When you set a permanent password for an administrator-created user, their status changes to `CONFIRMED` and your user pool doesn't prompt them for a new password *or* required attributes at their first sign-in.

## Creating a new user in the AWS Management Console
<a name="creating-a-new-user-using-the-console"></a>

You can set user password requirements, configure the invitation and verification messages sent to users, and add new users with the Amazon Cognito console.

### Set a password policy and enable self-registration
<a name="set-user-password-policy"></a>

You can configure settings for minimum password complexity and whether users can sign up using public APIs in your user pool.

**Configure a password policy**

1. Navigate to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home), and choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Authentication methods** menu and locate **Password policy**. Choose **Edit**.

1. Choose a **Password policy mode** of **Custom**.

1. Choose a **Password minimum length**. For limits to the password length requirement, see [User pools resource quotas](https://docs.aws.amazon.com/cognito/latest/developerguide/limits.html#limits-hard).

1. Choose a **Password complexity** requirement.

1. Choose how long password set by administrators should be valid for.

1. Choose **Save changes**.

**Allow self-service sign-up**

1. Navigate to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home), and choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Sign-up** menu and locate **Self-service sign-up**. Select **Edit**.

1. Choose whether to **Enable self-registration**. Self-registration is typically used with public app clients that need to register new users in your user pool without distributing a client secret or AWS Identity and Access Management (IAM) API credentials.
**Disabling self-registration**  
If you do not enable self-registration, new users must be created by administrative API actions using IAM API credentials or by sign-in with federated providers.

1. Choose **Save changes**.

### Customize email and SMS messages
<a name="creating-a-new-user-customize-messages"></a>

**Customize user messages**

You can customize the messages that Amazon Cognito sends to your users when you invite them to sign in, they sign up for a user account, or they sign in and are prompted for multi-factor authentication (MFA).
**Note**  
An **Invitation message** is sent when you create a user in your user pool and invite them to sign in. Amazon Cognito sends initial sign-in information to the user's email address or phone number.  
A **Verification message** is sent when a user signs up for a user account in your user pool. Amazon Cognito sends a code to the user. When the user provides the code to Amazon Cognito, they verify their contact information and confirm their account for sign-in. Verification codes are valid for 24 hours.  
An **MFA message** is sent when you enable SMS MFA in your user pool, and a user that has configured SMS MFA signs in and is prompted for MFA.

1. Navigate to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home), and choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Message templates** menu and select **Verification message**, **Invitation message**, or **MFA message** and choose **Edit**.

1. Customize the messages for the chosen message type.
**Note**  
All variables in message templates must be included when you customize the message. If the variable, for example **\$1\$1\$1\$1\$1\$1**, is not included, your user will have insufficient information to complete the message action.  
For more information, see [Message templates](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-templates.html).

1. 

   1. **Verification messages**

      1. Choose a **Verification type** for **Email** messages. A **Code** verification sends a numeric code that the user must enter. A **Link** verification sends a link the user can click to verify their contact information. The text in the variable for a **Link** message is displayed as hyperlink text. For example, a message template using the variable \$1\$1\$1Click here\$1\$1\$1 is displayed as [Click here]() in the email message.

      1. Enter an **Email subject** for **Email** messages.

      1. Enter a custom **Email message** template for **Email** messages. You can customize this template with HTML.

      1. Enter a custom **SMS message** template for **SMS** messages.

      1. Choose **Save changes**.

   1. **Invitation messages**

      1. Enter an **Email subject** for **Email** messages.

      1. Enter a custom **Email message** template for **Email** messages. You can customize this template with HTML.

      1. Enter a custom **SMS message** template for **SMS** messages.

      1. Choose **Save changes**.

   1. **MFA messages**

      1. Enter a custom **SMS message** template for **SMS** messages.

      1. Choose **Save changes**.

### Create a user
<a name="creating-a-new-user-using-the-users-tab"></a>

**Create a user**

You can create new users for your user pool from the Amazon Cognito console. Typically, users can sign in after they set a password. To sign in with an email address, a user must verify the `email` attribute. To sign in with a phone number, the user must verify the `phone_number` attribute. To confirm accounts as an administrator, you can also use the AWS CLI or API, or create user profiles with a federated identity provider. For more information, see the [Amazon Cognito API Reference](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/).

1. Navigate to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home), and choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Users** menu, and choose **Create a user**.

1. Review the **User pool sign-in and security requirements** for guidance on password requirements, available account recovery methods, and alias attributes for your user pool.

1. <a name="admincreateuserwalkthrough-step-invitationmessage"></a>Choose how you want to send an **Invitation message**. Choose SMS message, email message, or both. To suppress the invitation message, choose **Don't send an invitation**.
**Note**  
Before you can send invitation messages, configure a sender and an AWS Region with Amazon Simple Notification Service and Amazon Simple Email Service in the **Authentication methods** menu of your user pool . Recipient message and data rates apply. Amazon SES bills you for email messages separately, and Amazon SNS bills you for SMS messages separately.

1. Choose a **Username** for the new user.

1. Choose if you want to **Create a password** or have Amazon Cognito **Generate a password** for the user. The option to generate a password isn't available if [passwordless sign-in](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless) is available in the user pool. Any temporary password must adhere to the user pool password policy.

1. Choose **Create**.

1. Choose the **Users** menu and choose the **User name** entry for the user. Add and edit **User attributes** and **Group memberships**. Review **User event history**.

# Adding groups to a user pool
<a name="cognito-user-pools-user-groups"></a>

Support for groups in Amazon Cognito user pools enables you to create and manage groups, add users to groups, and remove users from groups. Use groups to create collections of users to manage their permissions or to represent different types of users. You can assign an AWS Identity and Access Management (IAM) role to a group to define the permissions for members of a group.

You can use groups to create a collection of users in a user pool, which is often done to set the permissions for those users. For example, you can create separate groups for users who are readers, contributors, and editors of your website and app. Using the IAM role associated with a group, you can also set different permissions for those different groups so that only contributors can put content into Amazon S3 and only editors can publish content through an API in Amazon API Gateway.

Amazon Cognito creates a user group for each OIDC, SAMl, and social [identity provider](cognito-user-pools-identity-federation.md#cognito-user-pools-identity-federation-how-it-works) (IdP) that you add to your user pool. The name of the group is in the format `[user pool ID]_[IdP name]`, for example `us-east-1_EXAMPLE_MYSSO` or `us-east-1_EXAMPLE_Google`. Each unique automatically-generated IdP user profile is automatically added to this group. [Linked users](cognito-user-pools-identity-federation-consolidate-users.md) aren't automatically added to this group, but you can add their profiles to the group in a separate process.

You can create and manage groups in a user pool from the AWS Management Console, the APIs, and the CLI. As a developer (using AWS credentials), you can create, read, update, delete, and list the groups for a user pool. You can also add users and remove users from groups.

There is no additional cost for using groups within a user pool. See [Amazon Cognito Pricing](https://aws.amazon.com/cognito/pricing/) for more information.

## Assigning IAM roles to groups
<a name="assigning-iam-roles-to-groups"></a>

You can use groups to control permissions to your resources using an IAM role. IAM roles include trust policies and permission policies. The role [trust](https://docs.aws.amazon.com/cognito/latest/developerguide/role-trust-and-permissions.html) policy specifies who can use the role. The [permissions](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies) policies specify the actions and resources that your group members can access. When you create an IAM role, set up the role trust policy to allow your group's users to assume the role. In the role permissions policies, specify the permissions that you want your group to have.

When you create a group in Amazon Cognito, you specify an IAM role by providing the role’s [ARN](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-arns). When group members sign in using Amazon Cognito, they can receive temporary credentials from the identity pools. Their permissions are determined by the associated IAM role.

Individual users can be in multiple groups. As a developer, you have the following options for automatically choosing the IAM role when a user is in multiple groups:
+ You can assign precedence values to each group. The group with the better (lower) precedence will be chosen and its associated IAM role will be applied. 
+ Your app can also choose from among the available roles when requesting AWS credentials for a user through an identity pool, by specifying a role ARN in the [GetCredentialsForIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html) `CustomRoleARN` parameter. The specified IAM role must match a role that is available to the user.

## Assigning precedence values to groups
<a name="assigning-precedence-values-to-groups"></a>

A user can belong to more than one group. In the user's access and ID tokens, the `cognito:groups` claim contains the list of all the groups a user belongs to. The `cognito:roles` claim contains the list of roles corresponding to the groups.

Because a user can belong to more than one group, each group can be assigned a precedence. This is a non-negative number that specifies the precedence of this group relative to the other groups that a user belongs to in the user pool. Zero is the top precedence value. Groups with lower precedence values take precedence over groups with higher or null precedence values. If a user belongs to two or more groups, the group with the lowest precedence value will have its IAM role applied to the `cognito:preferred_role` claim in the user's ID token.

Two groups can have the same precedence value. If this happens, neither group takes precedence over the other. If two groups with the same precedence value have the same role ARN, that role is used in the `cognito:preferred_role` claim in ID tokens for users in each group. If the two groups have different role ARNs, the `cognito:preferred_role` claim is not set in users' ID tokens.

## Using groups to control permission with Amazon API Gateway
<a name="using-groups-to-control-permission-with-amazon-api-gateway"></a>

You can use groups in a user pool to control permission with Amazon API Gateway. The groups that a user is a member of are included in both the ID token and access token from a user pool in the `cognito:groups` claim. You can submit ID or access tokens with requests to Amazon API Gateway and use an Amazon Cognito user pool authorizer for a REST API. For more information, see [Control access to a REST API using Amazon Cognito user pools as authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) in the [API Gateway Developer Guide](https://docs.aws.amazon.com/apigateway/latest/developerguide/).

You can also authorize access to an Amazon API Gateway HTTP API with a custom JWT authorizer. For more information, see [Controlling access to HTTP APIs with JWT authorizers](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html) in the [API Gateway Developer Guide](https://docs.aws.amazon.com/apigateway/latest/developerguide/).

## Limitations on groups
<a name="user-pool-user-groups-limitations"></a>

User groups are subject to the following limitations:
+ The number of groups you can create is limited by the [Amazon Cognito service quotas](quotas.md).
+ Groups cannot be nested.
+ You cannot search for users in a group.
+ You cannot search for groups by name, but you can list groups.

## Creating a new group in the AWS Management Console
<a name="creating-a-new-group-using-the-console"></a>

Use the following procedure to create a new group.

**To create a new group**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Groups** menu, and then choose **Create a group**.

1. On the **Create a group** page, in **Group name**, enter a friendly name for your new group.

1. You can optionally provide additional information about this group using any of the following fields:
   + **Description** - Enter details about what this new group will be used for.
   + **Precedence** - Amazon Cognito evaluates and applies all group permissions for a given user based on which groups that they belong to has a lower precedence value. The group with the lower precedence will be chosen and its associated IAM role will be applied. For more information, see [Assigning precedence values to groups](#assigning-precedence-values-to-groups).
   + **IAM role** - You can assign an IAM role to your group when you need to control permissions to your resources. If you are integrating a user pool with an identity pool, the **IAM role** setting determines which role is assigned in the user's ID token if the identity pool is configured to choose the role from the token. For more information, see [Assigning IAM roles to groups](#assigning-iam-roles-to-groups).
   + **Add users to this group** - Add existing users as members of this group after it is created.

1. Choose **Create** to confirm.

# Managing and searching for user accounts
<a name="how-to-manage-user-accounts"></a>

Users pools can contains millions of users. Working with a dataset of this size is a challenge for administrators. Amazon Cognito has tools for finding and modifying user profiles. The top methods for finding users are the **Users** menu of the Amazon Cognito console, and with [ListUsers](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html). Of the methods that retrieve information about users, these are the options that don't have a cost impact unlike, for example, [AdminGetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetUser.html).

This section of the guide has information about finding and updating user profiles in a user pool.

## Viewing user attributes
<a name="manage-user-accounts-viewing-user-attributes"></a>

Use the following procedure to view user attributes in the Amazon Cognito console.

**To view user attributes**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Users** menu and select a user in the list.

1. On the user details page, under **User attributes**, you can view which attributes are associated with the user.

## Resetting a user's password
<a name="manage-user-accounts-reset-user-password"></a>

Use the following procedure to reset a user's password in the Amazon Cognito console.

**To reset a user's password**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Users** menu and select a user in the list.

1. On the user details page, choose **Actions**, **Reset password**.

1. In the **Reset password** dialog, review the information and when ready, choose **Reset**.

   This action immediately results in a confirmation code being sent to the user and disables the user’s current password by changing the user state to `RESET_REQUIRED`. The **Reset password** code is valid for 1 hour.

## Enable, disable, and delete user accounts
<a name="manage-user-accounts-enable-disable"></a>

You can delete unused user profiles or, if you want to temporarily prevent access, disable them. Users can delete their own accounts, but only user pool administrators can enable and disable user accounts.

**Effect of deletion**  
Users can't sign in with deleted user accounts and to regain access, must sign up or be created again.

**Effect of disabling accounts**  
When you disable a user account, Amazon Cognito automatically invalidates all authenticated sessions, deactivates the user account for sign-in, and [revokes their access and refresh tokens](token-revocation.md). Amazon Cognito returns an `invalid_request` error with the message `User is not enabled` when a user tries to sign in to an account that you disabled. This behavior doesn't change with your [user existence disclosure settings](cognito-user-pool-managing-errors.md) for the app client. You can disable local user accounts and the local profiles of federated user accounts. When users sign in with managed login or the classic hosted UI, then you disable their account, and then they try to sign in again with the the browser cookie that maintains their authenticated session, Amazon Cognito redirects them to the login page.

**Effect of enabling accounts**  
Users can immediately sign in to accounts after you enable them. User accounts are enabled by default. Users' attributes and passwords remain the same as before their account was disabled. Tokens that your application revoked, whether you disabled the user account or separately revoked the refresh token, remain non-valid after you enable the user account that owned the token.

------
#### [ Delete a user account (console) ]

**To delete a user account**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Users** menu and select the radio button next to the username of a user in the list.

1. Choose **Delete**.

1. Choose **Disable user access**.

1. Choose **Delete**.

------
#### [ Delete a user account (API) ]

Users can delete their accounts with the self-service access-token-authorized [DeleteUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUser.html) API operation. The following is an example `DeleteUser` request body.

```
{
   "AccessToken": "eyJra456defEXAMPLE"
}
```

Administrators can delete user accounts with the IAM-authorized [AdminDeleteUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDeleteUser.html) API operation. The following is an example `AdminDeleteUser` request body.

```
{
   "Username": "testuser",
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

------
#### [ Disable a user account (console) ]

**To disable a user account**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Users** menu and select the username of a user in the list.

1. On the user details page, choose **Actions**, **Disable user access**.

1. In the dialog that this creates, choose **Disable**.

------
#### [ Disable a user account (API) ]

Administrators can disable user accounts with the IAM-authorized [AdminDisableUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDisableUser.html) API operation. The following is an example `AdminDisableUser` request body.

```
{
   "Username": "testuser",
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

------
#### [ Enable a user account (console) ]

**To enable a user account**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Users** menu and select the username of a user in the list.

1. On the user details page, choose **Actions**, **Enable user access**.

1. In the dialog that this creates, choose **Enable**.

------
#### [ Enable a user account (API) ]

Administrators can enable user accounts with the IAM-authorized [AdminEnableUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminEnableUser.html) API operation. The following is an example `AdminEnableUser` request body.

```
{
   "Username": "testuser",
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

------

## Searching user attributes
<a name="manage-user-accounts-searching-user-attributes"></a>

If you have already created a user pool, you can search from the **Users** panel in the AWS Management Console. You can also use the Amazon Cognito [ListUsers API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html), which accepts a **Filter** parameter.

You can search for any of the following standard attributes. Custom attributes are not searchable.
+ username (case-sensitive)
+ email
+ phone\$1number
+ name
+ given\$1name
+ family\$1name
+ preferred\$1username
+ cognito:user\$1status (called **Status** in the Console) (case-insensitive)
+ status (called **Enabled** in the Console) (case-sensitive)
+ sub

**Note**  
You can also list users with a client-side filter. The server-side filter matches no more than 1 attribute. For advanced search, use a client-side filter with the `--query` parameter of the `list-users` action in the AWS Command Line Interface. When you use a client-side filter, ListUsers returns a paginated list of zero or more users. You can receive multiple pages in a row with zero results. Repeat the query with each pagination token that is returned until you receive a null pagination token value, then review the combined result.  
For more information about server-side and client-side filtering, see [Filtering AWS CLI output](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html) in the AWS Command Line Interface User Guide.

## Searching for users with the AWS Management Console
<a name="cognito-user-pools-manage-user-accounts-searching-for-users-using-console"></a>

If you have already created a user pool, you can search from the **Users** panel in the AWS Management Console.

AWS Management Console searches are always prefix ("starts with") searches.

**To search for a user in the Amazon Cognito console**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). You might be prompted for your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Users** menu and enter the username in the search field. Note that some attribute values are case-sensitive (for example, **Username**).

   You can also find users by adjusting the search filter to narrow the scope down to other user properties, such as **Email**, **Phone number**, or **Last name**.

## Searching for users with the `ListUsers` API
<a name="cognito-user-pools-searching-for-users-using-listusers-api"></a>

 To search for users from your app, use the Amazon Cognito [ListUsers API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html). This API uses the following parameters: 
+  `AttributesToGet`: An array of strings, where each string is the name of a user attribute to be returned for each user in the search results. To retrieve all attributes, don't include an `AttributesToGet` parameter or request `AttributesToGet` with a value of the literal string `null`.
+  `Filter`: A filter string of the form "`AttributeName` `Filter-Type` "`AttributeValue`"". Quotation marks within the filter string must be escaped using the backslash (`\`) character. For example, `"family_name = \"Reddy\""`. If the filter string is empty, `ListUsers` returns all users in the user pool. 
  +  `AttributeName`: The name of the attribute to search for. You can only search for one attribute at a time. 
**Note**  
You can only search for standard attributes. Custom attributes are not searchable. This is because only indexed attributes are searchable, and custom attributes cannot be indexed.
  +  `Filter-Type`: For an exact match, use `=`, for example, `given_name = "Jon"`. For a prefix ("starts with") match, use `^=`, for example, `given_name ^= "Jon"`. 
  +  `AttributeValue`: The attribute value that must be matched for each user.
+  `Limit`: Maximum number of users to be returned.
+  `PaginationToken`: A token to get more results from a previous search. Amazon Cognito expires the pagination token after one hour.
+  `UserPoolId`: The user pool ID for the user pool on which the search should be performed.

All searches are case-insensitive. Search results are sorted by the attribute named by the `AttributeName` string, in ascending order.

## Examples of using the `ListUsers` API
<a name="cognito-user-pools-searching-for-users-listusers-api-examples"></a>

The following example returns all users and includes all attributes.

```
{
    "AttributesToGet": null,
    "Filter": "",
    "Limit": 10,
    "UserPoolId": "us-east-1_samplepool"
}
```

The following example returns all users whose phone numbers start with "\$11312" and includes all attributes.

```
{
    "AttributesToGet": null,
    "Filter": "phone_number ^= \"+1312\"",
    "Limit": 10,
    "UserPoolId": "us-east-1_samplepool"
}
```

The following example returns the first 10 users whose family name is "Reddy". For each user, the search results include the user's given name, phone number, and email address. If there are more than 10 matching users in the user pool, the response includes a pagination token.

```
{
    "AttributesToGet": [
        "given_name", 
        "phone_number", 
        "email"
    ],
    "Filter": "family_name = \"Reddy\"",
    "Limit": 10,
    "UserPoolId": "us-east-1_samplepool"
}
```

If the previous example returns a pagination token, the following example returns the next 10 users that match the same filter string.

```
{
    "AttributesToGet": [
        "given_name", 
        "phone_number", 
        "email"
    ],
    "Filter": "family_name = \"Reddy\"",
    "Limit": 10,
    "PaginationToken": "pagination_token_from_previous_search",
    "UserPoolId": "us-east-1_samplepool"
}
```

# Passwords, account recovery, and password policies
<a name="managing-users-passwords"></a>

All users who sign in to a user pool, even [federated users](cognito-terms.md#terms-federateduser), have passwords assigned to their user profiles. [Local users](cognito-terms.md#terms-localuser) and [linked users](cognito-terms.md#terms-linkeduser) must provide a password when they sign in. Federated users don't use user pool passwords, but sign in with their identity provider (IdP). You can permit users to reset their own passwords, reset or change passwords as an administrator, and [set policies](#user-pool-settings-policies) for password complexity and history.

Amazon Cognito doesn't store user passwords in plaintext. Instead, it stores a hash of each user's password with a user-specific salt. Because of this, you can't retrieve existing passwords from the user profiles in your user pools. As a best practice, don't store plaintext user passwords anywhere. Perform password resets when users forget their passwords.

## Password reset and recovery
<a name="user-pool-password-reset-and-recovery"></a>

Users forget their passwords. You might want them to be able to reset their password themselves, or you might want to require that an administrator resets their password for them. Amazon Cognito user pools have options for both models. This part of the guide covers the user pool settings and the API operations for password reset.

The [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html) API operation and the managed login option **Forgot your password?** send users a code that, when they confirm that they have the correct code, gives them an opportunity to set a new password with [ConfirmForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html). This is the self-service password-recovery model.

**Recovery of unverified users**  
You can send recovery messages to users who have verified their email address or phone number. If they don't have a confirmed recovery email or phone, a user pool administrator can mark their email address or phone number verified. Edit the user's **User attributes** in the Amazon Cognito console and select the checkbox next to **Mark phone number as verified** or **Mark email address as verified**. You can also set `email_verified` or `phone_number_verified` to true in an [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) request. For new users, the [ResendConfirmationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html) API operation sends a new code to their email address or phone number and they can complete self-service confirmation and verification.

**Reset passwords as an administrator**  
The [AdminSetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html) and [AdminResetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html) API operations are the administrator-inititated methods of password reset. `AdminSetUserPassword` sets a temporary or permanent password, and `AdminResetUserPassword` sends users a password-reset code in the same way as `ForgotPassword`.

### Configure password reset and recovery
<a name="user-pool-password-reset-and-recovery-configure"></a>

Amazon Cognito automatically selects your account-recovery options from the required attributes and sign-in options that you choose when you create a user pool in the console. You can modify these default settings.

A user's preferred MFA method influences the methods they can use to recover their password. Users whose preferred MFA is by email message can't receive a password-reset code by email. Users whose preferred MFA is by SMS message can't receive a password-reset code by SMS.

Your [password recovery](#user-pool-password-reset-and-recovery) settings must provide an alternative option when users aren't eligible for your preferred password-reset method. For example, your recovery mechanisms might have email as first priority and email MFA might be an option in your user pool. In this case, add SMS-message account recovery as a second option or use administrative API operations to reset passwords for those users.

Amazon Cognito replies to password-reset requests from users who don't have a valid recovery method with an `InvalidParameterException` error response.

**Note**  
Users can't receive MFA and password reset codes at the same email address or phone number. If they use one-time passwords (OTPs) from email messages for MFA, they must use SMS messages for account recovery. If they use OTPs from SMS messages for MFA, they must use email messages for account recovery. In user pools with MFA, users might be unable to complete self-service password recovery if they have attributes for their email address but no phone number, or their phone number but no email address.  
To prevent the state where users can't reset their passwords in user pools with this configuration, set the `email` and `phone_number` [attributes as required](user-pool-settings-attributes.md). As an alternative, you can set up processes that always collect and set those attributes when users sign up or when your administrators create user profiles. When users have both attributes, Amazon Cognito automatically sends password-reset codes to the destination that is *not* the user's MFA factor.

The following procedure configures self-service account recovery in a user pool.

------
#### [ Configure self-service password reset (API/SDK) ]

The `AccountRecoverySetting` parameter is the user pool parameter that sets the methods that users can use to recover their password in [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html) API requests or when they select **Forgot password?** in managed login. `ForgotPassword` sends a recovery code to a verified email or a verified phone number. The recovery code is valid for one hour. When you specify an [AccountRecoverySetting](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AccountRecoverySettingType.html) for your user pool, Amazon Cognito chooses the code delivery destination based on the priority that you set.

When you define `AccountRecoverySetting` and a user has SMS MFA configured, SMS cannot be used as an account recovery mechanism. The priority for this setting is determined with `1` being of the highest priority. Amazon Cognito sends a verification to only one of the specified methods. The following example `AccountRecoverySetting` sets email addresses as the primary destination for account-recovery codes, falling back to SMS message if the user doesn't have an email address attribute.

```
"AccountRecoverySetting": { 
   "RecoveryMechanisms": [ 
      { 
         "Name": "verified_email",
         "Priority": 1
      },
      { 
         "Name": "verified_phone_number",
         "Priority": 2
      }
   ]
}
```

The value `admin_only` turns off self-service account recovery, instead requiring users to contact their administrator for password reset. You cannot use `admin_only` with any other account recovery mechanism. The following e

```
"AccountRecoverySetting": { 
   "RecoveryMechanisms": [ 
      { 
         "Name": "admin_only",
         "Priority": 1
      }
   ]
}
```

If you do not specify `AccountRecoverySetting`, Amazon Cognito sends the recovery code to a verified phone number first, and to a verified email address if users don't have a phone number attribute.

For more information about `AccountRecoverySetting`, see [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) and [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html).

------
#### [ Configure self-service password reset (console) ]

Configure account-recovery and password-reset options from the **Sign-in** menu of your user pool.

**To set up user account recovery**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home).

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Sign-in** menu. Locate **User account recovery** and choose **Edit**

1. To permit users to reset their own passwords, choose **Enable self-service account recovery**.

1. Configure the delivery method for the password-recovery codes that your user pool sends to users. Under **Delivery method for user account recovery messages**, select an available option. As a best practice, choose an option that has a secondary method for sending messages, for example **Email if available, otherwise SMS**. With a secondary delivery method, Amazon Cognito can send codes to users in a way that requires them to use a different medium for password reset than for MFA.

1. Select **Save changes**.

------

### Forgot password behavior
<a name="forgot-password"></a>

In a given hour, we allow between 5 and 20 attempts for a user to request or enter a password reset code as part of forgot-password and confirm-forgot-password actions. The exact value depends on the risk parameters associated with the requests. Please note that this behavior is subject to change. 

## Adding user pool password requirements
<a name="user-pool-settings-policies"></a>

Strong, complex passwords are a security best practice for your user pool. Especially in applications that are open to the internet, weak passwords can expose your users' credentials to systems that guess passwords and try to access your data. The more complex a password is, the more difficult it is to guess. Amazon Cognito has additional tools for security-conscious administrators, like [threat protection](cognito-user-pool-settings-threat-protection.md#cognito-user-pool-settings-threat-protection.title) and [AWS WAF web ACLs](user-pool-waf.md#user-pool-waf.title), but your password policy is a central element of the security of your user directory.

Passwords for local users in Amazon Cognito user pools don't automatically expire. As a best practice, log the time, date, and metadata of user password resets in an external system. With an external log of password age, your application or a Lambda trigger can look up a user's password age and require a reset after a given period.

You can configure your user pool to require a minimum password complexity that conforms to your security standards. Complex passwords have a minimum length of at least eight characters. They also include a mix of uppercase, numeric, and special characters.

With the Essentials or Plus feature tiers, you can also set a policy for password reuse. You can prevent a user from resetting their password to a new password that matches their current password or any of up to 23 additional previous passwords, for a maximum total of 24.

**To set a user pool password policy**

1. Create a user pool and navigate to the **Configure security requirements** step, or access an existing user pool and navigate to the **Authentication methods** menu.

1. Navigate to **Password policy**.

1. Choose a **Password policy mode**. **Cognito defaults** configures your user pool with the recommended minimum settings. You can also choose a **Custom** password policy.

1. Set a **Password minimum length**. All users must sign up or be created with a password whose length is greater than or equal to this value. You can set this minimum value as high as 99, but your users can set passwords up to 256 characters long.

1. Configure password complexity rules under **Password requirements**. Choose the character types–numbers, special characters, uppercase letters, and lowercase letters–that you want to require at least one of in each user's password.

   You can require at least one of the following characters in passwords. After Amazon Cognito verifies that passwords contain the minimum required characters, your users' passwords can contain additional characters of any type up to the maximum password length.
   + Uppercase and lowercase [basic latin](https://en.wikipedia.org/wiki/ISO_basic_Latin_alphabet) letters
   + Numbers
   + The following special characters.

     ```
     ^ $ * . [ ] { } ( ) ? " ! @ # % & / \ , > < ' : ; | _ ~ ` = + - 
     ```
   + Non-leading, non-trailing space characters.

1. Set a value for **Temporary passwords set by administrators expire in**. After this period has passed, a new user that you created in the Amazon Cognito console or with `AdminCreateUser` can't sign in and set a new password. After they sign in with their temporary password, their user accounts never expire. To update the password duration in the Amazon Cognito user pools API, set a value for [TemporaryPasswordValidityDays ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_PasswordPolicyType.html#CognitoUserPools-Type-PasswordPolicyType-TemporaryPasswordValidityDays) in your [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request.

1. Set a value for **Prevent use of previous passwords**, if available. To use this feature, choose the Essentials or Plus [feature tier](cognito-sign-in-feature-plans.md) in your user pool. The value of this parameter is the number of previous passwords that a new password is prevented from matching when a user resets their password.

To reset access for an expired user account, do one of the following:
+ Send a new temporary password and reset the expiration period with an [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html) API request that has `MessageAction` set to `RESEND`.
+ Delete the user profile and create a new one.
+ Generate a new confirmation code in an [AdminResetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html) API request.

# Importing users into a user pool
<a name="cognito-user-pools-import-users"></a>

There are two ways you can import or migrate users from your existing user directory or user database into Amazon Cognito user pools. You can migrate users when they sign-in using Amazon Cognito for the first time with a user migration Lambda trigger. With this approach, users can continue using their existing passwords and will not have to reset them after the migration to your user pool. Alternatively, you can migrate users in bulk by uploading a CSV file containing the user profile attributes for all users. The following sections describe both these approaches.

**More resources**
+ [Approaches for migrating users to Amazon Cognito user pools](https://aws.amazon.com/blogs/security/approaches-for-migrating-users-to-amazon-cognito-user-pools/)
+ [AWS re:Inforce 2023 - Migrating to Amazon Cognito](https://www.youtube.com/watch?v=OkDj9uXWwCc)

**Topics**
+ [

# Importing users with a user migration Lambda trigger
](cognito-user-pools-import-using-lambda.md)
+ [

# Importing users into user pools from a CSV file
](cognito-user-pools-using-import-tool.md)

# Importing users with a user migration Lambda trigger
<a name="cognito-user-pools-import-using-lambda"></a>

With this approach, you can seamlessly migrate users from your existing user directory to user pools when a user signs in for the first time with your app or requests a password reset. Add a [Migrate user Lambda trigger](user-pool-lambda-migrate-user.md) function to your user pool and it receives metadata about users who try to sign in, and returns user profile information from an external identity source. For details and example code for this Lambda trigger, including request and response parameters, see [Migrate user Lambda trigger parameters](user-pool-lambda-migrate-user.md#cognito-user-pools-lambda-trigger-syntax-user-migration).

Before you start to migrate users, create a user migration Lambda function in your AWS account, and set the Lambda function as the user migration trigger in your user pool. Add an authorization policy to your Lambda function that permits only the Amazon Cognito service account principal, `cognito-idp.amazonaws.com` to invoke the Lambda function, and only in the context of your own user pool. For more information, see [Using resource-based policies for AWS Lambda (Lambda function policies)](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html). 

**Sign-in process**

1. The user opens your app and signs in with the Amazon Cognito user pools API or through managed login. For more information about how to facilitate sign-in with Amazon Cognito APIs, see [Integrating Amazon Cognito authentication and authorization with web and mobile apps](cognito-integrate-apps.md).

1. Your app sends the user name and password to Amazon Cognito. If your app has a custom sign-in UI that you built with an AWS SDK, your app must use [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) with the `USER_PASSWORD_AUTH` or `ADMIN_USER_PASSWORD_AUTH` flow. When your app uses one of these flows, the SDK sends the password to the server.
**Note**  
Before you add a user migration trigger, activate the `USER_PASSWORD_AUTH` or `ADMIN_USER_PASSWORD_AUTH` flow in the settings of your app client. You must use these flows instead of the default `USER_SRP_AUTH` flow. Amazon Cognito must send a password to your Lambda function so that it can verify your user's authentication in the other directory. An SRP obscures your user's password from your Lambda function.

1. Amazon Cognito checks if the submitted user name matches a user name or alias in the user pool. You can set the user's email address, phone number, or preferred user name as an alias in your user pool. If the user doesn't exist, Amazon Cognito sends parameters, including the user name and password, to your [Migrate user Lambda trigger](user-pool-lambda-migrate-user.md) function.

1. Your [Migrate user Lambda trigger](user-pool-lambda-migrate-user.md) function checks for or authenticates the user with your existing user directory or user database. The function returns user attributes that Amazon Cognito stores in the user's profile in the user pool. You can return a `username` parameter only if the submitted user name matches an alias attribute. If you want users to continue to use their existing passwords, your function sets the attribute `finalUserStatus` to `CONFIRMED` in the Lambda response. Your app must return all `"response"` parameters shown at [Migrate user Lambda trigger parameters](user-pool-lambda-migrate-user.md#cognito-user-pools-lambda-trigger-syntax-user-migration).
**Important**  
Do not log the entire request event object in your user migration Lambda code. This request event object includes the user's password. If you don't sanitize the logs, passwords appear in CloudWatch Logs.

1. Amazon Cognito creates the user profile in your user pool, and returns tokens to your app client.

1. Your app performs token intake, accepts the user authentication, and proceeds to the requested content.

After you migrate your users, use `USER_SRP_AUTH` for sign-in. The Secure Remote Password (SRP) protocol doesn't send the password across the network, and provides security benefits over the `USER_PASSWORD_AUTH` flow that you use during migration.

In case of errors during migration, including client device or network issues, your app receives error responses from the Amazon Cognito user pools API. When this happens, Amazon Cognito might or might not create the user account in your user pool. The user should then attempt to sign in again. If sign-in fails repeatedly, attempt to reset the user's password with the forgot-password flow in your app. 

The forgot-password flow also invokes your [Migrate user Lambda trigger](user-pool-lambda-migrate-user.md) function with a `UserMigration_ForgotPassword` event source. Because the user doesn't submit a password when they request a password reset, Amazon Cognito doesn't include a password in the event that it sends to your Lambda function. Your function can only look up the user in your existing user directory and return attributes to add to the user profile in your user pool. After your function completes its invocation and returns its response to Amazon Cognito, your user pool sends a password reset code by email or SMS. In your app, prompt your user for their confirmation code and a new password, then send that information to Amazon Cognito in a [ConfirmForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html) API request. You can also use the built-in pages for the forgot-password flow in managed login.

**Additional resources**
+ [Approaches for migrating users to Amazon Cognito user pools](https://aws.amazon.com/blogs/security/approaches-for-migrating-users-to-amazon-cognito-user-pools/)

# Importing users into user pools from a CSV file
<a name="cognito-user-pools-using-import-tool"></a>

When you have an external identity store and the time to prepare your user pool for new local users, a bulk user import from a comma-separated values (CSV) file can be a low-effort, low-cost option for a migration to an Amazon Cognito user pool. A CSV file import is a process of downloading and populating a template file, then handing off the file to your user pool in an import job. You can use a CSV import to quickly create test users. You can also programmatically populate the file with read API requests to your external identity store, followed by parsing their details and attributes into write operations to the file.

The import process sets values for all user attributes except **password**. Password import is not supported, because security best practices require that passwords are not available as plain text, and we don't support importing hashes. This means that your users must change their passwords the first time they sign in. Your users are in a `RESET_REQUIRED` state when imported using this method.

The lowest-effort way to import users from a CSV is to activate [passwordless sign-in](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless) in your user pool. With email address and phone number attributes and the right user pool configuration, users can sign in with email or SMS one-time passwords (OTPs) immediately after your import job completes. For more information, see [Requiring imported users to reset their passwords](#cognito-user-pools-using-import-tool-password-reset).

You can also set your users' passwords with an [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html) API request that sets the `Permanent` parameter to `true`. CSV import doesn't contribute to the billed monthly active users (MAUs) in your user pool. However, password-reset operations do generate MAUs. To manage costs when you import large numbers of users with password who might not be immediately active, set up your application to prompt users for a new password when they sign in and receive the `RESET_REQUIRED` challenge.

**Note**  
The creation date for each user is the time when that user was imported into the user pool. Creation date is not one of the imported attributes.

**Steps to create a user import job**

1. Create an Amazon CloudWatch Logs role in the AWS Identity and Access Management (IAM) console.

1. Create the user import .csv file.

1. Create and run the user import job.

1. Upload the user import .csv file.

1. Start and run the user import job.

1. Use CloudWatch to check the event log.

1. Require the imported users to reset their passwords.

**More resources**
+ [Cognito User Profiles Export Reference Architecture](https://aws.amazon.com/solutions/implementations/cognito-user-profiles-export-reference-architecture/) for exporting user accounts between user pools

**Topics**
+ [

## Creating the CloudWatch Logs IAM role
](#cognito-user-pools-using-import-tool-cli-cloudwatch-iam-role)
+ [

## Creating the user import CSV file
](#cognito-user-pools-using-import-tool-csv-header)
+ [

## Creating and running the Amazon Cognito user pool import job
](#cognito-user-pools-creating-import-job)
+ [

## Viewing the user pool import results in the CloudWatch console
](#cognito-user-pools-using-import-tool-cloudwatch)
+ [

## Requiring imported users to reset their passwords
](#cognito-user-pools-using-import-tool-password-reset)

## Creating the CloudWatch Logs IAM role
<a name="cognito-user-pools-using-import-tool-cli-cloudwatch-iam-role"></a>

If you're using the Amazon Cognito CLI or API, then you need to create a CloudWatch IAM role. The following procedure describes how to create an IAM role that Amazon Cognito can use to write the results of your import job to CloudWatch Logs. 

**Note**  
When you create an import job in the Amazon Cognito console, you can create the IAM role at the same time. When you choose to **Create a new IAM role**, Amazon Cognito automatically applies the appropriate trust policy and IAM policy to the role.

**To create the CloudWatch Logs IAM role for user pool import (AWS CLI, API)**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. Create a new IAM role for an AWS service. For detailed instructions, see [Creating a role for an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html#roles-creatingrole-service-console) in the *AWS Identity and Access Management User Guide*.

   1. When you select a **Use case** for your **Trusted entity type**, choose any service. Amazon Cognito isn't currently listed in service use cases.

   1. In the **Add permissions** screen, choose **Create policy** and insert the following policy statement. Replace *REGION* with the AWS Region of your user pool, for example `us-east-1`. Replace *ACCOUNT* with your AWS account ID, for example `111122223333`.

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "logs:CreateLogGroup",
                      "logs:CreateLogStream",
                      "logs:DescribeLogStreams",
                      "logs:PutLogEvents"
                  ],
                  "Resource": [
                      "arn:aws:logs:us-east-1:111122223333:log-group:/aws/cognito/*"
                  ]
              }
          ]
      }
      ```

------

1. Because you didn't choose Amazon Cognito as the trusted entity when you created the role, you now must manually edit the trust relationship of the role. Choose **Roles** from navigation pane of the IAM console, then choose the new role that you created.

1. Choose the **Trust relationships** tab.

1. Choose **Edit trust policy**.

1. Paste the following policy statement into **Edit trust policy**, replacing any existing text: 

------
#### [ JSON ]

****  

   ```
   {
           "Version":"2012-10-17",		 	 	 
           "Statement": [
               {
                   "Effect": "Allow",
                   "Principal": {
                       "Service": "cognito-idp.amazonaws.com"
                   },
                   "Action": "sts:AssumeRole"
               }
           ]
       }
   ```

------

1. Choose **Update policy**. 

1. Note the role ARN. You'll provide the ARN when you create your import job.

## Creating the user import CSV file
<a name="cognito-user-pools-using-import-tool-csv-header"></a>

Before you can import your existing users into your user pool, you must create a comma-separated values (CSV) file that contains the users that you want to import, and their attributes. From your user pool, you can retrieve a user import file with headers that reflect the attribute schema of your user pool. You can then insert user information that matches the formatting requirements in [Formatting the CSV file](#cognito-user-pools-using-import-tool-formatting-csv-file). 

### Downloading the CSV file header (console)
<a name="cognito-user-pools-using-import-tool-downloading-csv-header-console"></a>

Use the following procedure to download the CSV header file.

**To download the CSV file header**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). You might be prompted for your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Users** menu.

1. In the **Import users** section, choose **Create an import job**.

1. Under **Upload CSV**, select the *template.csv* link and download the CSV file.

### Downloading the CSV file header (AWS CLI)
<a name="cognito-user-pools-using-import-tool-downloading-csv-header-using-cli"></a>

To get a list of the correct headers, from the **Users menu** under **Import users**, select **Create import job**. In the dialog that follows, select the `template.csv` link to download a template file with your user pool attributes.

You can also run the following CLI command, where *USER\$1POOL\$1ID* is the user pool identifier for the user pool you'll import users into:

```
aws cognito-idp get-csv-header --user-pool-id "USER_POOL_ID"
```

Sample response:

```
{
    "CSVHeader": [
        "name",
        "given_name",
        "family_name",
        "middle_name",
        "nickname",
        "preferred_username",
        "profile",
        "picture",
        "website",
        "email",
        "email_verified",
        "gender",
        "birthdate",
        "zoneinfo",
        "locale",
        "phone_number",
        "phone_number_verified",
        "address",
        "updated_at",
        "cognito:mfa_enabled",
        "cognito:username"
    ],
    "UserPoolId": "USER_POOL_ID"
}
```

### Formatting the CSV file
<a name="cognito-user-pools-using-import-tool-formatting-csv-file"></a>

 The downloaded user import CSV header file looks like the following string. It also includes any custom attributes you have added to your user pool.

```
cognito:username,name,given_name,family_name,middle_name,nickname,preferred_username,profile,picture,website,email,email_verified,gender,birthdate,zoneinfo,locale,phone_number,phone_number_verified,address,updated_at,cognito:mfa_enabled
```

Edit your CSV file so that it includes this header and the attribute values for your users, and is formatted according to the following rules:

**Note**  
For more information about attribute values, such as proper format for phone numbers, see [Working with user attributes](user-pool-settings-attributes.md).
+ The first row in the file is the downloaded header row, which contains the user attribute names.
+ The order of columns in the CSV file doesn't matter.
+ Each row after the first row contains the attribute values for a user.
+ All columns in the header must be present, but you don't need to provide values in every column.
+ The following attributes are required:
  + **cognito:username**
  + **email\$1verified** or **phone\$1number\$1verified**
    + At least one of the auto-verified attributes must be `true` for each user. An auto-verified attribute is an email address or phone number that Amazon Cognito automatically sends a code to when a new user joins your user pool.
    + The user pool must have at least one auto-verified attribute, either **email\$1verified** or **phone\$1number\$1verified**. If the user pool has no auto-verified attributes, the import job will not start.
    + If the user pool only has one auto-verified attribute, that attribute must be verified for each user. For example, if the user pool has only **phone\$1number** as an auto-verified attribute, the **phone\$1number\$1verified** value must be `true` for each user.
**Note**  
For users to reset their passwords, they must have a verified email or phone number. Amazon Cognito sends a message containing a reset password code to the email or phone number specified in the CSV file. If the message is sent to the phone number, it is sent by SMS message. For more information, see [Verifying contact information at sign-up](signing-up-users-in-your-app.md#allowing-users-to-sign-up-and-confirm-themselves).
  + **email** (if **email\$1verified** is `true`)
  + **phone\$1number** (if **phone\$1number\$1verified** is `true`)
  + Any attributes that you marked as required when you created the user pool
+ Attribute values that are strings should *not* be in quotation marks.
+ If an attribute value contains a comma, you must put a backslash (\$1) before the comma. This is because the fields in a CSV file are separated by commas.
+ The CSV file contents should be in UTF-8 format without byte order mark.
+ The **cognito:username** field is required and must be unique within your user pool. It can be any Unicode string. However, it cannot contain spaces or tabs.
+ The **birthdate** values, if present, must be in the format **mm/dd/yyyy**. This means, for example, that a birthdate of February 1, 1985 must be encoded as **02/01/1985**.
+ The **cognito:mfa\$1enabled** field must correspond to the MFA requirements of your user pool. If you've set multi-factor authentication (MFA) to be required in your user pool, this field must be `true` or blank for all users. If you've set MFA to be off, this field must be `false` or blank for all users. A blank value sets imported users' MFA-enabled status to the state required by the user pool. You can import users in an MFA-required user pool without a valid MFA factor, regardless of whether you set a `cognito:mfa_enabled` value. Users in this state have MFA active but can't sign in until they configure an email attribute, phone number attribute, or a TOTP, and that configuration is a valid MFA factor in your user pool.
+ The maximum row length is 16,000 characters.
+ The maximum CSV file size is 100 MB.
+ The maximum number of rows (users) in the file is 500,000. This maximum doesn't include the header row.
+ The **updated\$1at** field value is expected to be epoch time in seconds, for example: **1471453471**.
+ Any leading or trailing white space in an attribute value will be trimmed.

The following list is a example CSV import file for a user pool with no custom attributes. Your user pool schema might differ from this example. In that case, you must provide test values in the CSV template that you download from your user pool.

```
cognito:username,name,given_name,family_name,middle_name,nickname,preferred_username,profile,picture,website,email,email_verified,gender,birthdate,zoneinfo,locale,phone_number,phone_number_verified,address,updated_at,cognito:mfa_enabled
John,,John,Doe,,,,,,,johndoe@example.com,TRUE,,02/01/1985,,,+12345550100,TRUE,123 Any Street,,FALSE
Jane,,Jane,Roe,,,,,,,janeroe@example.com,TRUE,,01/01/1985,,,+12345550199,TRUE,100 Main Street,,FALSE
```

## Creating and running the Amazon Cognito user pool import job
<a name="cognito-user-pools-creating-import-job"></a>

This section describes how to create and run the user pool import job by using the Amazon Cognito console and the AWS Command Line Interface (AWS CLI).

**Topics**
+ [

### Importing users from a CSV file (console)
](#cognito-user-pools-using-import-tool-console)
+ [

### Importing users (AWS CLI)
](#cognito-user-pools-using-import-tool-cli)

### Importing users from a CSV file (console)
<a name="cognito-user-pools-using-import-tool-console"></a>

The following procedure describes how to import the users from the CSV file.

**To import users from the CSV file (console)**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). You might be prompted for your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Users** menu.

1. In the **Import users** section, choose **Create an import job**.

1. On the **Create import job** page, enter a **Job name**.

1. Choose to **Create a new IAM role** or to **Use an existing IAM role**.

   1. If you chose **Create a new IAM role**, enter a name for your new role. Amazon Cognito will automatically create a role with the correct permissions and trust relationship. The IAM principal that creates the import job must have permissions to create IAM roles.

   1. If you chose **Use an existing IAM role**, choose a role from the list under **IAM role selection**. This role must have the permissions and trust policy described in [Creating the CloudWatch Logs IAM role](#cognito-user-pools-using-import-tool-cli-cloudwatch-iam-role).

1. Under **Upload CSV**, choose **Choose file** and attach the CSV file that you prepared.

1. Choose **Create job** to submit your job, but start it later. Choose **Create and start job** to submit your job and start it immediately.

1. If you created your job but didn't start it, you can start it later. In the **Users** menu under **Import users**, choose your import job, then select **Start**. You can also submit a [StartUserImportJob](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_StartUserImportJob.html) API request from an AWS SDK.

1. Monitor the progress of your user import job in the **Users** menu under **Import users**. If your job doesn't succeed, you can select the **Status** value. For additional details, select **View the CloudWatch logs for more details** and review any issues in the CloudWatch Logs console.

### Importing users (AWS CLI)
<a name="cognito-user-pools-using-import-tool-cli"></a>

The following CLI commands are available for importing users into a user pool:
+ `create-user-import-job`
+ `get-csv-header`
+ `describe-user-import-job`
+ `list-user-import-jobs`
+ `start-user-import-job`
+ `stop-user-import-job`

To get the list of command line options for these commands, use the `help` command line option. For example:

```
aws cognito-idp get-csv-header help
```

#### Creating a user import job
<a name="cognito-user-pools-using-import-tool-cli-creating-user-import-job"></a>

After you create your CSV file, create a user import job by running the following CLI command, where *JOB\$1NAME* is the name you're choosing for the job, *USER\$1POOL\$1ID* is the user pool ID for the user pool into which the new users will be added, and *ROLE\$1ARN* is the role ARN you received in [Creating the CloudWatch Logs IAM role](#cognito-user-pools-using-import-tool-cli-cloudwatch-iam-role): 

```
aws cognito-idp create-user-import-job --job-name "JOB_NAME" --user-pool-id "USER_POOL_ID" --cloud-watch-logs-role-arn "ROLE_ARN"
```

The *PRE\$1SIGNED\$1URL* returned in the response is valid for 15 minutes. After that time, it will expire and you must create a new user import job to get a new URL.

**Example response:**  

```
{
    "UserImportJob": {
        "Status": "Created",
        "SkippedUsers": 0,
        "UserPoolId": "USER_POOL_ID",
        "ImportedUsers": 0,
        "JobName": "JOB_NAME",
        "JobId": "JOB_ID",
        "PreSignedUrl": "PRE_SIGNED_URL",
        "CloudWatchLogsRoleArn": "ROLE_ARN",
        "FailedUsers": 0,
        "CreationDate": 1470957431.965
    }
}
```

#### Status values for a user import job
<a name="cognito-user-pools-using-import-tool-cli-status-values-for-user-import-job"></a>

In the responses to your user import commands, you'll see one of the following `Status` values:
+ `Created` - The job was created but not started.
+ `Pending` - A transition state. You have started the job, but it has not begun importing users yet.
+ `InProgress` - The job has started, and users are being imported.
+ `Stopping` - You have stopped the job, but the job has not stopped importing users yet.
+ `Stopped` - You have stopped the job, and the job has stopped importing users.
+ `Succeeded` - The job has completed successfully.
+ `Failed` - The job has stopped due to an error.
+ `Expired` - You created a job, but did not start the job within 24-48 hours. All data associated with the job was deleted, and the job can't be started.

#### Uploading the CSV file
<a name="cognito-user-pools-using-import-tool-cli-uploading-csv-file"></a>

Use the following `curl` command to upload the CSV file containing your user data to the presigned URL that you obtained from the response of the `create-user-import-job` command.

```
curl -v -T "PATH_TO_CSV_FILE" -H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL"
```

In the output of this command, look for the phrase `"We are completely uploaded and fine"`. This phrase indicates that the file was uploaded successfully. Your user pools don't keep the information in your import files after you run your import jobs. After they complete or expire, Amazon Cognito deletes your uploaded CSV file.

#### Describing a user import job
<a name="cognito-user-pools-using-import-tool-cli-describing-user-import-job"></a>

To get a description of your user import job, use the following command, where *USER\$1POOL\$1ID* is your user pool ID, and *JOB\$1ID* is the job ID that was returned when you created the user import job. 

```
aws cognito-idp describe-user-import-job --user-pool-id "USER_POOL_ID" --job-id "JOB_ID"
```

**Example Sample response:**  

```
{
    "UserImportJob": {
        "Status": "Created",
        "SkippedUsers": 0,
        "UserPoolId": "USER_POOL_ID",
        "ImportedUsers": 0,
        "JobName": "JOB_NAME",
        "JobId": "JOB_ID",
        "PreSignedUrl": "PRE_SIGNED_URL",
        "CloudWatchLogsRoleArn":"ROLE_ARN",
        "FailedUsers": 0,
        "CreationDate": 1470957431.965
    }
}
```

In the preceding sample output, the *PRE\$1SIGNED\$1URL* is the URL that you uploaded the CSV file to. The *ROLE\$1ARN* is the CloudWatch Logs role ARN that you received when you created the role.

#### Listing your user import jobs
<a name="cognito-user-pools-using-import-tool-cli-listing-user-import-jobs"></a>

To list your user import jobs, use the following command:

```
aws cognito-idp list-user-import-jobs --user-pool-id "USER_POOL_ID" --max-results 2
```

**Example Sample response:**  

```
{
    "UserImportJobs": [
        {
            "Status": "Created",
            "SkippedUsers": 0,
            "UserPoolId": "USER_POOL_ID",
            "ImportedUsers": 0,
            "JobName": "JOB_NAME",
            "JobId": "JOB_ID",
            "PreSignedUrl":"PRE_SIGNED_URL",
            "CloudWatchLogsRoleArn":"ROLE_ARN",
            "FailedUsers": 0,
            "CreationDate": 1470957431.965
        },
        {
            "CompletionDate": 1470954227.701,
            "StartDate": 1470954226.086,
            "Status": "Failed",
            "UserPoolId": "USER_POOL_ID",
            "ImportedUsers": 0,
            "SkippedUsers": 0,
            "JobName": "JOB_NAME",
            "CompletionMessage": "Too many users have failed or been skipped during the import.",
            "JobId": "JOB_ID",
            "PreSignedUrl":"PRE_SIGNED_URL",
            "CloudWatchLogsRoleArn":"ROLE_ARN",
            "FailedUsers": 5,
            "CreationDate": 1470953929.313
        }
    ],
    "PaginationToken": "PAGINATION_TOKEN"
}
```

Jobs are listed in chronological order from last created to first created. The *PAGINATION\$1TOKEN* string after the second job indicates that there are additional results for this list command. To list the additional results, use the `--pagination-token` option as follows:

```
aws cognito-idp list-user-import-jobs --user-pool-id "USER_POOL_ID" --max-results 10 --pagination-token "PAGINATION_TOKEN"
```

#### Starting a user import job
<a name="cognito-user-pools-using-import-tool-cli-starting-user-import-job"></a>

To start a user import job, use the following command:

```
aws cognito-idp start-user-import-job --user-pool-id "USER_POOL_ID" --job-id "JOB_ID"
```

Only one import job can be active at a time per account.

**Example Sample response:**  

```
{
    "UserImportJob": {
        "Status": "Pending",
        "StartDate": 1470957851.483,
        "UserPoolId": "USER_POOL_ID",
        "ImportedUsers": 0,
        "SkippedUsers": 0,
        "JobName": "JOB_NAME",
        "JobId": "JOB_ID",
        "PreSignedUrl":"PRE_SIGNED_URL",
        "CloudWatchLogsRoleArn": "ROLE_ARN",
        "FailedUsers": 0,
        "CreationDate": 1470957431.965
    }
}
```

#### Stopping a user import job
<a name="cognito-user-pools-using-import-tool-cli-stopping-user-import-job"></a>

To stop a user import job while it is in progress, use the following command. After you stop the job, it cannot be restarted.

```
aws cognito-idp stop-user-import-job --user-pool-id "USER_POOL_ID" --job-id "JOB_ID"
```

**Example Sample response:**  

```
{
    "UserImportJob": {
        "CompletionDate": 1470958050.571,
        "StartDate": 1470958047.797,
        "Status": "Stopped",
        "UserPoolId": "USER_POOL_ID",
        "ImportedUsers": 0,
        "SkippedUsers": 0,
        "JobName": "JOB_NAME",
        "CompletionMessage": "The Import Job was stopped by the developer.",
        "JobId": "JOB_ID",
        "PreSignedUrl":"PRE_SIGNED_URL",
        "CloudWatchLogsRoleArn": "ROLE_ARN",
        "FailedUsers": 0,
        "CreationDate": 1470957972.387
    }
}
```

## Viewing the user pool import results in the CloudWatch console
<a name="cognito-user-pools-using-import-tool-cloudwatch"></a>

You can view the results of your import job in the Amazon CloudWatch console.

**Topics**
+ [

### Viewing the results
](#cognito-user-pools-using-import-tool-viewing-the-results)
+ [

### Interpreting the results
](#cognito-user-pools-using-import-tool-interpreting-the-results)

### Viewing the results
<a name="cognito-user-pools-using-import-tool-viewing-the-results"></a>

The following steps describe how to view the user pool import results.

**To view the results of the user pool import**

1. Sign in to the AWS Management Console and open the CloudWatch console at [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/).

1. Choose **Logs**.

1. Choose the log group for your user pool import jobs. The log group name is in the form `/aws/cognito/userpools/USER_POOL_ID/USER_POOL_NAME`.

1. Choose the log for the user import job you just ran. The log name is in the form *JOB\$1ID*/*JOB\$1NAME*. The results in the log refer to your users by line number. No user data is written to the log. For each user, a line similar to the following appears:
   + `[SUCCEEDED] Line Number 5956 - The import succeeded.`
   + `[SKIPPED] Line Number 5956 - The user already exists.`
   + `[FAILED] Line Number 5956 - The User Record does not set any of the auto verified attributes to true. (Example: email_verified to true).`

### Interpreting the results
<a name="cognito-user-pools-using-import-tool-interpreting-the-results"></a>

Successfully imported users have their status set to "PasswordReset".

In the following cases, the user will not be imported, but the import job will continue:
+ No auto-verified attributes are set to `true`.
+ The user data doesn't match the schema.
+ The user couldn't be imported due to an internal error.

In the following cases, the import job will fail:
+ The Amazon CloudWatch Logs role cannot be assumed, doesn't have the correct access policy, or has been deleted.
+ The user pool has been deleted.
+ Amazon Cognito is unable to parse the .csv file.

## Requiring imported users to reset their passwords
<a name="cognito-user-pools-using-import-tool-password-reset"></a>

If your user pool only offers password-based sign-in, users must reset their passwords after they are imported. The first time they sign in, they can enter *any* password. Amazon Cognito prompts them to enter a new password in the API response to the sign-in request from your application.

If your user pool has passwordless authentication factors, Amazon Cognito defaults to those for imported users. They're not prompted for a new password, and can sign in immediately with a passwordless email or SMS OTP. You can also prompt users to set a password so that they can complete other sign-in methods like username-password and passkey. The following conditions apply to passwordless sign-in after user import.

1. You must import users with an attribute that corresponds to an available passwordless sign-in factor. If users can sign in with an email address, you must import an `email` attribute. If a phone number, you must import a `phone_number` attribute. If both, import a value for either attribute.

1. Normally, users import in a `RESET_REQUIRED` state where they must reset their password. If they are imported with the ability to sign in with a passwordless factor, Amazon Cognito sets their state to `CONFIRMED`.

For more information about passwordless authentication including how to set it up and how to construct the authentication flow in your application, see [Authentication with Amazon Cognito user pools](authentication.md).

The following procedure describes the user experience in a custom-built login mechanism with local users in a `RESET_REQUIRED` after you import a CSV file. If your users sign in with managed login, instruct them to select the **Forgot password?** option, provide the code from their email or text message, and set a password.

**Requiring imported users to reset their passwords**

1. In your app, silently attempt sign-in for the current user with `InitiateAuth` using a random password.

1. Amazon Cognito returns a `NotAuthorizedException` when `PreventUserExistenceErrors` is enabled. Otherwise, it returns `PasswordResetRequiredException`.

1. Your app makes a `ForgotPassword` API request and resets the user's password.

   1. The app submits the username in a `ForgotPassword` API request.

   1. Amazon Cognito sends a code to the verified email or phone number. The destination depends on the values you provided for `email_verified` and `phone_number_verified` in your CSV file. The response to the `ForgotPassword` request indicates the destination of the code.
**Note**  
Your user pool must be configured to verify emails or phone numbers. For more information, see [Signing up and confirming user accounts](signing-up-users-in-your-app.md).

   1. Your app displays a message to your user to check the location where the code was sent, and prompts your user to enter the code and a new password.

   1. The user enters the code and new password in the app.

   1. The app submits the code and new password in a `ConfirmForgotPassword` API request.

   1. Your app redirects your user to sign-in.

# Working with user attributes
<a name="user-pool-settings-attributes"></a>

Attributes are pieces of information that help you identify individual users, such as name, email address, and phone number. A new user pool has a set of default *standard attributes*. You can also add custom attributes to your user pool definition in the AWS Management Console. This topic describes those attributes in detail and gives you tips on how to set up your user pool.

Don't store all information about your users in attributes. For example, keep user data that changes frequently, such as usage statistics or game scores, in a separate data store, such as Amazon Cognito Sync or Amazon DynamoDB.

Sanitize the inputs for user-attribute string values before you submit them to your user pool. One method to analyze proposed user attribute values is with a Lambda trigger like [pre sign-up](user-pool-lambda-pre-sign-up.md).

**Note**  
Some documentation and standards refer to attributes as *members*.

**Topics**
+ [

## Standard attributes
](#cognito-user-pools-standard-attributes)
+ [

## Username and preferred username
](#user-pool-settings-usernames)
+ [

## Customizing sign-in attributes
](#user-pool-settings-aliases)
+ [

## Custom attributes
](#user-pool-settings-custom-attributes)
+ [

## Attribute permissions and scopes
](#user-pool-settings-attribute-permissions-and-scopes)

## Standard attributes
<a name="cognito-user-pools-standard-attributes"></a>

Amazon Cognito assigns all users a set of standard attributes based on the [OpenID Connect specification](http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). By default, standard and custom attribute values can be any string with a length of up to 2048 characters, but some attribute values have format restrictions. 

The standard attributes are:
+ `name`
+ `family_name`
+ `given_name`
+ `middle_name`
+ `nickname`
+ `preferred_username`
+ `profile`
+ `picture`
+ `website`
+ `gender`
+ `birthdate`
+ `zoneinfo`
+ `locale`
+ `updated_at`
+ `address`
+ `email`
+ `phone_number`
+ `sub`

Except for `sub`, standard attributes are optional by default for all users. To make an attribute required, during the user pool creation process, select the **Required** check box next to the attribute. Amazon Cognito assigns a unique user identifier value to each user's `sub` attribute. Only the **email** and **phone\$1number** attributes can be verified.

Standard attributes have predefined properties that you can view in the `SchemaAttributes` parameter of a [DescribeUserPool API response](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPool.html#API_DescribeUserPool_ResponseSyntax). You can set custom values for these attribute properties, like data type, mutability, and length constraints. To modify standard attribute properties, set their custom values in the [CreateUserPool Schema parameter](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-Schema). The schema is also where you set required attributes. You can't modify the properties of standard attributes when you create user pools in the Amazon Cognito console.

**Note**  
 When you mark a standard attribute as **Required**, a user can't register unless they provide a value for the attribute. To create users and not give values for required attributes, administrators can use the [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) API. After you create a user pool, you can't switch an attribute between required and not required.Standard attribute details and format restrictions

**birthdate**  
Value must be a valid 10 character date in the format YYYY-MM-DD.

**email**  
Users and administrators can verify email address values.  
An administrator with proper AWS account permissions can change the user's email address and also mark it as verified. Mark an email address as verified with the [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) API or the [admin-update-user-attributes](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-update-user-attributes.html) AWS Command Line Interface (AWS CLI) command. With this command, the administrator can change the `email_verified` attribute to `true`. You can also edit a user in the **Users** menu of the Amazon Cognito console to mark an email address as verified.  
Value must be a [valid email address string](https://datatracker.ietf.org/doc/html/rfc3696#section-3) following the standard email format with @ symbol and domain, up to 2048 characters in length.

**phone\$1number**  
A user must provide a phone number if SMS multi-factor authentication (MFA) is active. For more information, see [Adding MFA to a user pool](user-pool-settings-mfa.md).  
Users and administrators can verify phone number values.  
An administrator with proper AWS account permissions can change the user's phone number and also mark it as verified. Mark a phone number as verified with the [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) API or the [admin-update-user-attributes](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-update-user-attributes.html) AWS CLI command. With this command, the administrator can change the `phone_number_verified` attribute to `true`. You can also edit a user in the **Users** menu of the Amazon Cognito console to mark a phone number as verified.  
Phone numbers must follow these format rules: A phone number must start with a plus (**\$1**) sign, followed immediately by the country code. A phone number can only contain the **\$1** sign and digits. Remove any other characters from a phone number, such as parentheses, spaces, or dashes (**-**) before you submit the value to the service. For example, a phone number based in the United States must follow this format: **\$114325551212**.

**preferred\$1username**  
You can select `preferred_username` as required or as an alias, but not both. If the `preferred_username` is an alias, you can make a request to the [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html) API operation and add the attribute value after you confirm the user.

**sub**  
Index and search your users based on the `sub` attribute. The `sub` attribute is a unique user identifier within each user pool. Users can change attributes like `phone_number` and `email`. The `sub` attribute has a fixed value. For more information about finding users, see [Managing and searching for user accounts](how-to-manage-user-accounts.md).

### View required attributes
<a name="how-to-edit-standard-attributes"></a>

Use the following procedure to view required attributes for a given user pool.

**Note**  
You can't change required attributes after you create a user pool.

**To view required attributes**

1. Go to [Amazon Cognito](https://console.aws.amazon.com/cognito/home) in the AWS Management Console. If the console prompts you, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Sign-up** menu.

1. In the **Required attributes** section, view the required attributes of your user pool.

## Username and preferred username
<a name="user-pool-settings-usernames"></a>

The `username` value is a separate attribute and not the same as the `name` attribute. Each user has a `username` attribute. Amazon Cognito automatically generates a username for federated users. You must provide a `username` attribute to create a local user in the Amazon Cognito directory. After you create a user, you can't change the value of the `username` attribute.

Developers can use the `preferred_username` attribute to give users usernames that they can change. For more information, see [Customizing sign-in attributes](#user-pool-settings-aliases).

If your application doesn't require a username, you don't need to ask users to provide one. Your app can create a unique username for users in the background. This can be useful if you want users to register and sign in with an email address and password. For more information, see [Customizing sign-in attributes](#user-pool-settings-aliases).

The `username` must be unique within a user pool. A `username` can be reused, but only after you delete it and it is no longer in use. For information about the string constraints to the `username` attributes, see the *username* property of a [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html#CognitoUserPools-SignUp-request-Username) API request.

## Customizing sign-in attributes
<a name="user-pool-settings-aliases"></a>

When you create a user pool, you can set up *username attributes* if you want your users to be able to sign up and sign in with an email address or phone number as their username. Alternatively, you can set up *alias attributes* to give your users the option: they can include multiple attributes when they sign up, and then sign in with a username, preferred username, email address, or phone number.

**Important**  
After you create a user pool, you can't change this setting.

### How to choose between alias attributes and username attributes
<a name="user-pool-settings-aliases-settings"></a>


| Your requirement | Alias attributes | Username attributes | 
| --- |--- |--- |
| Users have multiple sign-in attributes | Yes¹ | No² | 
| Users must verify email address or phone number before they can sign in with it | Yes | No | 
| Sign up users with duplicate email addresses or phone numbers and prevent UsernameExistsException errors³ | Yes | No | 
| Can assign the same email address or phone number attribute value to more than one user | Yes⁴ | No | 

¹ Available sign-in attributes are username, email address, phone number, and preferred username.

² Can sign in with email address or phone number.

³ Your user pool doesn't generate `UsernameExistsException` errors when users register with potentially-duplicate email addresses or phone numbers, but no username. This behavior is independent of **Prevent username existence errors**, which applies to sign-in, but not sign-up, operations.

⁴ Only the last user who has verified the attribute can sign in with it.

#### Option 1: Multiple sign-in attributes (alias attributes)
<a name="user-pool-settings-aliases-settings-option-1"></a>

An attribute is an *alias* when users have a username but can also sign in with that attribute. Set up aliases when you want to allow your users to choose between their username and other attribute values in the username field of your sign-in form. The `username` attribute is a fixed value that users can't change. If you mark an attribute as an alias, users can sign in with that attribute in place of the username. You can mark the email address, phone number, and preferred username attributes as aliases. For example, if you select email address and phone number as aliases for a user pool, users in that user pool can sign in with their username, email address, or phone number, along with their password.

To choose alias attributes, select **User name** and at least one additional sign-in option when you create your user pool.

**Note**  
When you configure your user pool to be case insensitive, a user can use either lowercase or uppercase letters to sign up or sign in with their alias. For more information, see [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) in the *Amazon Cognito user pools API Reference*.

If you select email address as an alias, Amazon Cognito doesn't accept a username that matches a valid email address format. Similarly, if you select phone number as an alias, Amazon Cognito doesn't accept a username for that user pool that matches a valid phone number format.

**Note**  
Alias values must be unique in a user pool. If you configure an alias for an email address or phone number, the value that you provide can be in a verified state in only one account. During sign-up, if your user provides an email address or phone number as an alias value and another user has already used that alias value, registration succeeds. However, when a user tries to confirm the account with this email (or phone number) and enters the valid code, Amazon Cognito returns an `AliasExistsException` error. The error indicates to the user that an account with this email address (or phone number) already exists. At this point, the user can abandon their attempt to create the new account and instead try to reset the password for the old account. If the user continues to create the new account, your app must call the `ConfirmSignUp` API with the `forceAliasCreation` option. `ConfirmSignUp` with `forceAliasCreation` moves the alias from the previous account to the newly created account, and marks the attribute unverified in the previous account.

Phone numbers and email addresses only become active aliases for a user after your user verifies the phone numbers and email addresses. We recommend that you choose automatic verification of email addresses and phone numbers if you use them as aliases.

Choose alias attributes to prevent `UsernameExistsException` errors for email address and phone number attributes when your users sign up.

Activate the `preferred_username` attribute so that your user can change the username that they use to sign in while their `username` attribute value doesn't change. If you want to set up this user experience, submit the new `username` value as a `preferred_username` and choose `preferred_username` as an alias. Then users can sign in with the new value that they entered. If you select `preferred_username` as an alias, your user can provide the value only when they confirm an account. They can't provide the value during registration.

When the user signs up with a username, you can choose if they can sign in with one or more of the following aliases.
+ Verified email address
+ Verified phone number
+ Preferred username

After the user signs up, they can change these aliases.

**Important**  
When your user pool supports sign-in with aliases and you want to authorize or look up a user, don't identify your user by any of their sign-in attributes. The fixed-value user identifier `sub` is the only consistent indicator of your user's identity.

Include the following steps when you create the user pool so that users can sign in with an alias.

------
#### [ Phone number or email address (console) ]

You must set email address and phone number as alias attributes when you create a user pool.

**To create a user pool with username aliases in the Amazon Cognito console**

1. Go to [Amazon Cognito](https://console.aws.amazon.com/cognito/home) in the AWS Management Console. If the console prompts you, enter your AWS credentials.

1. Create a new user pool with the **Get started** or **Create user pool** button.

1. Choose application settings in **Define your application**.

1. In **Configure options** under **Options for sign-in identifiers**, select the checkbox next to **Username** and at least one of the other options, **Email** and **Phone number**.

1. Choose your alias attributes as **Required attributes for sign-up**. In the managed login sign-up form, Amazon Cognito prompts new users to provide values for required attributes.

1. Under **Add a return URL**, set up an application callback URL for redirect after managed login sign-in.

1. Choose **Create**.

------
#### [ Phone number or email address (API/SDK) ]

Create a new user pool with the [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) API operation. Configure the `AliasAttributes` parameter as shown. You can remove the `email` entry if you only want phone-number aliases, or remove the `phone_number` entry if you only want email-address aliases.

```
"AliasAttributes": [
   "email",
   "phone_number"
],
```

------
#### [ Preferred username (API/SDK) ]

The Amazon Cognito console creates user pools without `preferred_username` as an alias. To create user pools with a `preferred_username` alias, set up user pools with [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) API requests in an AWS SDK. To support the creation of preferred username attributes at sign-up, set `preferred_username` as a required attribute. In the managed login sign-up form, Amazon Cognito prompts new users to provide values for required attributes. You *can* set `preferred_username` as a required attribute in the Amazon Cognito console, but this doesn't make it available as an alias.

**Configure as an alias**  
Configure `preferred_username` as an alias in the `AliasAttributes` parameter of a `CreateUserPool` request as shown. Remove any values that you don't want as alias attributes from the list.

```
"AliasAttributes": [
   "email",
   "phone_number",
   "preferred_username"
],
```

**Configure as required**  
In the managed login sign-up form, Amazon Cognito prompts new users to provide values for required attributes. Configure `preferred_username` as required in the `SchemaAttributes` parameter of a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) request.

To set preferred username as a required attribute, configure it as shown. The following example modifies the default schema of `preferred_username` to set it as required. Other schema parameters like `AttributeDataType` (defaults to `string`) and `StringAttributeConstraints` (defaults to 1-99 characters in length) assume default values.

```
"Schema": [
   {
      "Name": "preferred_username",
      "Required": true
   }
]
```

------

#### Option 2: Email address or phone number as a sign-in attribute (username attributes)
<a name="user-pool-settings-aliases-settings-option-2"></a>

When the user signs up with an email address or phone number as their username, you can choose if they can sign up with only email addresses, only phone numbers, or either one. 

To choose username attributes, don't select **Username** as a sign-in option when you create your user pool.

The email address or phone number must be unique, and it must not already be in use by another user. It doesn't have to be verified. After the user has signed up with an email address or phone number, the user can't create a new account with the same email address or phone number. The user can only reuse the existing account and reset the account password, if needed. However, the user can change the email address or phone number to a new email address or phone number. If the email address or phone number isn't already in use, it becomes the new username.

When you select both email address and phone number as username attributes, users can sign in with one or the other, even if they provide values for both attributes. The sign-in username is based on the value that you pass in the `Username` parameter of [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html#CognitoUserPools-SignUp-request-Username).

**Note**  
If a user signs up with an email address as their username, they can change the username to another email address, but they can't change it to a phone number. If they sign up with a phone number, they can change the username to another phone number, but they can't change it to an email address.

Use the following steps during the user pool creation process to set up sign-up and sign-in with email address or phone number.

------
#### [ Username attributes (console) ]

The following procedure creates a user pool with email address or phone number username attributes. The difference in the process for username attributes in the Amazon Cognito console is that you don't also set **Username** as a sign-in attribute.

**To create a user pool with username attributes in the Amazon Cognito console**

1. Go to [Amazon Cognito](https://console.aws.amazon.com/cognito/home) in the AWS Management Console. If the console prompts you, enter your AWS credentials.

1. Create a new user pool with the **Get started** or **Create user pool** button.

1. Choose application settings in **Define your application**.

1. In **Configure options** under **Options for sign-in identifiers**, select your username attributes: **Email**, **Phone number**, or both. Leave **Username** unchecked.

1. As a best practice, select your username attributes as **Required attributes for sign-up**. In the managed login sign-up form, Amazon Cognito prompts new users to provide values for required attributes. If you don't set your username attributes as required, Amazon Cognito doesn't prompt new users to provide values for them. In that scenario, you must configure your application to collect and submit email addresses or phone numbers for each user before they can sign in.

1. Under **Add a return URL**, set up an application callback URL for redirect after managed login sign-in.

1. Choose **Create**.

------
#### [ Username attributes (API/SDK) ]

In a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) request, configure the `UsernameAttributes` parameter as shown. To allow sign-in only with email-address usernames, specify `email` alone in this list. To allow sign-in only with phone-number usernames, specify `phone_number` alone. This parameter overrides username as a sign-in option.

```
"UsernameAttributes": [ 
   "email",
   "phone_number"
],
```

------

When you configure username attributes, your can make [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) API requests that pass an email address or phone number in the `username` parameter. The following is the behavior of the code`SignUp` API operation with username attributes.
+ If the `username` string is in valid email address format, for example `user@example.com`, the user pool automatically populates the `email` attribute of the user with the `username` value.
+ If the `username` string is in valid phone number format, for example `+12065551212`, the user pool automatically populates the `phone_number` attribute of the user with the `username` value.
+ If the `username` string format isn't in email address or phone number format, the `SignUp` API returns an exception.
+ If the `username` string contains an email address or phone number that is already in use, the `SignUp` API returns an exception.
+ The `SignUp` API populates the `username` attribute with a [UUID](cognito-terms.md#terms-uuid) for your user. This UUID has the same value as the `sub` claim in the user identity token.

You can use an email address or phone number in place of the username in all APIs except the [ListUsers](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html) operation. In `ListUsers` API requests, you can specify a `Filter` of `email` or `phone_number`. If you filter by `username`, you must supply the UUID username, not the email address or phone number.

## Custom attributes
<a name="user-pool-settings-custom-attributes"></a>

You can add up to 50 custom attributes to your user pool. You can specify a minimum and/or maximum length for custom attributes. However, the maximum length for any custom attribute can be no more than 2048 characters. The name of a custom attribute must match the regular expression pattern that's described in the `Name` parameter of [SchemaAttributeType](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SchemaAttributeType.html).

**Each custom attribute has the following characteristics:**
+ You can define it as a string, number, boolean, or `DateTime` object. Amazon Cognito writes custom attribute values to the ID token only as strings.
**Note**  
In the Amazon Cognito console, you can add custom attributes only of the string and number data types. Additional options like boolean and `DateTime` attribute data types are only available in the `SchemaAttributes` property of [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) and [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API requests.
+ You can't require that users provide a value for the attribute.
+ You can't remove or change it after you add it to the user pool.
+ The character length of the attribute name is within the limit that Amazon Cognito accepts. For more information, see [Quotas in Amazon Cognito](quotas.md).
+ It can be *mutable* or *immutable*. You can only write a value to an immutable attribute when you create a user. You can change the value of a mutable attribute if your app client has write permission to the attribute. See [Attribute permissions and scopes](#user-pool-settings-attribute-permissions-and-scopes) for more information.

**Note**  
In your code, and in rules settings for [Using role-based access control](role-based-access-control.md), custom attributes require the `custom:` prefix to distinguish them from standard attributes.

You can also add *developer attributes* when you create user pools, in the `SchemaAttributes` property of [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html). Developer attributes have a `dev:` prefix. You can only modify a user's developer attributes with AWS credentials. Developer attributes are a legacy feature that Amazon Cognito replaced with app client read-write permissions.

Use the following procedure to create a new custom attribute.

**To add a custom attribute using the console**

1. Go to [Amazon Cognito](https://console.aws.amazon.com/cognito/home) in the AWS Management Console. If the console prompts you, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Sign-up** menu, and in the **Custom attributes** section, choose **Add custom attributes**.

1. On the **Add custom attributes** page, provide the following details about the new attribute:
   + Enter a **Name**.
   + Select a** Type** of either **String** or **Number**.
   + Enter a **Min** string length or number value.
   + Enter a **Max** string length or number value.
   + Select **Mutable** if you want to give users permission to change the value of a custom attribute after they set the initial value.

1. Choose **Save changes**.

## Attribute permissions and scopes
<a name="user-pool-settings-attribute-permissions-and-scopes"></a>

For each app client, you can set read and write permissions for each user attribute. This way, you can control the access that any app has to read and modify each attribute that you store for your users. For example, you might have a custom attribute that indicates whether a user is a paying customer or not. Your apps might be able to see this attribute but not change it directly. Instead, you would update this attribute using an administrative tool or a background process. You can set permissions for user attributes from the Amazon Cognito console, the Amazon Cognito API, or the AWS CLI. By default, any new custom attributes aren't available until you set read and write permissions for them. By default, when you create a new app client, you grant your app read and write permissions for all standard and custom attributes. To limit your app to only the amount of information that it requires, assign specific permissions to attributes in your app client configuration.

As a best practice, specify attribute read and write permissions when you create an app client. Grant your app client access to the minimum set of user attributes that you need for the operation of your application.

**Note**  
[DescribeUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolClient.html) only returns values for `ReadAttributes` and `WriteAttributes` when you configure app client permissions other than the default.

**To update attribute permissions (AWS Management Console)**

1. Go to [Amazon Cognito](https://console.aws.amazon.com/cognito/home) in the AWS Management Console. If the console prompts you, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **App clients** menu and choose an app client from the list.

1. In the **Attribute permissions** tab, choose **Edit**.

1. On the **Edit attribute read and write permissions** page, configure your read and write permissions, and then choose **Save changes**.

Repeat these steps for each app client that uses the custom attribute.

For each app client, you can mark attributes as readable or writeable. This applies to both standard and custom attributes. Your app can retrieve the value of attributes that you mark as readable, and can set or modify the value of attributes that you mark as writeable. If your app tries to set a value for an attribute that it isn't authorized to write, Amazon Cognito returns `NotAuthorizedException`. [GetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html) requests include an access token with an app client claim; Amazon Cognito only returns values for attributes that your app client can read. Your user's ID token from an app only contains claims that correspond to the readable attributes. All app clients can write user pool required attributes. You can only set the value of an attribute in an Amazon Cognito user pools API request when you also provide a value for any required attributes that don't yet have a value.

Custom attributes have distinct features for read and write permissions. You can create them as mutable or immutable for the user pool, and you can set them as read or write attributes for any app client.

An immutable custom attribute can be updated once, during user creation. You can populate an immutable attribute with the following methods.
+ `SignUp`: A user signs up with an app client that has write access to an immutable custom attribute. They provide a value for that attribute.
+ Sign-in with a third-party IdP: A user signs in to an app client that has write access to an immutable custom attribute. Your user pool configuration for their IdP has a rule to map a provided claim to an immutable attribute. This is possible but not practical, because the user will only be able to sign in one time. On sign-in attempts after their first, Amazon Cognito rejects the attempt because of the mapping rule to a now-unwriteable attribute.
+ `AdminCreateUser`: You provide a value for an immutable attribute.

### Attribute permissions with scopes
<a name="user-pool-settings-attribute-scope-based-permissions"></a>

In user pools that you configure with an AWS SDK or CDK, the REST API, or the AWS CLI, you can configure app client read or write access with the OIDC scope `oidc:profile`. The `oidc:profile` grants read or write access to the following standard attributes:
+ `name`
+ `family_name`
+ `given_name`
+ `middle_name`
+ `nickname`
+ `preferred_username`
+ `profile`
+ `picture`
+ `website`
+ `gender`
+ `birthdate`
+ `zoneinfo`
+ `locale`

This list is the OIDC standard attributes minus `email`, `phone_number`, `sub`, and `address`, as defined in [section 2.4 of the OIDC specification](https://openid.net/specs/openid-connect-basic-1_0.html#Scopes). For information about the scopes that you can assign to your app clients, see [Scopes, M2M, and resource servers](cognito-user-pools-define-resource-servers.md).

To configure your app client to write to the attributes under the `oidc:profile` scope, set the value of [WriteAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-WriteAttributes) to `oidc:profile`, plus any other attributes that you want to permit your application to modify, in a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) API request. Similarly, to grant read access to these attributes, add `oidc:profile` to the value of [ReadAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-ReadAttributes).

You can change attribute permissions and scopes after you have created your user pool.

# Understanding user pool JSON web tokens (JWTs)
<a name="amazon-cognito-user-pools-using-tokens-with-identity-providers"></a>

Tokens are artifacts of authentication that your applications can use as proof of OIDC authentication and to request access to resources. The *claims* in tokens are information about your user. The ID token contains claims about their identity, like their username, family name, and email address. The access token contains claims like `scope` that the authenticated user can use to access third-party APIs, Amazon Cognito user self-service API operations, and the [userInfo endpoint](userinfo-endpoint.md). The access and ID tokens both include a `cognito:groups` claim that contains your user's group membership in your user pool. For more information about user pool groups, see [Adding groups to a user pool](cognito-user-pools-user-groups.md).

Amazon Cognito also has refresh tokens that you can use to get new tokens or revoke existing tokens. [Refresh a token](amazon-cognito-user-pools-using-the-refresh-token.md) to retrieve a new ID and access tokens. [Revoke a token](amazon-cognito-user-pools-using-the-refresh-token.md#amazon-cognito-identity-user-pools-revoking-all-tokens-for-user) to revoke user access that is allowed by refresh tokens.

Amazon Cognito issues tokens as [base64url](https://datatracker.ietf.org/doc/html/rfc4648#section-5)-encoded strings. You can decode any Amazon Cognito ID or access token from `base64url` to plaintext JSON. Amazon Cognito refresh tokens are encrypted, opaque to user pools users and administrators, and can only be read by your user pool.

**Authenticating with tokens**  
When a user signs into your app, Amazon Cognito verifies the login information. If the login is successful, Amazon Cognito creates a session and returns an ID token, an access token, and a refresh token for the authenticated user. You can use the tokens to grant your users access to downstream resources and APIs like Amazon API Gateway. Or you can exchange them for temporary AWS credentials to access other AWS services.

![\[Authentication overview\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-cup2.png)


**Storing tokens**  
Your app must be able to store tokens of varying sizes. Token size can change for reasons including, but not limited to, additional claims, changes in encoding algorithms, and changes in encryption algorithms. When you enable token revocation in your user pool, Amazon Cognito adds additional claims to JSON Web Tokens, increasing their size. The new claims `origin_jti` and `jti` are added to access and ID tokens. For more information about token revocation, see [Revoking tokens](https://docs.aws.amazon.com/cognito/latest/developerguide/token-revocation.html).

**Important**  
As a best practice, secure all tokens in transit and storage in the context of your application. Tokens can contain personally-identifying information about your users, and information about the security model that you use for your user pool.

**Customizing tokens**  
You can customize the access and ID tokens that Amazon Cognito passes to your app. In a [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md), you can add, modify, and suppress token claims. The pre token generation trigger is a Lambda function that Amazon Cognito sends a default set of claims to. The claims include OAuth 2.0 scopes, user pool group membership, user attributes, and others. The function can then take the opportunity to make changes at runtime and return updated token claims to Amazon Cognito.

Additional costs apply to access token customization with version 2 events. For more information, see [Amazon Cognito Pricing](https://aws.amazon.com/cognito/pricing/).

**Topics**
+ [

# Understanding the identity (ID) token
](amazon-cognito-user-pools-using-the-id-token.md)
+ [

# Understanding the access token
](amazon-cognito-user-pools-using-the-access-token.md)
+ [

# Refresh tokens
](amazon-cognito-user-pools-using-the-refresh-token.md)
+ [

# Ending user sessions with token revocation
](token-revocation.md)
+ [

# Verifying JSON web tokens
](amazon-cognito-user-pools-using-tokens-verifying-a-jwt.md)
+ [

# Managing user pool token expiration and caching
](amazon-cognito-user-pools-using-tokens-caching-tokens.md)

# Understanding the identity (ID) token
<a name="amazon-cognito-user-pools-using-the-id-token"></a>

The ID token is a [JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519) that contains claims about the identity of the authenticated user, such as `name`, `email`, and `phone_number`. You can use this identity information inside your application. The ID token can also be used to authenticate users to your resource servers or server applications. You can also use an ID token outside of the application with your web API operations. In those cases, you must verify the signature of the ID token before you can trust any claims inside the ID token. See [Verifying JSON web tokens](amazon-cognito-user-pools-using-tokens-verifying-a-jwt.md). 

You can set the ID token expiration to any value between 5 minutes and 1 day. You can set this value per app client.

**Important**  
When your user signs in with managed login, Amazon Cognito sets session cookies that are valid for 1 hour. If you use managed login for authentication in your application, and specify a minimum duration of less than 1 hour for your access and ID tokens, your users will still have a valid session until the cookie expires. If the user has tokens that expire during the one-hour session, the user can refresh their tokens without the need to reauthenticate.

## ID Token Header
<a name="user-pool-id-token-header"></a>

The header contains two pieces of information: the key ID (`kid`), and the algorithm (`alg`).

```
{
"kid" : "1234example=",
"alg" : "RS256"
}
```

**`kid`**  
The key ID. Its value indicates the key that was used to secure the JSON Web Signature (JWS) of the token. You can view your user pool signing key IDs at the `jwks_uri` endpoint.  
For more information about the `kid` parameter, see the [Key identifier (kid) header parameter](https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41#section-4.5).

**`alg`**  
The cryptographic algorithm that Amazon Cognito used to secure the access token. User pools use an RS256 cryptographic algorithm, which is an RSA signature with SHA-256.  
For more information about the `alg` parameter, see [Algorithm (alg) header parameter](https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41#section-4.4).

## ID token default payload
<a name="user-pool-id-token-payload"></a>

This is a example payload from an ID token. It contains claims about the authenticated user. For more information about OpenID Connect (OIDC) standard claims, see the list of [OIDC standard claims](http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). You can add claims of your own design with a [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md).

```
<header>.{
    "sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "cognito:groups": [
        "test-group-a",
        "test-group-b",
        "test-group-c"
    ],
    "email_verified": true,
    "cognito:preferred_role": "arn:aws:iam::111122223333:role/my-test-role",
    "iss": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_example",
    "cognito:username": "my-test-user",
    "middle_name": "Jane",
    "nonce": "abcdefg",
    "origin_jti": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "cognito:roles": [
        "arn:aws:iam::111122223333:role/my-test-role"
    ],
    "aud": "xxxxxxxxxxxxexample",
    "identities": [
        {
            "userId": "amzn1.account.EXAMPLE",
            "providerName": "LoginWithAmazon",
            "providerType": "LoginWithAmazon",
            "issuer": null,
            "primary": "true",
            "dateCreated": "1642699117273"
        }
    ],
    "event_id": "64f513be-32db-42b0-b78e-b02127b4f463",
    "token_use": "id",
    "auth_time": 1676312777,
    "exp": 1676316377,
    "iat": 1676312777,
    "jti": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "email": "my-test-user@example.com"
}
.<token signature>
```

**`sub`**  
A unique identifier ([UUID](cognito-terms.md#terms-uuid)), or subject, for the authenticated user. The username might not be unique in your user pool. The `sub` claim is the best way to identify a given user.

**`cognito:groups`**  
An array of the names of user pool groups that have your user as a member. Groups can be an identifier that you present to your app, or they can generate a request for a preferred IAM role from an identity pool.

**`cognito:preferred_role`**  
The ARN of the IAM role that you associated with your user's highest-priority user pool group. For more information about how your user pool selects this role claim, see [Assigning precedence values to groups](cognito-user-pools-user-groups.md#assigning-precedence-values-to-groups).

**`iss`**  
The identity provider that issued the token. The claim has the following format.  
`https://cognito-idp.<Region>.amazonaws.com/<your user pool ID>`

**`cognito:username`**  
The username of your user in your user pool.

**`nonce`**  
The `nonce` claim comes from a parameter of the same name that you can add to requests to your OAuth 2.0 `authorize` endpoint. When you add the parameter, the `nonce` claim is included in the ID token that Amazon Cognito issues, and you can use it to guard against replay attacks. If you do not provide a `nonce` value in your request, Amazon Cognito automatically generates and validates a nonce when you authenticate through a third-party identity provider, then adds it as a `nonce` claim to the ID token. The implementation of the `nonce` claim in Amazon Cognito is based on [OIDC standards](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation).

**`origin_jti`**  
A token-revocation identifier associated with your user's refresh token. Amazon Cognito references the `origin_jti` claim when it checks if you revoked your user's token with the [Revoke endpoint](revocation-endpoint.md) or the [RevokeToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RevokeToken.html) API operation. When you revoke a token, Amazon Cognito invalidates all access and ID tokens with the same `origin_jti` value.

**`cognito:roles`**  
An array of the names of the IAM roles associated with your user's groups. Every user pool group can have one IAM role associated with it. This array represents all IAM roles for your user's groups, regardless of precedence. For more information, see [Adding groups to a user pool](cognito-user-pools-user-groups.md).

**`aud`**  
The user pool app client that authenticated your user. Amazon Cognito renders the same value in the access token `client_id` claim.

**`identities`**  
The contents of the user's `identities` attribute. The attribute contains information about each third-party identity provider profile that you've linked to a user, either by federated sign-in or by [linking a federated user to a local profile](cognito-user-pools-identity-federation-consolidate-users.md). This information contains their provider name, their provider unique ID, and other metadata.

**`token_use`**  
The intended purpose of the token. In an ID token, its value is `id`.

**`auth_time`**  
The authentication time, in Unix time format, that your user completed authentication.

**`exp`**  
The expiration time, in Unix time format, that your user's token expires.

**`iat`**  
The issued-at time, in Unix time format, that Amazon Cognito issued your user's token.

**`jti`**  
The unique identifier of the JWT.

The ID token can contain OIDC standard claims that are defined in [OIDC standard claims](https://openid.net/specs/openid-connect-core-1_0.html#Claims). The ID token can also contain custom attributes that you define in your user pool. Amazon Cognito writes custom attribute values to the ID token as strings regardless of attribute type.

**Note**  
User pool custom attributes are always prefixed with `custom:`. 

## ID Token Signature
<a name="user-pool-id-token-signature"></a>

The signature of the ID token is calculated based on the header and payload of the JWT token. Before you accept the claims in any ID token that your app receives, verify the signature of the token. For more information, see Verifying a JSON Web Token. [Verifying JSON web tokens](amazon-cognito-user-pools-using-tokens-verifying-a-jwt.md).

# Understanding the access token
<a name="amazon-cognito-user-pools-using-the-access-token"></a>

The user pool access token contains claims about the authenticated user, a list of the user's groups, and a list of scopes. The purpose of the access token is to authorize API operations. Your user pool accepts access tokens to authorize user self-service operations. For example, you can use the access token to grant your user access to add, change, or delete user attributes.

With [OAuth 2.0 scopes](https://www.rfc-editor.org/rfc/rfc6749#section-3.3) in an access token, derived from the custom scopes that you add to your user pool, you can authorize your user to retrieve information from an API. For example, Amazon API Gateway supports authorization with Amazon Cognito access tokens. You can populate a REST API authorizer with information from your user pool, or use Amazon Cognito as a JSON Web Token (JWT) authorizer for an HTTP API. To generate an access token with custom scopes, you must request it through your user pool [public endpoints](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html).

With the Essentials or Plus [feature plan](cognito-sign-in-feature-plans.md), you can also implement a pre token generation Lambda trigger that adds scopes to your access tokens at runtime. For more information, see [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md).

A user's access token with the `openid` scope is permission to request more information about your user's attributes from the [userInfo endpoint](userinfo-endpoint.md). The amount of information from the `userInfo` endpoint derives from the additional scopes in the access token: for example, `profile` for all user data, `email` for their email address. 

A user's access token with the `aws.cognito.signin.user.admin` scope is permission to read and write user attributes, list authentication factors, configure multi-factor authentication (MFA) preferences, and manage remembered devices. The level of access to attributes that your access token grants to this scope matches the attribute read/write permissions you assign to your app client.

The access token is a [JSON Web Token (JWT)](https://www.rfc-editor.org/rfc/rfc7519). The header for the access token has the same structure as the ID token. Amazon Cognito signs access tokens with a different key from the key that signs ID tokens. The value of an access key ID (`kid`) claim won't match the value of the `kid` claim in an ID token from the same user session. In your app code, verify ID tokens and access tokens independently. Don't trust the claims in an access token until you verify the signature. For more information, see [Verifying JSON web tokens](amazon-cognito-user-pools-using-tokens-verifying-a-jwt.md). You can set the access token expiration to any value between 5 minutes and 1 day. You can set this value per app client.

**Important**  
For access and ID tokens, don't specify a minimum less than an hour if you use managed login. Managed login sets browsers cookies that are valid for one hour. If you configure an access token duration of less than an hour, this has no effect on the validity of the managed login cookie and users' ability to reauthenticate without additional credentials for one hour after initial sign-in.

## Access token header
<a name="user-pool-access-token-header"></a>

The header contains two pieces of information: the key ID (`kid`), and the algorithm (`alg`).

```
{
"kid" : "1234example="
"alg" : "RS256",
}
```

**`kid`**  
The key ID. Its value indicates the key that was used to secure the JSON Web Signature (JWS) of the token. You can view your user pool signing key IDs at the `jwks_uri` endpoint.  
For more information about the `kid` parameter, see the [Key identifier (kid) header parameter](https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41#section-4.5).

**`alg`**  
The cryptographic algorithm that Amazon Cognito used to secure the access token. User pools use an RS256 cryptographic algorithm, which is an RSA signature with SHA-256.  
For more information about the `alg` parameter, see [Algorithm (alg) header parameter](https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41#section-4.4).

## Access token default payload
<a name="user-pool-access-token-payload"></a>

This is a sample payload from an access token. For more information, see [JWT claims](https://tools.ietf.org/html/rfc7519#section-4). You can add claims of your own design with a [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md).

```
<header>.
{
   "sub":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
   "device_key": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
   "cognito:groups":[
      "testgroup"
   ],
   "iss":"https://cognito-idp.us-west-2.amazonaws.com/us-west-2_example",
   "version":2,
   "client_id":"xxxxxxxxxxxxexample",
   "aud": "https://api.example.com",
   "origin_jti":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
   "event_id":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
   "token_use":"access",
   "scope":"phone openid profile resourceserver.1/appclient2 email",
   "auth_time":1676313851,
   "exp":1676317451,
   "iat":1676313851,
   "jti":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
   "username":"my-test-user"
}
.<token signature>
```

**`sub`**  
A unique identifier ([UUID](cognito-terms.md#terms-uuid)), or subject, for the authenticated user. The username might not be unique in your user pool. The `sub` claim is the best way to identify a given user.

**`cognito:groups`**  
An array of the names of user pool groups that have your user as a member.

**`iss`**  
The identity provider that issued the token. The claim has the following format.  
`https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE`

**`client_id`**  
The user pool app client that authenticated your user. Amazon Cognito renders the same value in the ID token `aud` claim.

**aud**  
The URL of the API that the access token is intended to authorize for. Present only if your application requested a [resource binding](cognito-user-pools-define-resource-servers.md#cognito-user-pools-resource-binding) from your authorization server.

**`origin_jti`**  
A token-revocation identifier associated with your user's refresh token. Amazon Cognito references the `origin_jti` claim when it checks if you revoked your user's token with the [Revoke endpoint](revocation-endpoint.md) or the [RevokeToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RevokeToken.html) API operation. When you revoke a token, Amazon Cognito no longer validates access and ID tokens with the same `origin_jti` value.

**`token_use`**  
The intended purpose of the token. In an access token, its value is `access`.

**`scope`**  
A list of OAuth 2.0 scopes issued to the signed-in user. Scopes define the access that the token provides to external APIs, user self-service operations, and user data on the `userInfo` endpoint. A token from the [Token endpoint](token-endpoint.md) can contain any scopes that your app client supports. A token from Amazon Cognito API sign-in only contains the scope `aws.cognito.signin.user.admin`.

**`auth_time`**  
The authentication time, in Unix time format, that your user completed authentication.

**`exp`**  
The expiration time, in Unix time format, that your user's token expires.

**`iat`**  
The issued-at time, in Unix time format, that Amazon Cognito issued your user's token.

**`jti`**  
The unique identifier of the JWT.

**`username`**  
The user's username in the user pool.

**More resources**
+ [How to customize access tokens in Amazon Cognito user pools](https://aws.amazon.com/blogs/security/how-to-customize-access-tokens-in-amazon-cognito-user-pools/)

## Access token signature
<a name="user-pool-access-token-signature"></a>

The signature of the access token, signed with the key advertised at the `.well-known/jwks.json` endpoint, validates the integrity of the token header and payload. When you use access tokens to authorize access to external APIs, always configure your API authorizer to verify this signature against the key that signed it. For more information, see [Verifying JSON web tokens](amazon-cognito-user-pools-using-tokens-verifying-a-jwt.md).

# Refresh tokens
<a name="amazon-cognito-user-pools-using-the-refresh-token"></a>

You can use the refresh token to retrieve new ID and access tokens. By default, the refresh token expires 30 days after your application user signs into your user pool. When you create an application for your user pool, you can set the application's refresh token expiration to any value between 60 minutes and 10 years. 

## Getting new access and identity tokens with a refresh token
<a name="amazon-cognito-user-pools-using-the-refresh-token_initiate-token"></a>

Amazon Cognito issues refresh tokens in response to successful authentication with the managed login authorization-code flow and with API operations or SDK methods. The refresh token returns new ID and access tokens, and optionally a new refresh token. You can use refresh tokens in the following ways.

**GetTokensFromRefreshToken**  
The [GetTokensFromRefreshToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetTokensFromRefreshToken.html) API operation issues new ID and access tokens from a valid refresh token. You also get a new refresh token if you've enabled refresh token rotation.

**InitiateAuth and AdminitiateAuth**  
The [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) or [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations include the `REFRESH_TOKEN_AUTH` authentication flow. In this flow, you pass a refresh token and get new ID and access tokens. You can't authenticate with `REFRESH_TOKEN_AUTH` in app clients with [refresh token rotation](#using-the-refresh-token-rotation) enabled.

**OAuth token endpoint**  
The [token endpoint](token-endpoint.md) in user pools with a [domain](cognito-user-pools-assign-domain.md) has a `refresh_token` grant type that issues new ID, access, and optionally (with [refresh token rotation](#using-the-refresh-token-rotation)) refresh tokens from a valid refresh token.

## Refresh token rotation
<a name="using-the-refresh-token-rotation"></a>

You can optionally configure refresh token rotation in your app client. With refresh token rotation, your client can invalidate the original refresh token and issue a new refresh token with each token refresh. When this setting is enabled, each successful request in all forms of token refresh return a new ID, access, *and* refresh token. When this setting is disabled, token-refresh requests return new access and ID tokens only and the original refresh token remains valid. The new refresh token is valid for the remaining duration of the original refresh token. You can configure [app clients](user-pool-settings-client-apps.md) to rotate refresh tokens or to carry over the original refresh token. To allow for retries for a brief duration, you can also configure a grace period for the original refresh token of up to 60 seconds.

**Things to know about refresh token rotation**
+ After you enable refresh token rotation, new claims are added in JSON web tokens from your user pool. The `origin_jti` and `jti` claims are added to access and ID tokens. These claims increase the size of the JWTs.
+ Refresh token rotation isn't compatible with the authentication flow `REFRESH_TOKEN_AUTH`. To implement refresh token rotation, you must disable this authentication flow in your app client and design your application to submit token-refresh requests with the [GetTokensFromRefreshToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetTokensFromRefreshToken.html) API operation or the equivalent SDK method.
+ With refresh token rotation inactive, you can complete token-refresh requests with either `GetTokensFromRefreshToken` or `REFRESH_TOKEN_AUTH`.
+ When [device remembering](amazon-cognito-user-pools-device-tracking.md) is active in your user pool, you must provide the device key in `GetTokensFromRefreshToken` requests. If your user doesn't have a confirmed-device key that your application submits in the initial authentication request, Amazon Cognito issues a new one. To refresh tokens in this configuration, you must provide a device key, whether you specified one in `AuthParameters` or received a new one in the authentication response.
+ You can pass `ClientMetadata` to the pre token generation Lambda trigger in your `GetTokensFromRefreshToken` request. This data, which gets passed to the input event for your trigger, delivers additional context that you can use in the custom logic of your Lambda function.

As a security best practice, enable refresh token rotation on your app clients.

------
#### [ Enable refresh token rotation (console) ]

The following procedure turns refresh token rotation on or off for your app client. This procedure requires an existing app client. To learn more about creating an app client, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).

**To enable refresh token rotation**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Navigate to the **App clients** menu and select an existing app client.

1. Select **Edit** from the **App client information** section of the page.

1. Under **Advanced security configurations**, locate the **Enable refresh token rotation** option.

1. To enable rotation, select the checkbox. To disable rotation, deselect the checkbox.

1. Under **Refresh token rotation grace period**, enter a number of seconds, up to 60, that you want to set as the delay before the rotated-out refresh token is revoked.

------
#### [ Enable refresh token rotation (API) ]

Configure refresh token rotation in a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) API request. The following partial request body turns on refresh token rotation and sets the grace period to ten seconds.

```
"RefreshTokenRotation" : {
   "Feature" : "ENABLED,
   "RetryGracePeriodSeconds" : 10
}
```

------

## API and SDK token refresh
<a name="using-the-refresh-token-api"></a>

There are two ways to use the refresh token to get new ID and access tokens with the user pools API, depending on whether refresh token rotation is active. In app clients with refresh token rotation active, use the [GetTokensFromRefreshToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetTokensFromRefreshToken.html) API operation. In app clients without refresh token rotation, use the `REFRESH_TOKEN_AUTH` flow of the [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) or [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations.

**Note**  
Users can authenticate with user pools in [managed login](cognito-user-pools-managed-login.md) or in custom applications that you build with AWS SDKs and Amazon Cognito API operations. The `REFRESH_TOKEN_AUTH` flow and `GetTokensFromRefreshToken` can both complete token refresh for managed login users. Token refresh in custom applications doesn't affect managed login sessions. These sessions are set in a browser cookie and are valid for one hour. The `GetTokensFromRefreshToken` response issues new ID, access, and optionally refresh tokens, but doesn't renew the managed login session cookie.  
`REFRESH_TOKEN_AUTH` isn't available in app clients with refresh token rotation enabled.

------
#### [ GetTokensFromRefreshToken ]

[GetTokensFromRefreshToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetTokensFromRefreshToken.html) returns new ID, access and refresh tokens from a request that you authorize with a refresh token. The following is an example request body for `GetTokensFromRefreshToken`. You can submit client metadata to Lambda triggers in requests to this operation.

```
{
    "RefreshToken": "eyJjd123abcEXAMPLE",
    "ClientId": "1example23456789",
    "ClientSecret": "myappclientsecret123abc",
    "ClientMetadata": { 
      "MyMetadataKey" : "MyMetadataValue" 
   },
}
```

------
#### [ AdminInitiateAuth/InitiateAuth ]

To use the refresh token when refresh token rotation is inactive, use the [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) or [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API operations. Pass `REFRESH_TOKEN_AUTH` for the `AuthFlow` parameter. In the `AuthParameters` property of `AuthFlow`, pass your user's refresh token as the value of `"REFRESH_TOKEN"`. Amazon Cognito returns new ID and access tokens after your API request passes all challenges.

The following is an example request body for a token refresh with the `InitiateAuth` or `AdminInitiateAuth` API.

```
{
    "AuthFlow": "REFRESH_TOKEN_AUTH",
    "ClientId": "1example23456789",
    "UserPoolId": "us-west-2_EXAMPLE",
    "AuthParameters": {
        "REFRESH_TOKEN": "eyJjd123abcEXAMPLE",
        "SECRET_HASH": "kT5acwCVrbD6JexhW3EQwnRSe6fLuPTRkEQ50athqv8="
    }
}
```

------

## OAuth token refresh
<a name="using-the-refresh-token-oauth"></a>

You can also submit refresh tokens to the [Token endpoint](token-endpoint.md) in a user pool where you have configured a domain. In the request body, include a `grant_type` value of `refresh_token` and a `refresh_token` value of your user's refresh token.

Requests to the token endpoint are available in app clients with refresh token rotation active and those where it's inactive. When refresh token rotation is active, the token endpoint returns a new refresh token.

The following is an example request with a refresh token.

```
POST /oauth2/token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw
Content-Length: **

client_id=1example23456789&grant_type=refresh_token&refresh_token=eyJjd123abcEXAMPLE
```

## Revoking refresh tokens
<a name="amazon-cognito-identity-user-pools-revoking-all-tokens-for-user"></a>

You can revoke refresh tokens that belong to a user. For more information about revoking tokens, see [Ending user sessions with token revocation](token-revocation.md). 

**Note**  
Revoking the refresh token will revoke all ID and access tokens that Amazon Cognito issued from refresh requests with that token.

To sign users out from all current signed-in session, revoke all of their tokens with [GlobalSignOut](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GlobalSignOut.html) or [AdminUserGlobalSignOut](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUserGlobalSignOut.html) API requests. After the user is signed out, the following effects happen.
+ The user's refresh token can't get new tokens for the user.
+ The user's access token can't make token-authorized API requests.
+ The user must re-authenticate to get new tokens. Because managed login session cookies don't expire automatically, your user can re-authenticate with a session cookie, with no additional prompt for credentials. After you sign out your managed login users, redirect them to the [Logout endpoint](logout-endpoint.md), where Amazon Cognito clears their session cookie.

With refresh tokens, you can persist users' sessions in your app for a long time. Over time, your users might want to deauthorize some applications where they have stayed signed in with their refresh tokens. To sign your user out from a single session, revoke their refresh token. When your user wants to sign themself out from all authenticated sessions, generate a [GlobalSignOut](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GlobalSignOut.html) API request . Your app can present your user with a choice like **Sign out from all devices**. `GlobalSignOut` accepts a user's valid–unaltered, unexpired, not-revoked–access token. Because this API is token-authorized, one user can't use it to initiate sign-out for another user.

You can, however, generate an [AdminUserGlobalSignOut](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUserGlobalSignOut.html) API request that you authorize with your AWS credentials to sign out any user from all of their devices. The administrator application must call this API operation with AWS developer credentials and pass the user pool ID and the user's username as parameters. The `AdminUserGlobalSignOut` API can sign out any user in the user pool.

For more information about requests that you can authorize with either AWS credentials or a user's access token, see [List of API operations grouped by authorization model](authentication-flows-public-server-side.md#user-pool-apis-auth-unauth).

# Ending user sessions with token revocation
<a name="token-revocation"></a>

You can revoke refresh tokens and end user sessions with the following methods. When you revoke a refresh token, all access tokens that were previously issued by that refresh token become invalid. The other refresh tokens issued to the user are not affected.

**RevokeToken operation**  
[RevokeToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RevokeToken.html) revokes all access tokens for a given refresh token, including the initial access token from interactive sign-in. This operation doesn't affect any of the user's other refresh tokens or the ID- and access-token children of those other refresh tokens.

**Revocation endpoint**  
The [revoke endpoint](revocation-endpoint.md) revokes a given refresh token and all ID and access tokens that the refresh token generated. This endpoint also revokes the initial access token from interactive sign-in. Requests to this endpoint don't affect any of the user's other refresh tokens or the ID- and access-token children of those other refresh tokens.

**GlobalSignOut operation**  
[GlobalSignOut](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GlobalSignOut.html) is a self-service operation that a user authorizes with their access token. This operation revokes all of the requesting user's refresh, ID, and access tokens.

**AdminUserGlobalSignOut operation**  
[AdminUserGlobalSignOut](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUserGlobalSignOut.html) is a server-side operation that an administrator authorizes with IAM credentials. This operation revokes all of the target user's refresh, ID, and access tokens.

**Things to know about revoking tokens**
+ Your request to revoke a refresh token must include the client ID that was used to obtain the token.
+ User pool JWTs are self-contained with a signature and expiration time that was assigned when the token was created. Revoked tokens can't be used with any Amazon Cognito API calls that require a token. However, revoked tokens will still be valid if they are verified using any JWT library that verifies the signature and expiration of the token.
+ When you create a new user pool client, token revocation is enabled by default.
+ You can revoke refresh tokens only in app clients with token revocation enabled. 
+ After you enable token revocation, new claims are added in the Amazon Cognito JSON Web Tokens. The `origin_jti` and `jti` claims are added to access and ID tokens. These claims increase the size of the application client access and ID tokens.
+ When you disable token revocation in an app client where it was previously enabled, revoked tokens don't become active again.
+ When you [disable a user account](how-to-manage-user-accounts.md#manage-user-accounts-enable-disable) (which revokes refresh and access tokens), the revoked tokens don't become active if you enable the user account again.
+ When you create a new user pool client using the AWS Management Console, the AWS CLI, or the AWS API, token revocation is enabled by default.

## Enable token revocation
<a name="enable-token-revocation"></a>

Before you can revoke a token for an existing user pool client, you must enable token revocation. You can enable token revocation for existing user pool clients using the AWS CLI or the AWS API. To do this, call the `aws cognito-idp describe-user-pool-client` CLI command or the `DescribeUserPoolClient` API operation to retrieve the current settings from your app client. Then call the `aws cognito-idp update-user-pool-client` CLI command or the `UpdateUserPoolClient` API operation. Include the current settings from your app client and set the `EnableTokenRevocation` parameter to `true`.

To create or modify an app client with token revocation enabled with the Amazon Cognito API or with an AWS SDK, include the following parameter in your [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) API request.

```
"EnableTokenRevocation": true
```

To configure token revocation in the Amazon Cognito console, select an app client from the **App clients** menu in your user pool. Select the **Edit** button in **App client information** and enable or disable token revocation under **Advanced configuration**.

## Revoke a token
<a name="revoke-tokens-api"></a>

You can revoke a refresh token using a [RevokeToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RevokeToken.html) API request, for example with the `[aws cognito-idp revoke-token](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/revoke-token.html)` CLI command. You can also revoke tokens using the [Revoke endpoint](revocation-endpoint.md). This endpoint is available after you add a domain to your user pool. You can use the revocation endpoint on either an Amazon Cognito hosted domain or your own custom domain.

The following is the body of an example `RevokeToken` API request.

```
{
   "ClientId": "1example23456789",
   "ClientSecret": "abcdef123456789ghijklexample",
   "Token": "eyJjdHkiOiJKV1QiEXAMPLE"
}
```

The following is an example cURL request to the `/oauth2/revoke` endpoint of a user pool with a custom domain.

```
curl --location 'auth.mydomain.com/oauth2/revoke' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic Base64Encode(client_id:client_secret)' \
--data-urlencode 'token=abcdef123456789ghijklexample' \
--data-urlencode 'client_id=1example23456789'
```

The `RevokeToken` operation and the `/oauth2/revoke` endpoint require no additional authorization unless your app client has a client secret.

# Verifying JSON web tokens
<a name="amazon-cognito-user-pools-using-tokens-verifying-a-jwt"></a>

JSON web tokens (JWTs) can be decoded, read, and modified easily. A modified access token creates a risk of privilege escalation. A modified ID token creates a risk of impersonation. Your application trusts your user pool as a token issuer, but what if a user intercepts the token in transit? You must ensure that your application is receiving the same token that Amazon Cognito issued.

Amazon Cognito issues tokens that use some of the integrity and confidentiality features of the OpenID Connect (OIDC) specification. User pool tokens indicate validity with objects like the expiration time, issuer, and digital signature. The signature, the third and final segment of the `.`-delimited JWT, is the key component of token validation. A malicious user can modify a token, but if your application retrieves the public key and compares the signature, it won't match. Any application that processes JWTs from OIDC authentication must perform this verification operation with each sign-in.

On this page, we make some general and specific recommendations for verification of JWTs. Application development spans a variety of programming languages and platforms. Because Amazon Cognito implements OIDC sufficiently close to the public specification, any reputable JWT library in your developer environment of choice can handle your verification requirements.

These steps describe verifying a user pool JSON Web Token (JWT).

**Topics**
+ [

## Prerequisites
](#amazon-cognito-user-pools-using-tokens-prerequisites)
+ [

## Validate tokens with aws-jwt-verify
](#amazon-cognito-user-pools-using-tokens-aws-jwt-verify)
+ [

## Understanding and inspecting tokens
](#amazon-cognito-user-pools-using-tokens-manually-inspect)

## Prerequisites
<a name="amazon-cognito-user-pools-using-tokens-prerequisites"></a>

Your library, SDK, or software framework might already handle the tasks in this section. AWS SDKs provide tools for Amazon Cognito user pool token handling and management in your app. AWS Amplify includes functions to retrieve and refresh Amazon Cognito tokens.

For more information, see the following pages.
+ [Integrating Amazon Cognito authentication and authorization with web and mobile apps](cognito-integrate-apps.md)
+ [Code examples for Amazon Cognito Identity Provider using AWS SDKs](https://docs.aws.amazon.com/cognito/latest/developerguide/service_code_examples.html)
+ [Advanced workflows](https://docs.amplify.aws/lib/auth/advanced/q/platform/js/#retrieve-jwt-tokens) in the *Amplify Dev Center*

Many libraries are available for decoding and verifying a JSON Web Token (JWT). If you want to manually process tokens for server-side API processing, or if you are using other programming languages, these libraries can help. See the [OpenID foundation list of libraries for working with JWT tokens](http://openid.net/developers/jwt/).

## Validate tokens with aws-jwt-verify
<a name="amazon-cognito-user-pools-using-tokens-aws-jwt-verify"></a>

In a Node.js app, AWS recommends the [aws-jwt-verify library](https://github.com/awslabs/aws-jwt-verify) to validate the parameters in the token that your user passes to your app. With `aws-jwt-verify`, you can populate a `CognitoJwtVerifier` with the claim values that you want to verify for one or more user pools. Some of the values that it can check include the following.
+ That access or ID tokens aren't malformed or expired, and have a valid signature.
+ That access tokens came from the [correct user pools and app clients](https://github.com/awslabs/aws-jwt-verify#verifying-jwts-from-amazon-cognito).
+ That access token claims contain the [correct OAuth 2.0 scopes](https://github.com/awslabs/aws-jwt-verify#checking-scope).
+ That the keys that signed your access and ID tokens [match a signing key `kid` from the *JWKS URI* of your user pools](https://github.com/awslabs/aws-jwt-verify#the-jwks-cache).

  The JWKS URI contains public information about the private key that signed your user's token. You can find the JWKS URI for your user pool at `https://cognito-idp.<Region>.amazonaws.com/<userPoolId>/.well-known/jwks.json`.

For more information and example code that you can use in a Node.js app or a AWS Lambda authorizer, see [https://github.com/awslabs/aws-jwt-verify](https://github.com/awslabs/aws-jwt-verify) on GitHub.

## Understanding and inspecting tokens
<a name="amazon-cognito-user-pools-using-tokens-manually-inspect"></a>

Before you integrate token inspection with your app, consider how Amazon Cognito assembles JWTs. Retrieve example tokens from your user pool. Decode and examine them in detail to understand their characteristics, and determine what you want to verify and when. For example, you might want to examine group membership in one scenario, and scopes in another.

The following sections describe a process to manually inspect Amazon Cognito JWTs as you prepare your app.

### Confirm the structure of the JWT
<a name="amazon-cognito-user-pools-using-tokens-step-1"></a>

A JSON Web Token (JWT) includes three sections with a `.` (dot) delimiter between them.

**Header**  
The key ID, `kid`, and the RSA algorithm, `alg`, that Amazon Cognito used to sign the token. Amazon Cognito signs tokens with an `alg` of `RS256`. The `kid` is a truncated reference to a 2048-bit RSA private signing key held by your user pool.

**Payload**  
Token claims. In an ID token, the claims include user attributes and information about the user pool, `iss`, and app client, `aud`. In an access token, the payload includes scopes, group membership, your user pool as `iss`, and your app client as `client_id`.

**Signature**  
The signature isn't decodable base64url like the header and payload. It's an RSA256 identifier derived from a signing key and parameters that you can observe at your JWKS URI.

The header and payload are base64url-encoded JSON. You can identify them by the opening characters `eyJ` that decode to the starting character `{`. If your user presents a base64url-encoded JWT to your app and it's not in the format `[JSON Header].[JSON Payload].[Signature]`, it's not a valid Amazon Cognito token and you can discard it.

The following example application verifies user pool tokens with `aws-jwt-verify`.

```
// cognito-verify.js
// Usage example: node cognito-verify.js eyJra789ghiEXAMPLE

const { CognitoJwtVerifier } = require('aws-jwt-verify');

// Replace with your Amazon Cognito user pool ID
const userPoolId = 'us-west-2_EXAMPLE';

async function verifyJWT(token) {
  try {
    const verifier = CognitoJwtVerifier.create({
      userPoolId,
      tokenUse: 'access', // or 'id' for ID tokens
      clientId: '1example23456789', // Optional, only if you need to verify the token audience
    });

    const payload = await verifier.verify(token);
    console.log('Decoded JWT:', payload);
  } catch (err) {
    console.error('Error verifying JWT:', err);
  }
}

// Example usage
if (process.argv.length < 3) {
  console.error('Please provide a JWT token as an argument.');
  process.exit(1);
}

const MyToken = process.argv[2];
verifyJWT(MyToken);
```

### Validate the JWT
<a name="amazon-cognito-user-pools-using-tokens-step-2"></a>

The JWT signature is a hashed combination of the header and the payload. Amazon Cognito generates two pairs of RSA cryptographic keys for each user pool. One private key signs access tokens, and the other signs ID tokens.

**To verify the signature of a JWT token**

1. Decode the ID token.

   The OpenID Foundation also [maintains a list of libraries for working with JWT tokens](http://openid.net/developers/jwt/).

   You can also use AWS Lambda to decode user pool JWTs. For more information, see [Decode and verify Amazon Cognito JWT tokens using AWS Lambda](https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt).

1. Compare the local key ID (`kid`) to the public `kid`.

   1. Download and store the corresponding public JSON Web Key (JWK) for your user pool. It is available as part of a JSON Web Key Set (JWKS). You can locate it by constructing the following `jwks_uri` URI for your environment:

      ```
      https://cognito-idp.<Region>.amazonaws.com/<userPoolId>/.well-known/jwks.json
      ```

      For more information on JWK and JWK sets, see [JSON Web Key (JWK)](https://tools.ietf.org/html/rfc7517).
**Note**  
Amazon Cognito might rotate signing keys in your user pool. As a best practice, cache public keys in your app, using the `kid` as a cache key, and refresh the cache periodically. Compare the `kid` in the tokens that your app receives to your cache.  
If you receive a token with the correct issuer but a different `kid`, Amazon Cognito might have rotated the signing key. Refresh the cache from your user pool `jwks_uri` endpoint.

      This is a sample `jwks.json` file:

      ```
      {
      	"keys": [{
      		"kid": "1234example=",
      		"alg": "RS256",
      		"kty": "RSA",
      		"e": "AQAB",
      		"n": "1234567890",
      		"use": "sig"
      	}, {
      		"kid": "5678example=",
      		"alg": "RS256",
      		"kty": "RSA",
      		"e": "AQAB",
      		"n": "987654321",
      		"use": "sig"
      	}]
      }
      ```  
**Key ID (`kid`)**  
The `kid` is a hint that indicates which key was used to secure the JSON Web Signature (JWS) of the token.  
**Algorithm (`alg`)**  
The `alg` header parameter represents the cryptographic algorithm that is used to secure the ID token. User pools use an RS256 cryptographic algorithm, which is an RSA signature with SHA-256. For more information on RSA, see [RSA cryptography](https://tools.ietf.org/html/rfc3447).   
**Key type (`kty`)**  
The `kty` parameter identifies the cryptographic algorithm family that is used with the key, such as "RSA" in this example.  
**RSA exponent (`e`)**  
The `e` parameter contains the exponent value for the RSA public key. It is represented as a Base64urlUInt-encoded value.  
**RSA modulus (`n`)**  
The `n` parameter contains the modulus value for the RSA public key. It is represented as a Base64urlUInt-encoded value.  
**Use (`use`)**  
The `use` parameter describes the intended use of the public key. For this example, the `use` value `sig` represents signature.

   1. Search the public JSON Web Key for a `kid` that matches the `kid` of your JWT.

### Verify the claims
<a name="amazon-cognito-user-pools-using-tokens-step-3"></a>

**To verify JWT claims**

1. By one of the following methods, verify that the token hasn't expired.

   1. Decode the token and compare the `exp` claim to the current time.

   1. If your access token includes an `aws.cognito.signin.user.admin` claim, send a request to an API like [GetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html). API requests that you [authorize with an access token](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pools-API-operations.html#user-pool-apis-auth-unauth) return an error if your token has expired.

   1. Present your access token in a request to the [userInfo endpoint](userinfo-endpoint.md). Your request returns an error if your token has expired.

1. The `aud` claim in an ID token and the `client_id` claim in an access token should match the app client ID that was created in the Amazon Cognito user pool.

1. The issuer (`iss`) claim should match your user pool. For example, a user pool created in the `us-east-1` Region will have the following `iss` value:

   `https://cognito-idp.us-east-1.amazonaws.com/<userpoolID>`.

1. Check the `token_use` claim. 
   + If you are only accepting the access token in your web API operations, its value must be `access`.
   + If you are only using the ID token, its value must be `id`.
   + If you are using both ID and access tokens, the `token_use` claim must be either `id` or `access`.

You can now trust the claims inside the token.

# Managing user pool token expiration and caching
<a name="amazon-cognito-user-pools-using-tokens-caching-tokens"></a>

Your app must successfully complete one of the following requests each time you want to get a new JSON Web Token (JWT).
+ Request a client credentials or authorization code [grant](https://www.rfc-editor.org/rfc/rfc6749#section-1.3) from the [Token endpoint](token-endpoint.md).
+ Request an implicit grant from your managed login pages.
+ Authenticate a local user in an Amazon Cognito API request like [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html).

You can configure your user pool to set tokens to expire in minutes, hours, or days. To ensure the performance and availability of your app, use Amazon Cognito tokens for about 75% of the token lifetime, and only then retrieve new tokens. A cache solution that you build for your app keeps tokens available, and prevents the rejection of requests by Amazon Cognito when your request rate is too high. A client-side app must store tokens in a memory cache. A server-side app can add an encrypted cache mechanism to store tokens.

When your user pool generates a high volume of user or machine-to-machine activity, you might encounter the limits that Amazon Cognito sets on the number of requests for tokens that you can make. To reduce the number of requests you make to Amazon Cognito endpoints, you can either securely store and reuse authentication data, or implement exponential backoff and retries.

Authentication data comes from two classes of endpoints. Amazon Cognito [OAuth 2.0 endpoints](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-userpools-server-contract-reference.html) include the token endpoint, which services client credentials and managed login authorization code requests. [Service endpoints](https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html#cognito_identity_your_user_pools_region) answer user pools API requests like `InitiateAuth` and `RespondToAuthChallenge`. Each type of request has its own limit. For more information about limits, see [Quotas in Amazon Cognito](quotas.md).

## Caching machine-to-machine access tokens with Amazon API Gateway
<a name="amazon-cognito-user-pools-using-tokens-caching-tokens-API-gateway"></a>

With API Gateway token caching, your app can scale in response to events larger than the default request rate quota of Amazon Cognito OAuth endpoints.

![\[A diagram of an API Gateway maintaining a cache of access tokens for M2M. The API proxy processes the token request and returns a cached token if one is already valid.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/user-pools-m2m-caching.png)


You can cache the access tokens so that your app only requests a new access token if a cached token is expired. Otherwise, your caching endpoint returns a token from the cache. This prevents an additional call to an Amazon Cognito API endpoint. When you use Amazon API Gateway as a proxy to the [Token endpoint](token-endpoint.md), your API responds to the majority of requests that would otherwise contribute to your request quota, avoiding unsuccessful requests as a result of rate limiting.

The following API Gateway-based solution offers a low-latency, low-code/no-code implementation of token caching. API Gateway APIs are encrypted in transit, and optionally at rest. An API Gateway cache is ideal for the OAuth 2.0 [client credentials grant](https://datatracker.ietf.org/doc/html/rfc6749#section-4.4), a frequently high-volume grant type that produces access tokens to authorize machine-to-machine and microservice sessions. In an event like a traffic surge that causes your microservices to horizontally scale, you can end up with many systems using the same client credentials at a volume that exceeds the AWS request-rate limit of your user pool or app client. To preserve app availability and low latency, a caching solution is best practice in such scenarios.

In this solution, you define a cache in your API to store a separate access token for each combination of OAuth scopes and app client that you want to request in your app. When your app makes a request that matches the cache key, your API responds with an access token that Amazon Cognito issued to the first request that matched the cache key. When your cache key duration expires, your API forwards the request to your token endpoint and caches a new access token.

**Note**  
Your cache key duration must be shorter than the access token duration of your app client.

The cache key is a combination of the OAuth scopes that you request in the `scope` parameter in the request body and the `Authorization` header in the request. The `Authorization` header contains your app client ID and client secret. You don't need to implement additional logic in your app to implement this solution. You must only update your configuration to change the path to your user pool token endpoint.

You can also implement token caching with [ElastiCache (Redis OSS)](https://docs.aws.amazon.com/elasticache/index.html). For fine-grained control with AWS Identity and Access Management (IAM) policies, consider an [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/authentication-and-access-control.html#authentication) cache.

**Note**  
Caching in API Gateway is subject to additional cost. [See pricing for more details.](https://aws.amazon.com/api-gateway/pricing)<a name="amazon-cognito-user-pools-using-tokens-caching-tokens-API-gateway-how-to"></a>

**To set up a caching proxy with API Gateway**

1. Open the [API Gateway console](https://console.aws.amazon.com/apigateway/main/apis) and create a REST API.

1. In **Resources**, create a POST method.

   1. Choose the HTTP **Integration type**.

   1. Select **Use HTTP proxy integration**.

   1. Enter an **Endpoint URL** of `https://<your user pool domain>/oauth2/token`.

1. In **Resources**, configure the cache key.

   1. Edit the **Method request** of your POST method.
**Note**  
This method request validation is for use with `client_secret_basic` authorization in token requests, where the client secret is encoded in the `Authorization` request header. For validation of the JSON request body in `client_secret_post` authorization, create instead a [data model](https://docs.aws.amazon.com/apigateway/latest/developerguide/models-mappings-models.html) that requires that [client\$1secret](token-endpoint.md#post-token-request-parameters-in-body) be present. In this model, your **Request validator** should **Validate body, query string parameters, and headers**.

   1. Configure the method **Request validator** to **Validate query string parameters and headers**. For more information about request validation, see [Request validation](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html) in the *Amazon API Gateway Developer Guide*.

   1. Set your `scope` parameter and `Authorization` header as your caching key.

      1. Add a query string to **URL query string parameters**. Enter a query string **Name** of `scope` and select **Required** and **Caching**.

      1. Add a header to **HTTP request headers**. Enter a request header **Name** of `Authorization` and select **Required** and **Caching**.

1. In **Stages**, configure caching.

   1. Choose the stage that you want to modify and choose **Edit** from **Stage Details**.

   1. Under **Additional settings**, **Cache settings**, turn on the **Provision API cache** option.

   1. Choose a **Cache capacity**. Higher cache capacity improves performance but comes at additional cost.

   1. Clear the **Require authorization** check box. Select **Continue**.

   1. API Gateway only applies cache policies to GET methods from the stage level. You must apply a cache policy override to your POST method.

      Expand the stage you configured and select the `POST` method. To create cache settings for the method, choose **Create override**.

   1. Activate the **Enable method cache** option.

   1. Enter a ****Cache time-to-live (TTL)**** of 3600 seconds. Choose **Save**.

1. In **Stages**, note the **Invoke URL**.

1. Update your app to POST token requests to the **Invoke URL** of your API instead of the `/oauth2/token` endpoint of your user pool.

# Accessing resources after successful sign-in
<a name="accessing-resources"></a>

Your app users can either sign in directly through a user pool, or they can federate through a third-party identity provider (IdP). The user pool manages the overhead of handling the tokens that are returned from social sign-in through Facebook, Google, Amazon, and Apple, and from OpenID Connect (OIDC) and SAML IdPs. For more information, see [Understanding user pool JSON web tokens (JWTs)](amazon-cognito-user-pools-using-tokens-with-identity-providers.md). 

After a successful authentication, your app will receive user pool tokens from Amazon Cognito. You can use user pool tokens to:
+ Retrieve AWS credentials that authorize requests for application resources in AWS services like Amazon DynamoDB and Amazon S3.
+ Provide temporary, revocable proof of authentication.
+ Populate identity data to a user profile in your app.
+ Authorize changes to the signed-in user's profile in the user pool directory.
+ Authorize requests for user information with an access token.
+ Authorize requests to data that is behind access-protected external APIs with access tokens.
+ Authorize access to application assets that are stored on the client or server with Amazon Verified Permissions.

For more information, see [An example authentication session](authentication.md#amazon-cognito-user-pools-authentication-flow) and [Understanding user pool JSON web tokens (JWTs)](amazon-cognito-user-pools-using-tokens-with-identity-providers.md).

![\[Authentication overview.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-cup.png)


**Topics**
+ [

# Authorizing access to client or server resources with Amazon Verified Permissions
](scenario-backend.md)
+ [

# Accessing resources with API Gateway after sign-in
](user-pool-accessing-resources-api-gateway-and-lambda.md)
+ [

# Accessing AWS services using an identity pool after sign-in
](amazon-cognito-integrating-user-pools-with-identity-pools.md)

# Authorizing access to client or server resources with Amazon Verified Permissions
<a name="scenario-backend"></a>

Your app can pass the tokens from a signed-in user to [Amazon Verified Permissions](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/what-is-avp.html). Verified Permissions is a scalable, fine-grained permissions management and authorization service for applications that you've built. An Amazon Cognito user pool can be an identity source to a Verified Permissions policy store. Verified Permissions makes authorization decisions for requested actions and resources, like `GetPhoto` for `premium_badge.png`, from the principal and their attributes in user pool tokens.

The following diagram shows how your application can pass a user's token to Verified Permissions in an authorization request.

![\[A flow diagram of an application that authenticates with an Amazon Cognito user pool and authorizes access to local resources with Amazon Verified Permissions.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/access-services-local-resources.png)


**Get started with Amazon Verified Permissions**  
After you integrate your user pool with Verified Permissions, you gain a central source of granular authorization for all of your Amazon Cognito apps. This removes the need for fine-grained security logic that you would otherwise have to code and replicate between all of your apps. For more information about authorization with Verified Permissions, see [Authorization with Amazon Verified Permissions](amazon-cognito-authorization-with-avp.md).

Verified Permissions authorization requests require AWS credentials. You can implement some of the following techniques to safely apply credentials to authorization requests.
+ Operate a web application that can store secrets in the server backend.
+ Acquire authenticated identity pool credentials.
+ Proxy user requests through an access-token-authorized API, and append AWS credentials to the request.

# Accessing resources with API Gateway after sign-in
<a name="user-pool-accessing-resources-api-gateway-and-lambda"></a>

A common use of Amazon Cognito user pools tokens is to authorize requests to an [API Gateway REST API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html). The OAuth 2.0 scopes in access tokens can authorize a method and path, like `HTTP GET` for `/app_assets`. ID tokens can serve as generic authentication to an API and can pass user attributes to the backend service. API Gateway has additional custom authorization options like [JWT authorizers for HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html) and [Lambda authorizers](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html) that can apply more fine-grained logic.

The following diagram illustrates an application that is gaining access to a REST API with the OAuth 2.0 scopes in an access token.

![\[A flow diagram of an application that authenticates with an Amazon Cognito user pool and authorizes access to API resources with Amazon API Gateway.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/access-services-api-gateway.png)


Your app must collect the tokens from authenticated sessions and add them as bearer tokens to an `Authorization` header in the request. Configure the authorizer that you configured for the API, path, and method to evaluate token contents. API Gateway returns data only if the request matches the conditions that you set up for your authorizer. 

Some potential ways that API Gateway API can approve access from an application are:
+ The access token is valid, isn't expired, and contains the correct OAuth 2.0 scope. The [Amazon Cognito user pools authorizer for a REST API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) is a common implementation with a low barrier to entry. You can also evaluate the body, query string parameters, and headers of a request to this type of authorizer.
+ The ID token is valid and isn't expired. When you pass an ID token to an Amazon Cognito authorizer, you can perform additional validation of the ID token contents on your application server.
+ A group, claim, attribute, or role in an access or ID token meets the requirements that you define in a Lambda function. A [Lambda authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html) parses the token in the request header and evaluates it for an authorization decision. You can construct custom logic in your function or make an API request to [Amazon Verified Permissions](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/what-is-avp.html).

You can also authorize requests to an [AWS AppSync GraphQL API](https://docs.aws.amazon.com/appsync/latest/devguide/security-authz.html#amazon-cognito-user-pools-authorization) with tokens from a user pool.

# Accessing AWS services using an identity pool after sign-in
<a name="amazon-cognito-integrating-user-pools-with-identity-pools"></a>

After your users sign in with a user pool, they can access AWS services with temporary API credentials that are issued from an identity pool.

Your web or mobile app receives tokens from a user pool. When you configure your user pool as an identity provider to your identity pool, the identity pool exchanges tokens for temporary AWS credentials. These credentials can be scoped to IAM roles and their policies that give users access to a limited set of AWS resources. For more information, see [Identity pools authentication flow](authentication-flow.md).

The following diagram shows how an application signs in with a user pool, retrieves identity pool credentials, and requests an asset from an AWS service.

![\[A flow diagram of an application that authenticates with an Amazon Cognito user pool and authorizes access to AWS resources with an identity pool.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/access-services-identity-pool.png)


You can use identity pool credentials to:
+ Make fine-grained authorization requests to Amazon Verified Permissions with your user's own credentials.
+ Connect to an Amazon API Gateway REST API or an AWS AppSync GraphQL API that authorizes connections with IAM.
+ Connect to a database backend like Amazon DynamoDB or Amazon RDS that authorizes connections with IAM.
+ Retrieve application assets from an Amazon S3 bucket.
+ Initiate a session with an Amazon WorkSpaces virtual desktop.

Identity pools don't operate exclusively within an authenticated session with a user pool. They also accept authentication directly from third-party identity providers and can generate credentials for unauthenticated guest users.

For more information about using identity pools together with user pool groups to control access to your AWS resources, see [Adding groups to a user pool](cognito-user-pools-user-groups.md) and [Using role-based access control](role-based-access-control.md). Also, for more information about identity pools and AWS Identity and Access Management, see [Identity pools authentication flow](authentication-flow.md).

## Setting up a user pool with the AWS Management Console
<a name="amazon-cognito-integrating-user-pools-with-identity-pools-setting-up"></a>

Create an Amazon Cognito user pool and make a note of the **User Pool ID** and **App Client ID** for each of your client apps. For more information about creating user pools, see [Getting started with user pools](getting-started-user-pools.md).

## Setting up an identity pool with the AWS Management Console
<a name="amazon-cognito-integrating-user-pools-with-identity-pools-configuring"></a>

The following procedure describes how to use the AWS Management Console to integrate an identity pool with one or more user pools and client apps.

**To add an Amazon Cognito user pools identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Amazon Cognito user pool**.

1. Enter a **User pool ID** and an **App client ID**.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can give users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**. With an Amazon Cognito user pool IdP, you can also **Choose role with preferred\$1role claim in tokens**. For more information about the `cognito:preferred_role` claim, see [Assigning precedence values to groups](cognito-user-pools-user-groups.md#assigning-precedence-values-to-groups).

      1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to use to compare the claim to the rule, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

      1. If you chose **Choose role with preferred\$1role claim in tokens**, Amazon Cognito issues credentials for the role in your user's `cognito:preferred_role` claim. If no preferred role claim is present, Amazon Cognito issues credentials based on your **Role resolution**.

   1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.
   + To apply no principal tags, choose **Inactive**.
   + To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.
   + To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

## Integrating a user pool with an identity pool
<a name="amazon-cognito-integrating-user-pools-with-identity-pools-using"></a>

After your app user is authenticated, add that user's identity token to the logins map in the credentials provider. The provider name will depend on your Amazon Cognito user pool ID. It will have the following structure:

```
cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>
```

You can derive the value for *<region>* from the **User Pool ID**. For example, if the user pool ID is `us-east-1_EXAMPLE1`, then the *<region>* is `us-east-1`. If the user pool ID is `us-west-2_EXAMPLE2`, then the *<region>* is `us-west-2`.

------
#### [ JavaScript ]

```
var cognitoUser = userPool.getCurrentUser();

if (cognitoUser != null) {
	cognitoUser.getSession(function(err, result) {
		if (result) {
			console.log('You are now logged in.');

			// Add the User's Id Token to the Cognito credentials login map.
			AWS.config.credentials = new AWS.CognitoIdentityCredentials({
				IdentityPoolId: 'YOUR_IDENTITY_POOL_ID',
				Logins: {
					'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>': result.getIdToken().getJwtToken()
				}
			});
		}
	});
}
```

------
#### [ Android ]

```
cognitoUser.getSessionInBackground(new AuthenticationHandler() {
	@Override
	public void onSuccess(CognitoUserSession session) {
		String idToken = session.getIdToken().getJWTToken();

		Map<String, String> logins = new HashMap<String, String>();
		logins.put("cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>", session.getIdToken().getJWTToken());
		credentialsProvider.setLogins(logins);
	}

});
```

------
#### [ iOS - objective-C ]

```
AWSServiceConfiguration *serviceConfiguration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:nil];
AWSCognitoIdentityUserPoolConfiguration *userPoolConfiguration = [[AWSCognitoIdentityUserPoolConfiguration alloc] initWithClientId:@"YOUR_CLIENT_ID"  clientSecret:@"YOUR_CLIENT_SECRET" poolId:@"YOUR_USER_POOL_ID"];
[AWSCognitoIdentityUserPool registerCognitoIdentityUserPoolWithConfiguration:serviceConfiguration userPoolConfiguration:userPoolConfiguration forKey:@"UserPool"];
AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:@"UserPool"];
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1 identityPoolId:@"YOUR_IDENTITY_POOL_ID" identityProviderManager:pool];
```

------
#### [ iOS - swift ]

```
let serviceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)
let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", poolId: "YOUR_USER_POOL_ID")
AWSCognitoIdentityUserPool.registerCognitoIdentityUserPoolWithConfiguration(serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: "UserPool")
let pool = AWSCognitoIdentityUserPool(forKey: "UserPool")
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YOUR_IDENTITY_POOL_ID", identityProviderManager:pool)
```

------

# Scopes, M2M, and resource servers
<a name="cognito-user-pools-define-resource-servers"></a>

After you configure a domain for your user pool, Amazon Cognito automatically provisions an OAuth 2.0 authorization server and a hosted web UI with sign-up and sign-in pages that your app can present to your users. For more information see [User pool managed login](cognito-user-pools-managed-login.md). You can choose the scopes that you want the authorization server to add to access tokens. Scopes authorize access to resource servers and user data.

A *resource server* is an OAuth 2.0 API server. To secure access-protected resources, it validates that access tokens from your user pool contain the scopes that authorize the requested method and path in the API that it protects. It verifies the issuer based on the token signature, validity based on token expiration time, and access level based on the scopes in token claims. User pool scopes are in the access token `scope` claim. For more information about the claims in Amazon Cognito access tokens, see [Understanding the access token](amazon-cognito-user-pools-using-the-access-token.md).

With Amazon Cognito, the scopes in access tokens can authorize access to external APIs or to user attributes. You can issue access tokens to local users, federated users, or machine identities.

**Topics**
+ [

## API authorization
](#cognito-user-pools-define-resource-servers-about-api-authz)
+ [

## Machine-to-machine (M2M) authorization
](#cognito-user-pools-define-resource-servers-about-m2m)
+ [

## About scopes
](#cognito-user-pools-define-resource-servers-about-scopes)
+ [

## About resource servers
](#cognito-user-pools-define-resource-servers-about-resource-servers)
+ [

## Resource binding
](#cognito-user-pools-resource-binding)

## API authorization
<a name="cognito-user-pools-define-resource-servers-about-api-authz"></a>

The following are some of the ways that you can authorize requests to APIs with Amazon Cognito tokens:

**Access token**  
When add an Amazon Cognito authorizer to a REST API method request configuration, add **Authorization scopes** to the authorizer configuration. With this configuration, your API accepts access tokens in the `Authorization` header and reviews them for accepted scopes.

**ID token**  
When you pass a valid ID token to an Amazon Cognito authorizer in your REST API, API Gateway accepts the request and passes the ID token contents to the API backend.

**Amazon Verified Permissions**  
In Verified Permissions, you have the option to create an [API-linked policy store](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-stores_api-userpool.html). Verified Permissions creates and assigns a Lambda authorizer that processes ID or access tokens from your request `Authorization` header. This Lambda authorizer passes your token to your policy store, where Verified Permissions compares it to policies and returns an allow or deny decision to the authorizer.

**More resources**
+ [Controlling and managing access to a REST API in API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html)
+ [Authorization with Amazon Verified Permissions](amazon-cognito-authorization-with-avp.md)

## Machine-to-machine (M2M) authorization
<a name="cognito-user-pools-define-resource-servers-about-m2m"></a>

Amazon Cognito supports applications that access API data with *machine identities*. Machine identities in user pools are [confidential clients](user-pool-settings-client-apps.md#user-pool-settings-client-app-client-types) that run on application servers and connect to remote APIs. Their operation happens without user interaction: scheduled tasks, data streams, or asset updates. When these clients authorize their requests with an access token, they perform *machine to machine*, or M2M, authorization. In M2M authorization, a shared secret replaces user credentials in access control.

An application that accesses an API with M2M authorization must have a client ID and client secret. In your user pool, you must build an app client that supports client credentials grants. To support client credentials, your app client must have a client secret and you must have a user pool domain. In this flow, your machine identity requests an access token directly from the [Token endpoint](token-endpoint.md). You can authorize only custom scopes from [resource servers](#cognito-user-pools-define-resource-servers-about-resource-servers) in access tokens for client credentials grants. For more information about setting up app clients, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).

The access token from a client credentials grant is a verifiable statement of the operations that you want to permit your machine identity to request from an API. To learn more about how access tokens authorize API requests, continue reading. For an example application, see [Amazon Cognito and API Gateway based machine to machine authorization using AWS CDK](https://github.com/aws-samples/amazon-cognito-and-api-gateway-based-machine-to-machine-authorization-using-aws-cdk).

M2M authorization has a billing model that differs from the way that monthly active users (MAUs) are billed. Where user authentication carries a cost per active user, M2M billing reflects active client credentials app clients and total token-request volume. For more information, see [Amazon Cognito Pricing](https://aws.amazon.com/cognito/pricing). To control costs for M2M authorization, optimize the duration of access tokens and the number of token requests that your applications make. See [Managing user pool token expiration and caching](amazon-cognito-user-pools-using-tokens-caching-tokens.md) for a way to use API Gateway caching to reduce requests for new tokens in M2M authorization.

For information about optimizing Amazon Cognito operations that add costs to your AWS bill, see [Managing costs](tracking-cost.md#tracking-cost-managing).

**Client metadata for machine-to-machine (M2M) client credentials**  
You can pass [client metadata](cognito-user-pools-working-with-lambda-triggers.md#working-with-lambda-trigger-client-metadata) in M2M requests. Client metadata is additional information from a user or application environment that can contribute to the outcomes of a [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md). In authentication operations with a user principal, you can pass client metadata to the pre token generation trigger in the body of [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API requests. Because applications conduct the flow for generation of access tokens for M2M with direct requests to the [Token endpoint](token-endpoint.md), they have a different model. In the POST body of token requests for client credentials, pass an `aws_client_metadata` parameter with the client metadata object URL-encoded (`x-www-form-urlencoded`) to string. For an example request, see [Client credentials with basic authorizationClient credentials with POST body authorization](token-endpoint.md#exchanging-client-credentials-for-an-access-token-in-request-body). The following is an example parameter that passes the key-value pairs `{"environment": "dev", "language": "en-US"}`.

```
aws_client_metadata=%7B%22environment%22%3A%20%22dev%22,%20%22language%22%3A%20%22en-US%22%7D
```

## About scopes
<a name="cognito-user-pools-define-resource-servers-about-scopes"></a>

A *scope* is a level of access that an app can request to a resource. In an Amazon Cognito access token, the scope is backed up by the trust that you set up with your user pool: a trusted issuer of access tokens with a known digital signature. User pools can generate access tokens with scopes that prove your customer is allowed to manage some or all of their own user profile, or to retrieve data from a back-end API. Amazon Cognito user pools issue access tokens with *the user pools reserved API scope*, *custom scopes*, and *OpenID Connect (OIDC) scopes*.

**The user pools reserved API scope**  
The `aws.cognito.signin.user.admin` scope authorizes self-service operations for the current user in the Amazon Cognito user pools API. It authorizes the bearer of an access token to query and update all information about the bearer with, for example, the [GetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html) and [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html) API operations. When you authenticate your user with the Amazon Cognito user pools API, this is the only scope you receive in the access token. It's also the only scope you need to read and write user attributes that you've authorized your app client to read and write. You can also request this scope in requests to your [Authorize endpoint](authorization-endpoint.md). This scope alone isn't sufficient to request user attributes from the [userInfo endpoint](userinfo-endpoint.md). For access tokens that authorize both user pools API *and* `userInfo` requests for your users, you must request both of the scopes `openid` and `aws.cognito.signin.user.admin` in an `/oauth2/authorize` request.

**Custom scopes**  
Custom scopes authorize requests to the external APIs that resource servers protect. You can request custom scopes with other types of scopes. You can find more information about custom scopes throughout this page.

**OpenID Connect (OIDC) scopes**  
When you authenticate users with your user pool authorization server, including with managed login, you must request scopes. You can authenticate user pool local users and third-party federated users in your Amazon Cognito authorization server. OIDC scopes authorize your app to read user information from the [userInfo endpoint](userinfo-endpoint.md) of your user pool. The OAuth model, where you query user attributes from the `userInfo` endpoint, can optimize your app for a high volume of requests for user attributes. The `userInfo` endpoint returns attributes at a permission level that's determined by the scopes in the access token. You can authorize your app client to issue access tokens with the following OIDC scopes.

openid  
The minimum scope for OpenID Connect (OIDC) queries. Authorizes the ID token, the unique-identifier claim `sub`, and the ability to request other scopes.  
When you request the `openid` scope and no others, your user pool ID token and `userInfo` response include claims for all user attributes that your app client can read. When you request `openid` and other OIDC scopes like `profile`, `email`, and `phone`, the contents of the ID token and [userInfo](userinfo-endpoint.md#userinfo-endpoint.title) response are limited to the constraints of the additional scopes.  
For example, a request to the [Authorize endpoint](authorization-endpoint.md) with the parameter `scope=openid+email` returns an ID token with `sub`, `email`, and `email_verified`. The access token from this request returns the same attributes from [userInfo endpoint](userinfo-endpoint.md). A request with parameter `scope=openid` returns all client-readable attributes in the ID token and from `userInfo`.

profile  
Authorizes all user attributes that the app client can read.

email  
Authorizes the user attributes `email` and `email_verified`. Amazon Cognito returns `email_verified` if it has had a value explicitly set.

phone  
Authorizes the user attributes `phone_number` and `phone_number_verified`.

## About resource servers
<a name="cognito-user-pools-define-resource-servers-about-resource-servers"></a>

A resource server API might grant access to the information in a database, or control your IT resources. An Amazon Cognito access token can authorize access to APIs that support OAuth 2.0. Amazon API Gateway REST APIs have [built-in support](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) for authorization with Amazon Cognito access tokens. Your app passes the access token in the API call to the resource server. The resource server inspects the access token to determine if access should be granted.

Amazon Cognito might make future updates to the schema of user pool access tokens. If your app analyzes the contents of the access token before it passes it to an API, you must engineer your code to accept updates to the schema.

Custom scopes are defined by you, and extend the authorization capabilities of a user pool to include purposes unrelated to querying and modifying users and their attributes. For example, if you have a resource server for photos, it might define two scopes: `photos.read` for read access to the photos and `photos.write` for write/delete access. You can configure an API to accept access tokens for authorization, and grant `HTTP GET` requests to access tokens with `photos.read` in the `scope` claim, and `HTTP POST` requests to tokens with `photos.write`. These are *custom scopes*.

**Note**  
Your resource server must verify the access token signature and expiration date before processing any claims inside the token. For more information about verifying tokens, see [Verifying JSON web tokens](amazon-cognito-user-pools-using-tokens-verifying-a-jwt.md). For more information about verifying and using user pool tokens in Amazon API Gateway, see the blog [Integrating Amazon Cognito User Pools with API Gateway](https://aws.amazon.com/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-gateway/). API Gateway is a good option for inspecting access tokens and protecting your resources. For more about API Gateway Lambda authorizers, see [Use API Gateway Lambda authorizers](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html).

**Overview**  
With Amazon Cognito, you can create OAuth 2.0 **Resource servers** and associate **Custom scopes** with them. Custom scopes in an access token authorize specific actions in your API. You can authorize any app client in your user pool to issue custom scopes from any of your resource servers. Associate your custom scopes with an app client and request those scopes in OAuth 2.0 authorization code grants, implicit grants, and client credentials grants from the [Token endpoint](token-endpoint.md). Amazon Cognito adds custom scopes to the `scope` claim in an access token. A client can use the access token against its resource server, which makes the authorization decision based on the scopes present in the token. For more information about access token scope, see [Using Tokens with User Pools](amazon-cognito-user-pools-using-tokens-with-identity-providers.md).

![\[An overview of the flow of a resource server. The client requests a grant with a custom scope, the user pool returns an access token with the custom scope, and the client presents the access token to an API.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/resource-servers.png)


To get an access token with custom scopes, your app must make a request to the [Token endpoint](token-endpoint.md) to redeem an authorization code or to request a client credentials grant. In managed login, you can also request custom scopes in an access token from an implicit grant.

**Note**  
Because they are designed for human-interactive authentication with the user pool as the IdP, [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) requests only produce a `scope` claim in the access token with the single value `aws.cognito.signin.user.admin`.

**Managing the Resource Server and Custom Scopes**

When creating a resource server, you must provide a resource server name and a resource server identifier. For each scope you create in the resource server, you must provide the scope name and description.
+ **Resource server name**: A friendly name for the resource server, such as `Solar system object tracker` or `Photo API`.
+ **Resource server identifier**: A unique identifier for the resource server. The identifier is any name that you want to associate with your API, for example `solar-system-data`. You can configure longer identifiers like `https://solar-system-data-api.example.com` as a more direct reference to API URI paths, but longer strings increase the size of access tokens.
+ **Scope name**: The value that you want in your `scope` claims. For example, `sunproximity.read`.
+ **Description**: A friendly description of the scope. For example, `Check current proximity to sun`.

Amazon Cognito can include custom scopes in access tokens for any users, whether they are local to your user pool or federated with a third-party identity provider. You can choose scopes for your users' access tokens during authentication flows with the OAuth 2.0 authorization server that includes managed login. Your user's authentication must begin at the [Authorize endpoint](authorization-endpoint.md) with `scope` as one of the request parameters. The following is a recommended format for resource servers. For an identifier, use an API friendly name. For a custom scope, use the action that they authorize.

```
resourceServerIdentifier/scopeName
```

For example, you've discovered a new asteroid in the Kuiper belt and you want to register it through your `solar-system-data` API. The scope that authorizes write operations to the database of asteroids is `asteroids.add`. When you request the access token that will authorize you to register your discovery, format your `scope` HTTPS request parameter as `scope=solar-system-data/asteroids.add`.

Deleting a scope from a resource server does not delete its association with all clients. Instead, the scope is marked *inactive*. Amazon Cognito doesn't add inactive scopes to access tokens, but otherwise proceeds as normal if your app requests one. If you add the scope to your resource server again later, then Amazon Cognito again writes it to the access token. If you request a scope that you haven't associated with your app client, regardless of whether you deleted it from your user pool resource server, authentication fails.

You can use the AWS Management Console, API, or CLI to define resource servers and scopes for your user pool.

### Defining a resource server for your user pool (AWS Management Console)
<a name="cognito-user-pools-define-resource-servers-console"></a>

You can use the AWS Management Console to define a resource server for your user pool.

**To define a resource server**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home).

1. In the navigation pane, choose **User Pools**, and choose the user pool you want to edit.

1. Choose the **Domain** menu under **Branding** and locate **Resource servers**.

1. Choose **Create a resource server**.

1. Enter a **Resource server name**. For example, `Photo Server`.

1. Enter a **Resource server identifier**. For example, `com.example.photos`.

1. Enter **Custom scopes** for your resources, such as `read` and `write`.

1. For each **Scope name**, enter a **Description**, such as `view your photos` and `update your photos`.

1. Choose **Create**.

Your custom scopes can be reviewed in the **Domain** menu under **Resource servers**, in the **Custom scopes** column. Custom scopes can be enabled for app clients from the **App clients** menu under **Applications**. Select an app client, locate **Login pages** and choose **Edit**. Add **Custom scopes** and choose **Save changes**.

### Defining a resource server for your user pool (AWS CLI and AWS API)
<a name="cognito-user-pools-define-resource-servers-cli-api"></a>

Use the following commands to specify resource server settings for your user pool.

**To create a resource server**
+ AWS CLI: `aws cognito-idp create-resource-server`
+ AWS API: [CreateResourceServer](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateResourceServer.html)

**To get information about your resource server settings**
+ AWS CLI: `aws cognito-idp describe-resource-server`
+ AWS API: [DescribeResourceServer](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeResourceServer.html)

**To list information about all resource servers for your user pool**
+ AWS CLI: `aws cognito-idp list-resource-servers`
+ AWS API: [ListResourceServers](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListResourceServers.html)

**To delete a resource server**
+ AWS CLI: `aws cognito-idp delete-resource-server`
+ AWS API: [DeleteResourceServer](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteResourceServer.html)

**To update the settings for a resource server**
+ AWS CLI: `aws cognito-idp update-resource-server`
+ AWS API: [UpdateResourceServer](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateResourceServer.html)

## Resource binding
<a name="cognito-user-pools-resource-binding"></a>

With resource binding, also referred to as resource indicators, you can request API-specific grants from your user pool authorization server. Resource binding is an OAuth 2.0 extension defined in [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html) that allows clients to explicitly specify which resource server they intend to access during authorization requests. With resource binding, your API configurations can decline access for tokens that aren't specifically intended for them.

**Note**  
You can only bind access tokens to resources for users. You can't request a resource binding with client-credentials M2M grants.

When you use resource binding with Amazon Cognito user pools, clients can include a `resource` parameter in their authentication requests to your user pool authorization server . Your user pool validates that the value of the requested resource is a URL, following the same scheme rules as [app client](user-pool-settings-client-apps.md#cognito-user-pools-app-idp-settings-about) callback URLs: `https://`, `http://` with `localhost` only, or a custom scheme like `myapp://`. Amazon Cognito sets the requested URI as the audience in the `aud` claim of the [access token](amazon-cognito-user-pools-using-the-access-token.md). If the requested resource is a user pool resource server, the resource server identifier must be in a URL format. You can request one resource per authentication request.

This feature is exclusive to [managed login authentication](authentication-flows-selection-managedlogin.md) with your user pool OAuth 2.0 authorization server. You can request resource binding in implicit and authorization-code grants from the [Authorize endpoint](authorization-endpoint.md). Token-refresh grants from the [Token endpoint](token-endpoint.md) carry over the `aud` claim from the original request. It is not currently available in [SDK authentication models](authentication-flows-selection-sdk.md).

**Implement resource binding with your Amazon Cognito user pool**

1. Configure one or more resource servers in your user pool with unique identifiers.

1. In your authorization request to `/oauth2/authorize`, request an authorization code or implicit grant and include the `resource` parameter. The value of `resource` must be a URL-formatted resource server identifier or a URL. For example, `&resource=https://solar-system-data-api.example.com`.

1. The authorization server validates the resource request, completes authentication, and sets the access token `aud` claim to the requested resource URL.

1. To validate that tokens were issued specifically for it, the resource that consumes your user's access token checks the `aud` claim.

# Configure user pool features
<a name="user-pools-configure-features"></a>

In previous chapters, you've likely configured some features with guidance from the Amazon Cognito console. The pages in this section are a deeper dive into the detailed configuration requirements of some of the core features of user pools. There's important reference information about your options with app clients, email and SMS configuration, remembering user devices, and more.

**Topics**
+ [

# Updating user pool and app client configuration
](cognito-user-pool-updating.md)
+ [

# Application-specific settings with app clients
](user-pool-settings-client-apps.md)
+ [

# Working with user devices in your user pool
](amazon-cognito-user-pools-device-tracking.md)
+ [

# Using Amazon Pinpoint for user pool analytics
](cognito-user-pools-pinpoint-integration.md)
+ [

# Email settings for Amazon Cognito user pools
](user-pool-email.md)
+ [

# SMS message settings for Amazon Cognito user pools
](user-pool-sms-settings.md)

# Updating user pool and app client configuration
<a name="cognito-user-pool-updating"></a>

When you want to change a setting in a user pool or app client, you can apply the update in the Amazon Cognito console with a few clicks. You navigate through the feature-based tabs in your user pool settings and update fields as described in other areas of this guide.

Many organizations manage their resources programmatically in AWS CloudFormation, applications built on the AWS SDKs or CDK, and other automation software. When this is your resource-management model, you must take extra care when you stage changes to your resources.

The API operations [ UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) and [ UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) make updates to an existing user pool or app client. Each comes with a warning in the API Reference: *If you don't provide a value for an attribute, Amazon Cognito sets it to its default value.* When you submit an update request with just one parameter, Amazon Cognito sets that parameter to the value of your choosing and sets all others to a default value. This can reset configurations including your attribute schema, your Lambda triggers, and your email and SMS message configuration.

Additionally, some settings are locked in after you create your user pool or app client, and you can't change them unless you create a new resource.

**Topics**
+ [

## Settings you can't change
](#cognito-user-pool-updating-fixed-settings)
+ [

## SMS configuration
](#cognito-user-pool-updating-sms)
+ [

## Updating a user pool with an AWS SDK, AWS CDK, or REST API
](#cognito-user-pool-updating-api-cli)

## Settings you can't change
<a name="cognito-user-pool-updating-fixed-settings"></a>

You can't change some settings after you create a user pool. If you want to change the following settings, you must create a new user pool or app client.

**Note**  
Previously, you couldn't change the name of a user pool. This has changed. You can now assign new friendly names to your user pools.

**User pool ID**  
API parameter name: [Id/UserPoolId](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UserPoolType.html#CognitoUserPools-Type-UserPoolType-ID)  
The user pool ID, for example `us-east-1_EXAMPLE`, is automatically generated by Amazon Cognito and can't be changed.

**Amazon Cognito user pool sign-in options**  
API parameter names: [AliasAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-AliasAttributes) and [UsernameAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-UsernameAttributes)  
The attributes that your users can pass as a user name when they sign in. When you create a user pool, you can choose to allow sign-in with user name, email address, phone number, or a preferred user name. To change user pool sign-in options, create a new user pool.

**Make user name case sensitive**  
API parameter name: [UsernameConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-UsernameConfiguration)  
When you create a user name that matches another user name except for the letter case, Amazon Cognito can treat them as either the same user or as unique users. For more information, see [User pool case sensitivity](user-pool-case-sensitivity.md). To change case sensitivity, create a new user pool.

**Client secret**  
API parameter name: [GenerateSecret](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-GenerateSecret)  
When you create an app client, you can generate a client secret so that only trusted sources can make requests to your user pool. For more information, see [Application-specific settings with app clients](user-pool-settings-client-apps.md). To change a client secret, create a new app client in the same user pool.

**Required attributes**  
API parameter name: [Schema](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-Schema)  
The attributes that your users must provide values for when they sign up, or when you create them. For more information, see [Working with user attributes](user-pool-settings-attributes.md). To change required attributes, create a new user pool.

**Custom attributes (deletion)**  
API parameter name: [Schema](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-Schema)  
Attributes with custom names. You can change the value of a user's custom attribute, but you can't delete a custom attribute from your user pool. For more information, see [Working with user attributes](user-pool-settings-attributes.md). If you reach the maximum number of custom attributes and you want to modify the list, create a new user pool.

## SMS configuration
<a name="cognito-user-pool-updating-sms"></a>

After you activate SMS messages in your user pool, you can't deactivate them.
+ If you choose to configure SMS messages when you create a user pool, you can't deactivate SMS after you complete setup.
+ You can activate SMS messages in a user pool that you created, but after that you can't deactivate SMS.
+ Amazon Cognito can use SMS messages for user account invitation and recovery, attribute verification, and multi-factor authentication (MFA). After you activate SMS messages, you can turn SMS messages on or off for these functions at any time.
+ SMS message configuration includes an IAM role that you delegate to Amazon Cognito to send messages with Amazon SNS. You can change the assigned role at any time.

## Updating a user pool with an AWS SDK, AWS CDK, or REST API
<a name="cognito-user-pool-updating-api-cli"></a>

In the Amazon Cognito console, you can change your user pool settings one parameter at a time. For example, to add a Lambda trigger, you choose **Add Lambda trigger** and choose the function and trigger type. The Amazon Cognito user pools API is structured in a way that update operations for user pools and app clients require the full set of parameters for the user pool. However, the console transparently automates this update operation with your other user pool settings.

You might find at times that a change elsewhere in your AWS account can cause updates to generate an error when they aren't related to the setting you want to change. A deleted Amazon SES identity or a change in an IAM permission for AWS WAF, for example. If one of the current parameters is no longer valid, you can't update your settings until you fix it. When you encounter such an error, examine the error response and validate the setting that it mentions.

The [AWS Cloud Development Kit (AWS CDK)](https://aws.amazon.com/cdk), [Amazon Cognito user pools REST API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html) and [AWS SDKs](https://aws.amazon.com/developer/tools/) are tools for automation and programmatic configuration of Amazon Cognito resources. Requests with these tools must also, like the Amazon Cognito console, update a setting with a full resource configuration in the request body. At a high level, you must perform the following process.

1. Capture the output from an operation that describes the configuration of your existing resource .

1. Modify the output with your settings change.

1. Send the modified configuration in an operation that updates your resource.

The following procedure updates your configuration with the [ UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API operation. The same approach, with different input fields, applies to [ UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html).

**Important**  
If you don't provide values for existing parameters, Amazon Cognito sets them to default values. For example, when you have existing `LambdaConfig` and you submit an `UpdateUserPool` with an empty `LambdaConfig`, you delete the assignment of all Lambda functions to user pool triggers. Plan accordingly when you want to automate changes to your user pool configuration.

1. Capture the existing state of your user pool with [ DescribeUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPool.html).

1. Format the output of `DescribeUserPool` to match the [ request parameters](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html#API_UpdateUserPool_RequestSyntax) of `UpdateUserPool`. Remove the following top-level fields and their child objects from the output JSON.
   + `Arn`
   + `CreationDate`
   + `CustomDomain`
     + Update this field with the [UpdateUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolDomain.html) API operation.
   + `Domain`
     + Update this field with the [UpdateUserPoolDomain](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolDomain.html) API operation.
   + `EmailConfigurationFailure`
   + `EstimatedNumberOfUsers`
   + `Id`
   + `LastModifiedDate`
   + `Name`
   + `SchemaAttributes`
   + `SmsConfigurationFailure`
   + `Status`

1. Confirm that the resulting JSON matches the [ request parameters](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html#API_UpdateUserPool_RequestSyntax) of `UpdateUserPool`.

1. Modify any parameters that you want to change in the resulting JSON.

1. Submit an `UpdateUserPool` API request with your modified JSON as the request input.

You can also use this modified `DescribeUserPool` output in the `--cli-input-json` parameter of `update-user-pool` in the AWS CLI.

Alternately, run the following AWS CLI command to generate JSON with blank values for the accepted input fields for `update-user-pool`. You can then populate these fields with the existing values from your user pool.

```
aws cognito-idp update-user-pool --generate-cli-skeleton --output json
```

Run the following command to generate the same JSON object for an app client.

```
aws cognito-idp update-user-pool-client --generate-cli-skeleton --output json
```

# Application-specific settings with app clients
<a name="user-pool-settings-client-apps"></a>

A user pool app client is a configuration within a user pool that interacts with one mobile or web application that authenticates with Amazon Cognito. App clients can call authenticated and unauthenticated API operations, and read or modify some or all of your users' attributes. Your app must identify itself to the app client in operations to register, sign in, and handle forgotten passwords. These API requests must include self-identification with an app client ID, and authorization with an optional client secret. You must secure any app client IDs or secrets so that only authorized client apps can call these unauthenticated operations. Additionally, if you configure your app to sign authenticated API requests with AWS credentials, you must secure your credentials against user inspection.

You can create multiple apps for a user pool. An app client might be linked to the code platform of an app, or a separate tenant in your user pool. For example, you might create an app for a server-side application and a different Android app. Each app has its own app client ID.

You can apply settings for the following user pool features at the app client level:

1. [Analytics](cognito-user-pools-pinpoint-integration.md)

1. [Managed login](cognito-user-pools-managed-login.md) IdPs, grant types, callback URLs, and customization

1. [Resource servers and custom scopes](cognito-user-pools-define-resource-servers.md)

1. [Threat protection](cognito-user-pool-settings-threat-protection.md)

1. [Attribute read and write permissions](user-pool-settings-attributes.md#user-pool-settings-attribute-permissions-and-scopes)

1. [Token expiration and revocation](amazon-cognito-user-pools-using-tokens-with-identity-providers.md)

1. [Authentication flows](authentication.md#amazon-cognito-user-pools-authentication-flow)

## App client types
<a name="user-pool-settings-client-app-client-types"></a>

When you create an app client in Amazon Cognito, you can pre-populate options based on the standard OAuth client types **public client** and **confidential client**. Configure a **confidential client** with a **client secret**. For more information about client types, see [IETF RFC 6749 \$12.1](https://datatracker.ietf.org/doc/html/rfc6749#section-2.1).

**Public client**  
A public client runs in a browser or on a mobile device. Because it does not have trusted server-side resources, it does not have a client secret.

**Confidential client**  
A confidential client has server-side resources that can be trusted with a **client secret** for unauthenticated API operations. The app might run as a daemon or shell script on your backend server.

**Client secret**  
A client secret, or client password, is a fixed string that your app must use in all API requests to the app client. Your app client must have a client secret to perform `client_credentials` grants. For more information, see [IETF RFC 6749 \$12.3.1](https://datatracker.ietf.org/doc/html/rfc6749#section-2.3.1).  
Each app client can have up to two secrets at a time, enabling secret rotation without downtime. When you create an app client, you can either let Amazon Cognito generate a secret value or provide your own custom secret value. You can't change secrets after you create an app. You can add a second secret with the [AddUserPoolClientSecret](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AddUserPoolClientSecret.html) API operation to rotate secrets. When you add a secret, you can either let Amazon Cognito generate a secret value or provide your own custom secret value. To delete a secret, use the [DeleteUserPoolClientSecret](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPoolClientSecret.html) API operation. You cannot delete the only secret associated with an app client. You can also delete an app to block access from apps that use that app client ID.  
The Amazon Cognito console creates app clients with client secrets when you select the **Traditional web application** and **Machine-to-machine application** options for application type. Choose one of these options to generate a client secret, or create the client programmatically with [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) and set `GenerateSecret` to `true`.

You can use a confidential client, and a client secret, with a public app. Use an Amazon CloudFront proxy to add a `SECRET_HASH` in transit. For more information, see [Protect public clients for Amazon Cognito by using an Amazon CloudFront proxy](https://aws.amazon.com/blogs/security/protect-public-clients-for-amazon-cognito-by-using-an-amazon-cloudfront-proxy/) on the AWS blog.

## JSON web tokens
<a name="user-pool-settings-client-app-token-types"></a>

Amazon Cognito app clients can issue JSON web tokens (JWTs) of the following types.

**Identity (ID) token**  
A verifiable statement that your user is authenticated from your user pool. OpenID Connect (OIDC) added the [ID token specification](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) to the access and refresh token standards defined by OAuth 2.0. The ID token contains identity information, like user attributes, that your app can use to create a user profile and provision resources. See [Understanding the identity (ID) token](amazon-cognito-user-pools-using-the-id-token.md) for more information.

**Access token**  
A verifiable statement of your user's access rights. The access token contains [scopes](https://datatracker.ietf.org/doc/html/rfc6749#section-3.3), a feature of OIDC and OAuth 2.0. Your app can present scopes to back-end resources and prove that your user pool authorized a user or machine to access data from an API, or their own user data. An access token with *custom scopes*, often from an M2M client-credentials grant, authorizes access to a resource server. See [Understanding the access token](amazon-cognito-user-pools-using-the-access-token.md) for more information.

**Refresh token**  
An encrypted statement of initial authentication that your app can present to your user pool when your user's tokens expire. A refresh-token request returns new, unexpired access and ID tokens. See [Refresh tokens](amazon-cognito-user-pools-using-the-refresh-token.md) for more information.

You can set the expiration of these tokens for each app client from the **App clients** menu of your user pool in the [Amazon Cognito console](https://console.aws.amazon.com/cognito/v2/idp/user-pools).

## App client terms
<a name="cognito-user-pools-app-idp-settings-about"></a>

The following terms are available properties of app clients in the Amazon Cognito console.

**Allowed callback URLs**  
A callback URL indicates where the user will be redirected after a successful sign-in. Choose at least one callback URL. The callback URL must:  
+ Be an absolute URI.
+ Be pre-registered with a client.
+ Not include a fragment component.
See [OAuth 2.0 - redirection endpoint](https://tools.ietf.org/html/rfc6749#section-3.1.2).  
Amazon Cognito requires `HTTPS` over `HTTP` except for `http://localhost` for testing purposes only.  
App callback URLs such as `myapp://example` are also supported.

**Allowed sign out URLs**  
A sign-out URL indicates where your user is to be redirected after signing out.

**Attribute read and write permissions**  
Your user pool might have many customers, each with their own app client and IdPs. You can configure your app client to have read and write access to only those user attributes that are relevant to the app. In cases like machine-to-machine (M2M) authorization, you can grant access to none of your user attributes.  

**Considerations for attribute read and write permissions configuration**
+ When you create an app client and don't customize attribute read and write permissions, Amazon Cognito grants read and write permissions to all user pool attributes.
+ You can grant write access to immutable [custom attributes](user-pool-settings-attributes.md#user-pool-settings-custom-attributes.title). Your app client can write values to immutable attributes when you create or sign up a user. After this, you can't write values to any immutable custom attributes for the user.
+ App clients must have write access to required attributes in your user pool. The Amazon Cognito console automatically sets required attributes as writeable.
+ You can't permit an app client to have write access to `email_verified` or `phone_number_verified`. A user pool administrator can modify these values. A user can only change the value of these attributes through [attribute verification](signing-up-users-in-your-app.md#allowing-users-to-sign-up-and-confirm-themselves.title).

**Authentication flows**  
The methods that your app client allows for sign-in. Your app can support authentication with username and password, email and SMS message OTPs, passkey authenticators, custom authentication with Lambda triggers, and token refresh. As a best security practice, use SRP authentication for username and password authentication in custom-built applications.

**Custom scopes**  
A custom scope is one that you define for your own resource server in the **Resource Servers**. The format is *resource-server-identifier*/*scope*. See [Scopes, M2M, and resource servers](cognito-user-pools-define-resource-servers.md).

**Default redirect URI**  
Replaces the `redirect_uri` parameter in authentication requests for users with third-party IdPs. Configure this app client setting with the `DefaultRedirectURI` parameter of a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) API request. This URL must also be a member of the `CallbackURLs` for your app client. Amazon Cognito redirects authenticated sessions to this URL when:  

1. Your app client has one [identity provider](#app-client-terms-identity-provider) assigned and multiple [callback URLs](#app-client-terms-callback-urls) defined. Your user pool redirects authentication requests to the [authorization server](authorization-endpoint.md) to the default redirect URI when they don't include a `redirect_uri` parameter.

1. Your app client has one [identity provider](#app-client-terms-identity-provider) assigned and one [callback URLs](#app-client-terms-callback-urls) defined. In this scenario it's not necessary to define a default callback URL. Requests that don't include a `redirect_uri` parameter redirect to the one available callback URL.

**Identity providers**  
You can choose some or all of your user pool external identity providers (IdPs) to authenticate your users. Your app client can also authenticate only local users in your user pool. When you add an IdP to your app client, you can generate authorization links to the IdP and display it on your managed login sign-in page. You can assign multiple IdPs, but you must assign at least one. For more information on using external IdPs, see [User pool sign-in with third party identity providers](cognito-user-pools-identity-federation.md).

**OpenID Connect scopes**  
Choose one or more of the following `OAuth` scopes to specify the access privileges that can be requested for access tokens.  
+ The `openid` scope declares that you want to retrieve an ID token and a user's unique ID. It also requests all or some user attributes, depending on additional scopes in the request. Amazon Cognito doesn't return an ID token unless you request the `openid` scope. The `openid` scope authorizes structural ID token claims like expiration and key ID, and determines the user attributes that you receive in a response from the [userInfo endpoint](userinfo-endpoint.md).
  + When `openid` is the only scope that you request, Amazon Cognito populates the ID token with all user attributes that the current app client can read. The `userInfo` response to an access token with this scope alone returns all user attributes.
  + When you request `openid` with other scopes like `phone`, `email`, or `profile`, the ID token and `userInfo` return the user's unique ID and the attributes defined by the additional scopes.
+ The `phone` scope grants access to the `phone_number` and `phone_number_verified` claims. This scope can only be requested with the `openid` scope.
+ The `email` scope grants access to the `email` and `email_verified` claims. This scope can only be requested with the `openid` scope.
+ The `aws.cognito.signin.user.admin` scope grants access to [Amazon Cognito user pools API operations](authentication-flows-public-server-side.md#user-pools-API-operations) that require access tokens, such as [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html) and [VerifyUserAttribute](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html).
+ The `profile` scope grants access to all user attributes that are readable by the client. This scope can only be requested with the `openid` scope.
For more information about scopes, see the list of [standard OIDC scopes](http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims).

**OAuth grant types**  
An OAuth grant is a method of authentication that retrieves user-pool tokens. Amazon Cognito supports the following types of grants. To integrate these OAuth grants in your app, you must add a domain to your user pool.  
**Authorization code grant**  
The authorization code grant generates a code that your app can exchange for user pool tokens with the [Token endpoint](token-endpoint.md). When you exchange an authorization code, your app receives ID, access, and refresh tokens. This OAuth flow, like the implicit grant, happens in your users' browsers. An authorization code grant is the most secure grant that Amazon Cognito offers, because tokens aren't visible in your users' sessions. Instead, your app generates the request that returns tokens and can cache them in protected storage. For more information, see *Authorization code* in [IETF RFC 6749 \$11.3.1](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.1)
As a best security practice in public-client apps, activate only the authorization-code grant OAuth flow, and implement Proof Key for Code Exchange (PKCE) to restrict token exchange. With PKCE, a client can only exchange an authorization code when they have provided the token endpoint with the same secret that was presented in the original authentication request. For more information on PKCE, see [IETF RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636).
**Implicit grant**  
The implicit grant delivers an access and ID token, but not refresh token, to your user's browser session directly from the [Authorize endpoint](authorization-endpoint.md). An implicit grant removes the requirement for a separate request to the token endpoint, but isn't compatible with PKCE and doesn't return refresh tokens. This grant accommodates testing scenarios and app architecture that can't complete authorization-code grants. For more information, see *Implicit grant* in [IETF RFC 6749 \$11.3.2](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.2). You can activate both the authorization-code grant and the implicit grant in an app client, and then use each grant as needed.
**Client credentials grant**  
The client credentials grant is for machine-to-machine (M2M) communications. Authorization-code and implicit grants issue tokens to authenticated human users. Client credentials grant scope-based authorization from a non-interactive system to an API. Your app can request client credentials directly from the token endpoint and receive an access token. For more information, see *Client Credentials* in [IETF RFC 6749 \$11.3.4](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.4). You can only activate client-credentials grants in app clients that have a client secret and that don't support authorization-code or implicit grants.
Because you don't invoke the client credentials flow as a user, this grant can only add *custom* scopes to access tokens. A custom scope is one that you define for your own resource server. Default scopes like `openid` and `profile` don't apply to nonhuman users.  
Because ID tokens are a validation of user attributes, they aren't relevant to M2M communication, and a client credentials grants doesn't issue them. See [Scopes, M2M, and resource servers](cognito-user-pools-define-resource-servers.md).
Client credentials grants add costs to your AWS bill. For more information, see [Amazon Cognito Pricing](https://aws.amazon.com/cognito/pricing).

## Creating an app client
<a name="cognito-user-pools-app-idp-settings-console-create"></a>

------
#### [ AWS Management Console ]

**To create an app client (console)**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or create a user pool. Both options prompt you to configure an app client with application-specific settings.

1. Choose an **Application type** that reflects your application architecture.

1. **Name your application** with a friendly identifier.

1. Enter a **Return URL**.

1. Choose **Create app client**. You can change advanced options after you create your app client.

1. Amazon Cognito returns you to app client details. To access example code for your application, select a platform from the **Quick setup guide** tab.

------
#### [ AWS CLI ]

```
aws cognito-idp create-user-pool-client --user-pool-id MyUserPoolID --client-name myApp
```

**Note**  
Use JSON format for callback and logout URLs to prevent the CLI from treating them as remote parameter files:  

```
--callback-urls "["https://example.com"]"
--logout-urls "["https://example.com"]"
```

See the AWS CLI command reference for more information: [create-user-pool-client](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html)

------
#### [ Amazon Cognito user pools API ]

Generate a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) API request. You must specify a value for all parameters that you don't want set to a default value.

------

## Updating a user pool app client (AWS CLI and AWS API)
<a name="cognito-user-pools-app-idp-settings-cli-api-update-user-pool-client"></a>

At the AWS CLI, enter the following command:

```
aws cognito-idp update-user-pool-client --user-pool-id  "MyUserPoolID" --client-id "MyAppClientID" --allowed-o-auth-flows-user-pool-client --allowed-o-auth-flows "code" "implicit" --allowed-o-auth-scopes "openid" --callback-urls "["https://example.com"]" --supported-identity-providers "["MySAMLIdP", "LoginWithAmazon"]"
```

If the command is successful, the AWS CLI returns a confirmation:

```
{
    "UserPoolClient": {
        "ClientId": "MyClientID",
        "SupportedIdentityProviders": [
            "LoginWithAmazon",
            "MySAMLIdP"
        ],
        "CallbackURLs": [
            "https://example.com"
        ],
        "AllowedOAuthScopes": [
            "openid"
        ],
        "ClientName": "Example",
        "AllowedOAuthFlows": [
            "implicit",
            "code"
        ],
        "RefreshTokenValidity": 30,
        "AuthSessionValidity": 3,
        "CreationDate": 1524628110.29,
        "AllowedOAuthFlowsUserPoolClient": true,
        "UserPoolId": "MyUserPoolID",
        "LastModifiedDate": 1530055177.553
    }
}
```

See the AWS CLI command reference for more information: [update-user-pool-client](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html).

AWS API: [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html)

## Getting information about a user pool app client (AWS CLI and AWS API)
<a name="cognito-user-pools-app-idp-settings-cli-api-describe-user-pool-client"></a>

```
aws cognito-idp describe-user-pool-client --user-pool-id MyUserPoolID --client-id MyClientID
```

See the AWS CLI command reference for more information: [describe-user-pool-client](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/describe-user-pool-client.html).

AWS API: [DescribeUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolClient.html)

## Listing all app client information in a user pool (AWS CLI and AWS API)
<a name="cognito-user-pools-app-idp-settings-cli-api-list-user-pool-clients"></a>

```
aws cognito-idp list-user-pool-clients --user-pool-id "MyUserPoolID" --max-results 3
```

See the AWS CLI command reference for more information: [list-user-pool-clients](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/list-user-pool-clients.html).

AWS API: [ListUserPoolClients](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUserPoolClients.html)

## Deleting a user pool app client (AWS CLI and AWS API)
<a name="cognito-user-pools-app-idp-settings-cli-api-delete-user-pool-client"></a>

```
aws cognito-idp delete-user-pool-client --user-pool-id "MyUserPoolID" --client-id "MyAppClientID"
```

See the AWS CLI command reference for more information: [delete-user-pool-client](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/delete-user-pool-client.html)

AWS API: [DeleteUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPoolClient.html)

# Working with user devices in your user pool
<a name="amazon-cognito-user-pools-device-tracking"></a>

When you sign in local user pool users with the Amazon Cognito user pools API, you can associate your users’ activity logs from [threat protection](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-threat-protection.html) with each of their devices and, optionally, allow your users to skip multi-factor authentication (MFA) if they’re on a trusted device. Amazon Cognito includes a device key in the response to any sign-in that doesn’t already include device information. The device key is in the format `Region_UUID`. With a device key, a Secure Remote Password (SRP) library, and a user pool that permits device authentication, you can prompt users in your app to trust the current device and no longer prompt for an MFA code at sign-in.

**Topics**
+ [

## Setting up remembered devices
](#amazon-cognito-user-pools-setting-up-remembered-devices)
+ [

## Getting a device key
](#user-pools-remembered-devices-getting-a-device-key)
+ [

## Signing in with a device
](#user-pools-remembered-devices-signing-in-with-a-device)
+ [

## Viewing, updating and forgetting devices
](#user-pools-remembered-devices-viewing-updating-forgetting)

## Setting up remembered devices
<a name="amazon-cognito-user-pools-setting-up-remembered-devices"></a>

With Amazon Cognito user pools, you can associate each of your users' devices with a unique device identifier: a device key. When you present the device key and perform device authentication at sign-in, you can configure your application with a *trusted device* authentication flow. In this flow, your application can present a choice to users to sign in without MFA until a later time, as determined by the security requirements of your app or the preferences of your users. At the end of that time period, your application must change the device status to *not remembered* and the user must sign in with MFA until they confirm that they want to remember a device. For example, your application might prompt your users to trust a device for 30, 60, or 90 days. You can store this date in a custom attribute and on that date, change the remembered status of their device. You must then re-prompt your user to submit an MFA code and set the device to be remembered again after successful authentication.

1. Remembered devices can override MFA only in user pools with MFA active.

When your user signs in with a remembered device, you must perform an additional device authentication during their authentication flow. For more information, see [Signing in with a device](#user-pools-remembered-devices-signing-in-with-a-device).

Configure your user pool to remember devices in the **Sign-in** menu of your user pool, under **Device tracking**. When setting up the remembered devices functionality through the Amazon Cognito console, you have three options: **Always**, **User Opt-In**, and **No**.

**Don't remember**  
Your user pool doesn't prompt users to remember devices when they sign in.

**Always remember**  
When your app confirms a user's device, your user pool always remembers the device and doesn't return MFA challenges on future successful device sign-ins.

**User opt-in**  
When your app confirms a user's device, your user pool doesn't automatically suppress MFA challenges. You must prompt your user to choose whether they want to remember the device.

When you choose **Always remember** or **User Opt-In**, Amazon Cognito generates a device-identifier key and secret every time a user signs in from an unidentified device. The device key is the initial identifier that your app sends to your user pool when your user performs device authentication.

With each confirmed user device, whether remembered automatically or opted-in, you can use the device-identifier key and secret to authenticate a device on every user sign-in. 

You can also configure remembered-device settings for your user pool in a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request. For more information, see the [DeviceConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html#CognitoUserPools-UpdateUserPool-request-DeviceConfiguration) property.

The Amazon Cognito user pools API has additional operations for remembered devices.

1. [ListDevices](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html) and [AdminListDevices](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListDevices.html) return a list of the device keys and their metadata for a user.

1. [GetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetDevice.html) and [AdminGetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetDevice.html) return the device key and metadata for a single device.

1. [UpdateDeviceStatus](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateDeviceStatus.html) and [AdminUpdateDeviceStatus](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateDeviceStatus.html) set a user's device as remembered or not remembered.

1. [ForgetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgetDevice.html) and [AdminForgetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminForgetDevice.html) remove a user's confirmed device from their profile.

API operations with names that begin with `Admin` are for use in server-side apps and must be authorized with IAM credentials. For more information, see [Understanding API, OIDC, and managed login pages authentication](authentication-flows-public-server-side.md#user-pools-API-operations).

## Getting a device key
<a name="user-pools-remembered-devices-getting-a-device-key"></a>

Any time that your user signs in with the user pools API and doesn’t include a device key in the authentication parameters as `DEVICE_KEY`, Amazon Cognito returns a new device key in the response. In your public client-side app, place the device key in app storage so that you can include it in future requests. In your confidential server-side app, set a browser cookie or another client-side token with your user’s device key.

Before your user can sign in with their trusted device, your app must confirm the device key and provide additional information. Generate a [ConfirmDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmDevice.html) request to Amazon Cognito that confirms your user’s device with the device key, a friendly name, password verifier, and a salt. If you configured your user pool for opt-in device authentication, Amazon Cognito responds to your `ConfirmDevice` request with a prompt that your user must choose whether to remember the current device. Respond with your user’s selection in an [UpdateDeviceStatus](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateDeviceStatus.html) request. 

When you confirm your user’s device but don’t set it as remembered, Amazon Cognito stores the association but proceeds with non-device sign-in when you provide the device key. Devices can generate logs that are useful for user security and troubleshooting. A confirmed but unremembered device doesn’t take advantage of the sign-in feature, but does take advantage of the security monitoring logs feature. When you activate threat protection for your app client and encode a device fingerprint into your request, Amazon Cognito associates user events with the confirmed device. 

**To get a new device key**

1. Start your user’s sign-in session with an [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API request.

1. Respond to all authentication challenges with [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) until you receive JSON web tokens (JWTs) that mark your user’s sign-in session complete.

1. In your app, record the values that Amazon Cognito returns in `NewDeviceMetadata` in its `RespondToAuthChallenge` or `InitiateAuth` response: `DeviceGroupKey` and `DeviceKey`.

1. Generate a new SRP secret for your user: a salt and a password verifier. This function is available in SDKs that provide SRP libraries.

1. Prompt your user for a device name, or generate one from your user’s device characteristics.

1. Provide your user’s access token, device key, device name, and SRP secret in a [ConfirmDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmDevice.html) API request. If your user pool is set to **Always remember** devices, your user’s registration is complete.

1. If Amazon Cognito responded to `ConfirmDevice` with `"UserConfirmationNecessary": true`, prompt your user to choose if they would like to remember the device. If they affirm that they want to remember the device, generate an [UpdateDeviceStatus](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateDeviceStatus.html) API request with your user’s access token, device key, and `"DeviceRememberedStatus": "remembered"`.

1. If you have instructed Amazon Cognito to remember the device, the next time they sign in, instead of an MFA challenge, they’re presented with a `DEVICE_SRP_AUTH` challenge.

## Signing in with a device
<a name="user-pools-remembered-devices-signing-in-with-a-device"></a>

After you configure a user’s device to be remembered, Amazon Cognito no longer requires them to submit an MFA code when they sign in with the same device key. Device authentication only replaces the MFA-authentication challenge with a device-authentication challenge. You can’t sign users in with device authentication only. Your user must first complete authentication with their password or a custom challenge. The following is the authentication process for a user on a remembered device.

To perform device authentication in a flow that uses [Custom authentication challenge Lambda triggers](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html), pass a `DEVICE_KEY` parameter in your [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API request. After your user succeeds all challenges and the `CUSTOM_CHALLENGE` challenge returns an `issueTokens` value of `true`, Amazon Cognito returns one final `DEVICE_SRP_AUTH` challenge.

**To sign in with a device**

1. Retrieve your user’s device key from client storage.

1. Start your user’s sign-in session with an [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) API request. Choose an `AuthFlow` of `USER_SRP_AUTH`, `REFRESH_TOKEN_AUTH`, `USER_PASSWORD_AUTH`, or `CUSTOM_AUTH`. In `AuthParameters`, add your user’s device key to the `DEVICE_KEY` parameter, and include the other required parameters for your selected sign-in flow.

   1. You can also pass `DEVICE_KEY` in the parameters of a `PASSWORD_VERIFIER` response to an authentication challenge.

1. Complete challenge responses until you receive a `DEVICE_SRP_AUTH` challenge in the response.

1. In a [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) API request, send a `ChallengeName` of `DEVICE_SRP_AUTH` and parameters for `USERNAME`, `DEVICE_KEY`, and `SRP_A`.

1. Amazon Cognito responds with a `DEVICE_PASSWORD_VERIFIER` challenge. This challenge response includes values for `SECRET_BLOCK` and `SRP_B`.

1. With your SRP library, generate and submit `PASSWORD_CLAIM_SIGNATURE`, `PASSWORD_CLAIM_SECRET_BLOCK`, `TIMESTAMP`, `USERNAME`, and `DEVICE_KEY` parameters. Submit these in an additional `RespondToAuthChallenge` request.

1. Complete additional challenges until you receive the user’s JWTs.

The following pseudocode demonstrates how to calculate values for your `DEVICE_PASSWORD_VERIFIER` challenge response. For SRP authentication with a device, generate a *new* SRP secret for your user: a fresh high-entropy password `DeviceSecret`, a salt, and the associated password verifier. These values are distinct from the password, salt, and verifier used for the user's SRP authentication. They are only used for device authentication and are only stored on the device. Functions for generating the SRP secrets for users' devices are available in [SRP libraries](https://github.com/secure-remote-password/implementations) that are available in various SDKs.

```
PASSWORD_CLAIM_SECRET_BLOCK = SECRET_BLOCK
TIMESTAMP = "Tue May 7 00:09:40 UTC 2025"
k = SHA256(N || g) as a non-negative integer in big-endian
u = SHA256(SRP_A || SRP_B) as a non-negative integer in big-endian
x = SHA256(salt || SHA256(DeviceGroupKey || DeviceKey || ":" || DeviceSecret)) as a non-negative integer in big-endian
S_USER = (SRP_B - k * g^x)^(a + u * x) % N
K_USER = HKDF_HMAC_SHA256(salt=u, ikm=S_USER, info="Caldera Derived Key", length=16 bytes)
PASSWORD_CLAIM_SIGNATURE = Base64(HMAC_SHA256(key=K_USER, message=(DeviceGroupKey || DeviceKey || PASSWORD_CLAIM_SECRET_BLOCK || TIMESTAMP)))
```

## Viewing, updating and forgetting devices
<a name="user-pools-remembered-devices-viewing-updating-forgetting"></a>

You can implement the following features in your app with the Amazon Cognito API.

1. Display information about a user’s current device.

1. Display a list of all of your user’s devices.

1. Forget a device.

1. Update a device remembered state.

The access tokens that authorize the API requests in the following descriptions must include the `aws.cognito.signin.user.admin` scope. Amazon Cognito adds a claim for this scope to all access tokens that you generate with the Amazon Cognito user pools API. Third-party IdPs must separately manage devices and MFA for their users who authenticate to Amazon Cognito. In managed login, you can request the `aws.cognito.signin.user.admin` scope, but managed login automatically adds device information to advanced security user logs, and doesn't offer to remember devices.

**Display information about a device**  
You can query information about a user’s device to determine if it is still in current use. For example, you might want to deactivate remembered devices after they haven’t signed in for 90 days. 
+ To display your user’s device information in a public-client app, submit your user’s access key and device key in a [GetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetDevice.html) API request.
+ To display your user’s device information in a confidential-client app, sign an [AdminGetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetDevice.html) API request with AWS credentials and submit your user’s username, device key, and user pool.

**Display a list of all your user’s devices**  
You can display a list of all your user’s devices and their properties. For example, you might want to verify that the current device matches a remembered device. 
+ In a public-client app, submit your user’s access token in a [ListDevices](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html) API request.
+ In a confidential-client app, sign an [AdminListDevices](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListDevices.html) API request with AWS credentials and submit your user’s username and user pool.

**Forget a device**  
You can delete a user’s device key. You might want to do this when you determine that your user no longer uses a device, or when you detect unusual activity and want to prompt a user to complete MFA again. To register the device again later, you must generate and store a new device key.
+ In a public-client app, submit your user’s device key and access token in [ForgetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgetDevice.html) API request.
+ In a confidential-client app, submit your user’s device key and access token in [AdminForgetDevice](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminForgetDevice.html) API request.

# Using Amazon Pinpoint for user pool analytics
<a name="cognito-user-pools-pinpoint-integration"></a>

**Note**  
**End of support notice:** On October 30, 2026, AWS will end support for Amazon Pinpoint. After October 30, 2026, you will no longer be able to access the Amazon Pinpoint console or Amazon Pinpoint resources (endpoints, segments, campaigns, journeys, and analytics). For more information, see [Amazon Pinpoint end of support](https://docs.aws.amazon.com/console/pinpoint/migration-guide). **Note:** APIs related to SMS, voice, mobile push, OTP, and phone number validate are not impacted by this change and are supported by AWS End User Messaging.

Amazon Cognito user pools are integrated with Amazon Pinpoint to provide analytics for Amazon Cognito user pools and to enrich the user data for Amazon Pinpoint campaigns. Amazon Pinpoint provides analytics and targeted campaigns to drive user engagement in mobile apps using push notifications. With Amazon Pinpoint analytics support in Amazon Cognito user pools, you can track user pool sign-ups, sign-ins, failed authentications, daily active users (DAUs), and monthly active users (MAUs) in the Amazon Pinpoint console. You can drill into the data for different date ranges or attributes, such as device platform, device locale, and app version.

You can also set up custom attributes for your app. Those can then be used to segment your users on Amazon Pinpoint and send them targeted push notifications. If you choose **Share user attribute data with Amazon Pinpoint** in the **Analytics** configuration for your app client in the **App clients** menu in the Amazon Cognito console, Amazon Pinpoint creates additional endpoints for user email addresses and phone numbers.

When you activate Amazon Pinpoint analytics in your user pool with the Amazon Cognito console, you also create a [service-linked role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#service-linked-role-permissions) that Amazon Cognito assumes when it makes an API request to Amazon Pinpoint for your user pool. The IAM principal that adds your analytics configuration must have [CreateServiceLinkedRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceLinkedRole.html) permissions. The service-linked role is [AWSServiceRoleForAmazonCognitoIdp](https://console.aws.amazon.com/iamv2/home?region=us-east-1#/roles/details/AWSServiceRoleForAmazonCognitoIdp). For more information, see [Using service-linked roles for Amazon Cognito](using-service-linked-roles.md).

When you apply an `AnalyticsConfiguration` to your app client in the Amazon Cognito API, you can assign a custom IAM role for Amazon Pinpoint and an external ID to assume the role. The role must trust the `cognito-idp` service principal, and if the role trust policy requires an external ID, it must match your `AnalyticsConfiguration`. You must grant the role `cognito-idp:Describe*` permissions, and the following permissions for your **Amazon Pinpoint project**.
+ `mobiletargeting:UpdateEndpoint`
+ `mobiletargeting:PutEvents`

## Amazon Cognito and Amazon Pinpoint Region availability
<a name="cognito-user-pools-find-region-mappings"></a>

The following table shows the AWS Region mappings between Amazon Cognito and Amazon Pinpoint that meet one of the following conditions.
+ You can only use an Amazon Pinpoint project in the US East (N. Virginia) (us-east-1) Region.
+ You can use an Amazon Pinpoint project in the same Region *or* in the US East (N. Virginia) (us-east-1) Region

By default, Amazon Cognito can only send analytics to a Amazon Pinpoint project in the same AWS Region. The exceptions to this rule are the Regions in the following table, and Regions where Amazon Pinpoint in unavailable.

Amazon Pinpoint isn't available in the following Regions. Amazon Cognito user pools in these Regions don't support analytics.
+ Europe (Milan)
+ Middle East (Bahrain)
+ Asia Pacific (Osaka)
+ Israel (Tel Aviv)
+ Africa (Cape Town)
+ Asia Pacific (Jakarta)
+ Asia Pacific (Malaysia)

The table shows the relation between the Region where you built your Amazon Cognito user pool and the corresponding Region in Amazon Pinpoint. You must configure your Amazon Pinpoint project in an available Region to integrate it with Amazon Cognito.


| Amazon Cognito user pool Region | Region for Amazon Pinpoint project | 
| --- | --- | 
|  ap-northeast-1  |  us-east-1  | 
|  ap-northeast-2  |  us-east-1  | 
|  ap-south-1  |  us-east-1, ap-south-1  | 
|  ap-southeast-1  |  us-east-1  | 
|  ap-southeast-2  |  us-east-1, ap-southeast-2  | 
|  ca-central-1  |  us-east-1  | 
|  eu-central-1  |  us-east-1, eu-central-1  | 
|  eu-west-1  |  us-east-1, eu-west-1  | 
|  eu-west-2  |  us-east-1  | 
|  us-east-1  |  us-east-1  | 
|  us-east-2  |  us-east-1  | 
|  us-west-2  |  us-east-1, us-west-2  | 

**Region mapping examples**
+ If you create a user pool in ap-northeast-1, you can create your Amazon Pinpoint project in us-east-1.
+ If you create a user pool in ap-south-1, you can create your Amazon Pinpoint project in either us-east-1 or ap-south-1.

**Note**  
For all AWS Regions except those in the preceding table, Amazon Cognito can only use an Amazon Pinpoint project in the same Region as your user pool. If Amazon Pinpoint isn't available in the Region where you built your user pool, and it's not listed in the table, then Amazon Cognito doesn't support Amazon Pinpoint analytics in that Region. For detailed AWS Region information, see [Amazon Pinpoint endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/pinpoint.html).

### Specifying Amazon Pinpoint analytics settings (AWS Management Console)
<a name="cognito-user-pools-pinpoint-integration-console"></a>

You can configure your Amazon Cognito user pool to send analytics data to Amazon Pinpoint. Amazon Cognito only sends analytics data to Amazon Pinpoint for local users. After you configure your user pool to associate with a Amazon Pinpoint project, you must include `AnalyticsMetadata` in your API requests. For more information, see [Integrating your app with Amazon Pinpoint](#cognito-user-pools-pinpoint-integration-client).

**To specify analytics settings**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). You might be prompted for your AWS credentials.

1. Select **User Pools** and choose an existing user pool from the list.

1. Choose the **App clients** menu and select the app client that you want to update.

1. In the **Analytics** tab under **Pinpoint analytics**, choose **Enable**.

1. Choose a **Pinpoint Region**.

1. Choose an **Amazon Pinpoint project** or select **Create Amazon Pinpoint project**.
**Note**  
The Amazon Pinpoint project ID is a 32-character string that is unique to your Amazon Pinpoint project. It is listed in the Amazon Pinpoint console.  
You can map multiple Amazon Cognito apps to a single Amazon Pinpoint project. However, each Amazon Cognito app can only be mapped to one Amazon Pinpoint project.  
In Amazon Pinpoint, each project should be a single app. For example, if a game developer has two games, each game should be a separate Amazon Pinpoint project, even if both games use the same Amazon Cognito user pool. For more information on Amazon Pinpoint projects, see [Create a project in Amazon Pinpoint](https://docs.aws.amazon.com/push-notifications/latest/userguide/mobile-push.html#mobile-push-create-project). 

1. Under **User data sharing**, choose **Share user data with Amazon Pinpoint** if you want Amazon Cognito to send email addresses and phone numbers to Amazon Pinpoint and create additional endpoints for users. After your users verify their email address and phone number, Amazon Cognito only shares them with Amazon Pinpoint if they are available to the user account.
**Note**  
An *endpoint* uniquely identifies a user device to which you can send push notifications with Amazon Pinpoint. For more information about endpoints, see [Adding endpoints](https://docs.aws.amazon.com/pinpoint/latest/developerguide/endpoints.html) in the *Amazon Pinpoint Developer Guide*.

1. Choose **Save changes**.

### Specifying Amazon Pinpoint analytics settings (AWS CLI and AWS API)
<a name="cognito-user-pools-pinpoint-integration-cli-api"></a>

Use the following commands to specify Amazon Pinpoint analytics settings for your user pool.

**To specify the analytics settings for your user pool's existing client app at app creation time**
+ AWS CLI: `aws cognito-idp create-user-pool-client`
+ AWS API: [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html)

**To update the analytics settings for your user pool's existing client app**
+ AWS CLI: `aws cognito-idp update-user-pool-client`
+ AWS API: [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html)

**Note**  
Amazon Cognito supports in-Region integrations when you use `ApplicationArn`

## Integrating your app with Amazon Pinpoint
<a name="cognito-user-pools-pinpoint-integration-client"></a>

You can publish analytics metadata to Amazon Pinpoint for Amazon Cognito *local users* in the *user pools API*.

**Local users**  
Users who signed up for an account or were created in your user pool instead of signing in through a third-party identity provider (IdP).

**User pools API**  
The operations that you can integrate with an AWS SDK, using an app with a custom user interface (UI). You can't pass analytics metadata for federated or local users who sign in through managed login. See the [Amazon Cognito API Reference](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html) for a list of user pools API operations.

After you configure your user pool to publish to a campaign, Amazon Cognito passes metadata to Amazon Pinpoint for the following API operations.
+ `AdminInitiateAuth`
+ `AdminRespondToAuthChallenge`
+ `ConfirmForgotPassword`
+ `ConfirmSignUp`
+ `ForgotPassword`
+ `InitiateAuth`
+ `ResendConfirmationCode`
+ `RespondToAuthChallenge`
+ `SignUp`

To pass metadata about your user's session to your Amazon Pinpoint campaign, include an `AnalyticsEndpointId` value in the `AnalyticsMetadata` parameter of your API request. For a JavaScript example, see [Why aren't my Amazon Cognito user pool analytics appearing on my Amazon Pinpoint dashboard?](https://aws.amazon.com/premiumsupport/knowledge-center/pinpoint-cognito-user-pool-analytics/) in the *AWS Knowledge Center*.

# Email settings for Amazon Cognito user pools
<a name="user-pool-email"></a>

Certain events in your application can cause Amazon Cognito to email your users. For example, if you configure your user pool to require email verification, Amazon Cognito sends an email when a user signs up for a new account in your app or resets their password. Depending on the action that initiates the email, the email contains a verification code or a temporary password.

To handle email delivery, you can use either of the following options:
+ [The default email configuration](#user-pool-email-default) that is built into the Amazon Cognito service.
+ [Your Amazon Simple Email Service (Amazon SES) configuration](#user-pool-email-developer).

You can change your delivery option after you create your user pool.

Amazon Cognito sends email messages to your users with either a code that they can enter or a URL link that they can select. The following table shows the events that can generate an email message.

**Message options**


| Activity | API operation | Delivery options | Format options | Customizable | [Message template](cognito-user-pool-settings-message-customizations.md) | 
| --- |--- |--- |--- |--- |--- |
| Forgot password | [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html), [AdminResetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html) | Email, SMS | code | Yes | Verification message | 
| Invitation | [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) | Email, SMS | code | Yes | Invitation message | 
| Self-registration | [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html), [ResendConfirmationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html) | Email, SMS | code, link | Yes | Verification message | 
| Email address or phone number verification | [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html), [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html), [GetUserAttributeVerificationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html) | Email, SMS | code | Yes | Verification message | 
| Multi-factor authentication (MFA) | [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html), [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) | Email¹, SMS, authenticator app | code | Yes² | MFA message | 
| One-time password authentication (OTP) | [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html), [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) | Email¹, SMS | code | Yes | MFA message³ | 

¹ Requires Essentials [feature plan](cognito-sign-in-feature-plans.md) or higher and [Amazon SES email configuration](#user-pool-email-developer). 

² For SMS and email messages.

³ You can only customize the MFA message template when MFA is required or optional in your user pool. When MFA is inactive, Amazon Cognito sends one-time passwords with the default template.

Amazon SES charges for email messages. For more information, see [Amazon SES pricing](https://aws.amazon.com/ses/pricing/).

To learn more about email MFA, see [SMS and email message MFA](user-pool-settings-mfa-sms-email-message.md).

Amazon Cognito might prevent delivery of additional email or SMS messages to a single destination in a short time period. If you believe your user pool is affected, configure and review [logs for message delivery errors](exporting-quotas-and-usage.md#exporting-quotas-and-usage-messages) and then contact your account team.

## Default email configuration
<a name="user-pool-email-default"></a>

Amazon Cognito can use its default email configuration to handle email deliveries for you. When you use the default option, Amazon Cognito limits the number of emails it sends each day for your user pool. For information on service limits, see [Quotas in Amazon Cognito](quotas.md). For typical production environments, the default email limit is below the required delivery volume. To enable a higher delivery volume, you can use your Amazon SES email configuration.

When you use the default configuration, you use Amazon SES resources that are managed by AWS to send email messages. Amazon SES adds email addresses that return a [hard bounce](https://docs.aws.amazon.com/ses/latest/dg/send-email-concepts-deliverability.html#send-email-concepts-deliverability-bounce) to an [account-level suppression list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html) or a [global suppression list](https://docs.aws.amazon.com/ses/latest/dg/send-email-concepts-deliverability.html#send-email-concepts-deliverability-suppression-list). If an undeliverable email address becomes deliverable later, you can't control its removal from the suppression list while your user pool is configured to use the default configuration. An email address can remain on the AWS-managed suppression list indefinitely. To manage undeliverable email addresses, use your Amazon SES email configuration with an account-level suppression list, as described in the next section.

When you use the default email configuration, you can use either of the following email addresses as the FROM address:
+ The default email address, *no-reply@verificationemail.com*.
+ A custom email address. Before you can use your own email address, you must verify it with Amazon SES and grant Amazon Cognito permission to use this address.

## Amazon SES email configuration
<a name="user-pool-email-developer"></a>

Your application might require a higher delivery volume than what is available with the default option. To increase the possible delivery volume, use your Amazon SES resources with your user pool to email your users. You can also [monitor your email sending activity](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html) when you send email messages with your own Amazon SES configuration.

Before you can use your Amazon SES configuration, you must verify one or more email addresses, or a domain, with Amazon SES. Use a verified email address, or an address from a verified domain, as the FROM email address that you assign to your user pool. When Amazon Cognito sends email to a user, it calls Amazon SES for you and uses your email address.

When you use your Amazon SES configuration, the following conditions apply:
+ The email delivery limits for your user pool are the same limits that apply to your Amazon SES verified email address in your AWS account.
+ You can manage your messages to undeliverable email addresses with an account-level suppression list in Amazon SES that overrides the [global suppression list](https://docs.aws.amazon.com/ses/latest/dg/send-email-concepts-deliverability.html#send-email-concepts-deliverability-suppression-list). When you use an account-level suppression list, email message bounces affect the reputation of your account as a sender. For more information, see [Using the Amazon SES account-level suppression list](https://docs.aws.amazon.com/ses/latest/dg/sending-email-suppression-list.html) in the Amazon Simple Email Service Developer Guide.

### Amazon SES email configuration Regions
<a name="user-pool-email-developer-region-mapping"></a>

The AWS Region where you create a user pool will have one of three requirements for the configuration of email messages with Amazon SES. You might send email messages from Amazon SES in the same Region as your user pool, several Regions including the same Region, or one or more remote Regions. For best performance, send email messages with a Amazon SES verified identity in the same Region as your user pool when you have the option.Categories of Region requirements for Amazon SES verified identities

**In-Region only**  
Your user pools can send email messages with verified identities in the same AWS Region as the user pool. In the default email configuration without a custom `FROM` email address, Amazon Cognito uses a `no-reply@verificationemail.com` verified identity in the same Region.

**Backwards compatible**  
Your user pools can send email messages with verified identities in the same AWS Region or in one of the following alternate Regions:   
+ US East (N. Virginia)
+ US West (Oregon)
+ Europe (Ireland)
This feature supports continuity for user pool resources that you might have created to match Amazon Cognito requirements when the service launched. User pools from that period could only send email messages with verified identities in a limited number of AWS Regions. In the default email configuration without a custom `FROM` email address, Amazon Cognito uses a `no-reply@verificationemail.com` verified identity in the same Region.

**Alternate Region**  
Your user pools can send email messages with verified identities in an alternate AWS Region that is outside of the user pool Region. This configuration occurs when Amazon SES isn't available in a Region where Amazon Cognito is available.  
The Amazon SES sending authorization policy for your verified identity in the alternate Region must trust the Amazon Cognito service principal of the originating Region. For more information, see [To grant permissions to use the default email configuration](#user-pool-email-permissions-default).  
In some of these Regions, Amazon Cognito splits email messages between two alternate Regions for the default email configuration of `COGNITO_DEFAULT`. In these cases, to use a custom `FROM` email address, the Amazon SES sending authorization policy for your verified identity in each alternate Region must trust the Amazon Cognito service principal of the originating Region. For more information, see [To grant permissions to use the default email configuration](#user-pool-email-permissions-default). With the Amazon SES email configuration of `DEVELOPER` in these Regions, you must use a verified identity in the *first* listed Region and configure it to trust the Amazon Cognito service principal in the user pool Region. For example, in a user pool in Middle East (UAE), configure a verified identity in Europe (Frankfurt) to trust `cognito-idp.me-central-1.amazonaws.com`. In the default email configuration without a custom `FROM` email address, Amazon Cognito uses a `no-reply@verificationemail.com` verified identity in each Region.

**Note**  
Under the following combination of conditions, you must specify the `SourceArn` parameter of [EmailConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-EmailConfiguration) with a wildcard in the Region element, in the format `arn:${Partition}:ses:*:${Account}:identity/${IdentityName}`. This permits your user pool to send email messages with identical verified identities in your AWS account in both AWS Regions.  
Your EmailSendingAccount is `COGNITO_DEFAULT`.
You want to use a custom `FROM` address.
Your user pool sends emails in an **Alternate Region**.
Your user pool has a *second*[1](#cognito-email-alternate-regions-note) **Alternate Region** specified in the table of **Amazon SES supported Regions** that follows.

If you create a user pool programmatically–with an AWS SDK, the Amazon Cognito API or CLI, the AWS CDK, or AWS CloudFormation–your user pool sends email messages with the Amazon SES identity that the `SourceArn` parameter of [EmailConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-EmailConfiguration) specifies for your user pool. The Amazon SES identity must occupy a supported AWS Region. If your `EmailSendingAccount` is `COGNITO_DEFAULT` and you don't specify a `SourceArn` parameter, Amazon Cognito sends email messages from `no-reply@verificationemail.com` using resources in the Region where you created your user pool.

The following table shows the AWS Regions where you can use Amazon SES identities with Amazon Cognito.


| User pool Region | Region option | Amazon SES supported Regions | 
| --- | --- | --- | 
|  US East (N. Virginia)  |  Backwards compatible  |  US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  US East (Ohio)  |  Backwards compatible  |  US East (Ohio), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  US West (N. California)  |  In-Region only  |  US West (N. California)  | 
|  US West (Oregon)  |  Backwards compatible  |  US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Canada (Central)  |  Backwards compatible  |  Canada (Central), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Canada West (Calgary)  |  Alternate Region  |  Canada (Central), US West (N. California)[1](#cognito-email-alternate-regions-note)  | 
|  Mexico (Central)  |  Alternate Region  |  US East (N. Virginia), US West (Oregon)[1](#cognito-email-alternate-regions-note)  | 
|  Asia Pacific (Tokyo)  |  Backwards compatible  |  Asia Pacific (Tokyo), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Asia Pacific (Hong Kong)  |  Alternate Region  |  Asia Pacific (Singapore), Asia Pacific (Tokyo)[1](#cognito-email-alternate-regions-note)  | 
|  Asia Pacific (Seoul)  |  Backwards compatible  |  Asia Pacific (Seoul), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
| Asia Pacific (Malaysia) | Alternate Region | Asia Pacific (Sydney), Asia Pacific (Singapore)[1](#cognito-email-alternate-regions-note) | 
| Asia Pacific (Thailand) | Alternate Region | Asia Pacific (Singapore), Asia Pacific (Mumbai)[1](#cognito-email-alternate-regions-note) | 
|  Asia Pacific (Mumbai)  |  Backwards compatible  |  Asia Pacific (Mumbai), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Asia Pacific (Hyderabad)  |  Alternate Region  |  Asia Pacific (Mumbai), Asia Pacific (Singapore)[1](#cognito-email-alternate-regions-note)  | 
|  Asia Pacific (Singapore)  |  Backwards compatible  |  Asia Pacific (Singapore), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Asia Pacific (Sydney)  |  Backwards compatible  |  Asia Pacific (Sydney), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Asia Pacific (Osaka)  |  In-Region only  |  Asia Pacific (Osaka)  | 
|  Asia Pacific (Jakarta)  |  In-Region only  |  Asia Pacific (Jakarta)  | 
|  Asia Pacific (Melbourne)  |  Alternate Region  |  Asia Pacific (Sydney), Asia Pacific (Singapore)[1](#cognito-email-alternate-regions-note)  | 
|  Europe (Ireland)  |  Backwards compatible  |  US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Europe (London)  |  Backwards compatible  |  Europe (London), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Europe (Paris)  |  In-Region only  |  Europe (Paris)  | 
|  Europe (Frankfurt)  |  Backwards compatible  |  Europe (Frankfurt), US East (N. Virginia), US West (Oregon), Europe (Ireland)  | 
|  Europe (Zurich)  |  Alternate Region  |  Europe (Frankfurt), Europe (London)[1](#cognito-email-alternate-regions-note)  | 
|  Europe (Stockholm)  |  In-Region only  |  Europe (Stockholm)  | 
| Europe (Milan) |  In-Region only  | Europe (Milan) | 
| Europe (Spain) |  Alternate Region  | Europe (Paris), Europe (Stockholm)[1](#cognito-email-alternate-regions-note) | 
|  Middle East (Bahrain)  |  In-Region only  |  Middle East (Bahrain)  | 
|  Middle East (UAE)  |  Alternate Region  |  Europe (Frankfurt), Europe (London)[1](#cognito-email-alternate-regions-note)  | 
|  South America (São Paulo)  |  In-Region only  |  South America (São Paulo)  | 
|  Israel (Tel Aviv)  |  In-Region only  |  Israel (Tel Aviv)  | 
|  Africa (Cape Town)  |  In-Region only  |  Africa (Cape Town)  | 

 1 Used in user pools with the default email configuration. Amazon Cognito distributes email messages among verified identities with the same email address in each Region. To use a custom `FROM` address, configure `EmailConfiguration` with a `SourceArn` parameter in the format `arn:${Partition}:ses:*:${Account}:identity/${IdentityName}`.

## Configuring email for your user pool
<a name="user-pool-email-configure"></a>

Complete the following steps to configure the email settings for your user pool. Depending on the settings that you use, you might need IAM permissions in Amazon SES, AWS Identity and Access Management (IAM), and Amazon Cognito.

**Note**  
You can't share the resources that you create in these steps across AWS accounts. For example, you can't configure a user pool in one account, and then use it with an Amazon SES email address in a different account. If you use Amazon Cognito in multiple accounts, repeat these steps for each account.

### Step 1: Verify your email address or domain with Amazon SES
<a name="user-pool-email-configure-verify-ses"></a>

Before you configure your user pool, you must verify one or more domains or email addresses with Amazon SES if you want to do either of the following:
+ Use your own email address as the FROM address
+ Use your Amazon SES configuration to handle email delivery

By verifying your email address or domain, you confirm that you own it, which helps prevent unauthorized use.

For information on verifying an email address with Amazon SES, see [Verifying an Email Address](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-email-addresses-procedure.html) in the *Amazon Simple Email Service Developer Guide*. For information on verifying a domain with Amazon SES, see [Verifying domains](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-domains.html).

### Step 2: Move your account out of the Amazon SES sandbox
<a name="user-pool-email-configure-sandbox"></a>

Omit this step if you are using the default Amazon Cognito email configuration.

When you first use Amazon SES in any AWS Region, it places your AWS account in the Amazon SES sandbox for that Region. Amazon SES uses the sandbox to prevent fraud and abuse. If you use your Amazon SES configuration to handle email delivery, you must move your AWS account out of the sandbox before Amazon Cognito can email your users.

In the sandbox, Amazon SES imposes restrictions on how many emails you can send and where you can send them. You can send emails only to addresses and domains that you have verified with Amazon SES, or you can send them to Amazon SES mailbox simulator addresses. While your AWS account remains in the sandbox, don't use your Amazon SES configuration for applications that are in production. In this situation, Amazon Cognito can't send messages to your users' email addresses.

To remove your AWS account from the sandbox, see [Moving out of the Amazon SES sandbox](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/request-production-access.html) in the *Amazon Simple Email Service Developer Guide.*

### Step 3: Grant email permissions to Amazon Cognito
<a name="user-pool-email-permissions"></a>

You might need to grant specific permissions to Amazon Cognito before it can email your users. The permissions that you grant, and the process that you use to grant them, depend on whether you are using the default email configuration, or your Amazon SES configuration.

#### To grant permissions to use the default email configuration
<a name="user-pool-email-permissions-default"></a>

Complete this step only if you configure your user pool to **Send email with Cognito** or set `EmailSendingAccount` to `COGNITO_DEFAULT`.

With the default email configuration, your user pool can send email messages with either of the following addresses.
+ The default address `no-reply@verificationemail.com`.
+ A custom FROM address from your verified email addresses or domains in Amazon SES.

If you use a custom address, Amazon Cognito needs additional permissions to email users from that address. These permissions are granted by a [sending authorization policy](https://docs.aws.amazon.com/ses/latest/dg/sending-authorization.html) for the address or domain in Amazon SES. If you use the Amazon Cognito console to add a custom address to your user pool, the policy is automatically attached to the Amazon SES verified email address. However, if you configure your user pool outside of the console, such as using the AWS CLI or the Amazon Cognito API, you must attach the policy using the [Amazon SES console](https://console.aws.amazon.com/ses/) or the [PutIdentityPolicy](https://docs.aws.amazon.com/ses/latest/APIReference/API_PutIdentityPolicy.html) API.

**Note**  
You can only configure a FROM address in a verified domain using the AWS CLI or the Amazon Cognito API.

A sending authorization policy allows or denies access based on the account resources that are using Amazon Cognito to invoke Amazon SES. For more information about resource-based policies, see the [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_resource-based). You can also find example resource-based policies in the [Amazon SES Developer Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policy-examples.html).

**Example Sending authorization policy**  
The following example sending authorization policy grants Amazon Cognito a limited ability to use an Amazon SES verified identity. Amazon Cognito can only send email messages when it does so on behalf of both the user pool in the `aws:SourceArn` condition and the account in the `aws:SourceAccount` condition.  
Your sending authorization policy in the user pool Region or alternate Region must permit the Amazon Cognito service principal to send email messages. Refer to the [Regions table](#ses-regions-table) for more information. If your **User pool Region** matches at least one value in **Amazon SES Region**, configure your sending authorization policy with the global service principal in the following example.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "stmnt1234567891234",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "email.cognito-idp.amazonaws.com"
                ]
            },
            "Action": [
                "SES:SendEmail",
                "SES:SendRawEmail"
            ],
            "Resource": "arn:aws:ses:us-east-1:111122223333:identity/support@example.com",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                },
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_EXAMPLE"
                }
            }
        }
    ]
}
```
Amazon SES isn't available in all opt-in AWS Regions where Amazon Cognito is available. Middle East (UAE) is an example, and can only send emails with verified identities in Europe (Frankfurt) (`eu-central-1`). In user pools with the default email configuration, Amazon Cognito also sends email messages with a verified identity in each of two Regions. In the case of Middle East (UAE), the additional Region is Europe (London). You must update the sending authorization policy in both Regions.  
Your sending authorization policy in each of the alternate Regions must permit the Amazon Cognito service principal in the user pool opt-in Region to send email messages. Refer to the [Regions table](#ses-regions-table) for more information. If your Region is marked as **Alternate Region**, configure your sending authorization policies with the Regional service principal as in the following example. Replace the example Region identifier *me-central-1* with the required Region ID as needed.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "cognito-idp.me-central-1.amazonaws.com"
                ]
            },
            "Action": [
                "SES:SendEmail",
                "SES:SendRawEmail"
            ],
            "Resource": "arn:aws:ses:us-east-1:111122223333:identity/support@example.com",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                },
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_EXAMPLE"
                }
            }
        }
    ]
}
```
For more information about policy syntax, see [Amazon SES sending authorization policies](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html) in the *Amazon Simple Email Service Developer Guide*.  
For more examples, see [Amazon SES sending authorization policy examples](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policy-examples.html) in the *Amazon Simple Email Service Developer Guide*.

#### To grant permissions to use your Amazon SES configuration
<a name="user-pool-email-permissions-developer"></a>

If you configure your user pool to use your Amazon SES configuration, Amazon Cognito needs additional permissions to call Amazon SES on your behalf when it emails your users. This authorization is granted with the IAM service.

When you configure your user pool with this option, Amazon Cognito creates a *service-linked role*, which is a type of IAM role, in your AWS account. This role contains the permissions that allow Amazon Cognito to access Amazon SES and send email with your address.

Amazon Cognito creates your service-linked role with the AWS credentials of the user session that sets the configuration. The IAM permissions of this session must include the `iam:CreateServiceLinkedRole` action. For more information about permissions in IAM, see [Access management for AWS resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) in the *IAM User Guide*.

For more information about the service-linked role that Amazon Cognito creates, see [Using service-linked roles for Amazon Cognito](using-service-linked-roles.md).

### Step 4: Configure your user pool
<a name="user-pool-email-configure-user-pool"></a>

Complete the following steps if you want to configure your user pool with any of the following:
+ A custom FROM address that appears as the email sender
+ A custom REPLY-TO address that receives the messages that your users send to your FROM address
+ Your Amazon SES configuration

**Note**  
If your verified identity is an email address, Amazon Cognito sets that email address as the FROM and REPLY-TO email address by default. But, if your verified identity is a domain, you must provide a value for the FROM email address.

Omit this procedure if you want to use the default Amazon Cognito email configuration and address.

**To configure your user pool to use a custom email address**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Authentication methods** menu, locate **Email configuration**, choose **Edit**.

1. On the **Edit email configuration** page, select **Send email from Amazon SES** or **Send email with Amazon Cognito**. You can customize the **SES Region**, **Configuration Set**, and **FROM sender name** only when you choose **Send email from Amazon SES**.

1. To use a custom FROM address, complete the following steps:

   1. Under **SES Region**, choose the Region that contains your verified email address.

   1. Under **FROM email address**, choose your email address. Use an email address that you have verified with Amazon SES.

   1. (Optional) Under **Configuration set**, choose a configuration set for Amazon SES to use. Making and saving this change creates a service-linked role.

   1. (Optional) Under **FROM sender address**, enter an email address. You can provide only an email address, or an email address and a friendly name in the format `Jane Doe <janedoe@example.com>`.

   1. (Optional) Under **REPLY-TO email address**, enter the email address where you want to receive messages that your users send to your FROM address.

1. Choose **Save changes**.

**Related Topics**
+ [Customizing email verification messages](cognito-user-pool-settings-message-customizations.md#cognito-user-pool-settings-email-verification-message-customization)
+ [Customizing user invitation messages](cognito-user-pool-settings-message-customizations.md#cognito-user-pool-settings-user-invitation-message-customization)

# SMS message settings for Amazon Cognito user pools
<a name="user-pool-sms-settings"></a>

Some Amazon Cognito events for your user pool might cause Amazon Cognito to send SMS text messages to your users. For example, if you configure your user pool to require phone verification, Amazon Cognito sends an SMS text message when a user signs up for a new account in your app or resets their password. Depending on the action that initiates the SMS text message, the message contains a verification code, a temporary password, or a welcome message.

Amazon Cognito uses Amazon Simple Notification Service (Amazon SNS) for delivery of SMS text messages. Amazon SNS in turn hands off SMS messages to AWS End User Messaging SMS. If you are sending a text message through Amazon Cognito for the first time, AWS End User Messaging SMS places you in a [sandbox environment](https://docs.aws.amazon.com/sms-voice/latest/userguide/sandbox.html). In the sandbox environment, you can test your applications for SMS text messages. In the sandbox, you can only simulate the sending of messages.

**Note**  
In November 2024, AWS replaced Amazon SNS SMS messaging with AWS End User Messaging SMS. Currently, The Amazon Cognito console refers to Amazon SNS resources. User pools initiate SMS messages with the Amazon SNS [Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) operation, which is a pass-through to AWS End User Messaging SMS. Accordingly, you must still configure permissions for `sns:Publish`, not `sms-voice:SendTextMessage`.

AWS End User Messaging SMS charges for SMS text messages. For more information, see [AWS End User Messaging SMS pricing](https://aws.amazon.com/end-user-messaging/pricing/).

Amazon Cognito sends SMS messages to your users with a code that they can enter. The following table shows the events that can generate an SMS message.

**Message options**


| Activity | API operation | Delivery options | Format options | Customizable | [Message template](cognito-user-pool-settings-message-customizations.md) | 
| --- |--- |--- |--- |--- |--- |
| Forgot password | [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html), [AdminResetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html) | Email, SMS | code | Yes | Verification message | 
| Invitation | [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) | Email, SMS | code | Yes | Invitation message | 
| Self-registration | [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html), [ResendConfirmationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html) | Email, SMS | code, link | Yes | Verification message | 
| Email address or phone number verification | [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html), [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html), [GetUserAttributeVerificationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html) | Email, SMS | code | Yes | Verification message | 
| Multi-factor authentication (MFA) | [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html), [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) | Email¹, SMS, authenticator app | code | Yes² | MFA message | 
| One-time password authentication (OTP) | [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html), [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) | Email¹, SMS | code | Yes | MFA message³ | 

¹ Requires Essentials [feature plan](cognito-sign-in-feature-plans.md) or higher and [Amazon SES email configuration](user-pool-email.md#user-pool-email-developer). 

² For SMS and email messages.

³ You can only customize the MFA message template when MFA is required or optional in your user pool. When MFA is inactive, Amazon Cognito sends one-time passwords with the default template.

AWS End User Messaging SMS charges for SMS messages. For more information, see [AWS End User Messaging SMS pricing](https://aws.amazon.com/end-user-messaging/pricing/).

To learn more about MFA, see [SMS and email message MFA](user-pool-settings-mfa-sms-email-message.md).

Amazon Cognito might prevent delivery of additional email or SMS messages to a single destination in a short time period. If you believe your user pool is affected, configure and review [logs for message delivery errors](exporting-quotas-and-usage.md#exporting-quotas-and-usage-messages) and then contact your account team.

## Best practices
<a name="user-pool-sms-settings-best-practices"></a>

Because of the volume of unsolicited SMS traffic worldwide, some governments impose barriers between the senders and recipients of SMS messages. When you use SMS messages for MFA and user updates, you must take additional steps to ensure that your messages are delivered. You must also monitor SMS-message-related regulations in countries where your users might live and keep your SMS message configuration current. For more information, see [SMS and MMS country capabilities and limitations](https://docs.aws.amazon.com/sms-voice/latest/userguide/phone-numbers-sms-support-by-country.html) in the *AWS End User Messaging SMS User Guide*.

The use of SMS messages to authenticate and verify users isn't a security best practice. Phone numbers can change owners, and might not reliably represent a *something you have* factor of MFA for your users. Instead, implement TOTP MFA in your app or with your third-party IdP. You can also create additional custom authentication factors with [Custom authentication challenge Lambda triggers](user-pool-lambda-challenge.md).

Review the following links for information about securing your SMS message delivery architecture.
+ [Reduce risks of user sign-up fraud and SMS pumping with Amazon Cognito user pools](https://aws.amazon.com/blogs/security/reduce-risks-of-user-sign-up-fraud-and-sms-pumping-with-amazon-cognito-user-pools/)
+ [Defending Against SMS Pumping: New AWS Features to Help Combat Artificially Inflated Traffic](https://aws.amazon.com/blogs/messaging-and-targeting/defending-against-sms-pumping-new-aws-features-to-help-combat-artificially-inflated-traffic/)

## Setting up SMS messaging for the first time in Amazon Cognito user pools
<a name="user-pool-sms-settings-first-time"></a>

Amazon Cognito uses Amazon SNS, and indirectly AWS End User Messaging SMS, to send SMS messages from your user pools. You can also use a [Custom SMS sender Lambda trigger](user-pool-lambda-custom-sms-sender.md) to use your own resources to send SMS messages. The first time that you set up SMS text messages in a particular AWS Region, AWS End User Messaging SMS places your AWS account in the SMS sandbox for that Region. AWS End User Messaging SMS uses the sandbox to prevent fraud and abuse and to meet compliance requirements. When your AWS account is in the sandbox, AWS End User Messaging SMS imposes some [restrictions](https://docs.aws.amazon.com/sms-voice/latest/userguide/sandbox.html#sandbox-sms). For example, you can send text messages to a maximum of 10 verified destination numbers if you have an origination identity, or you can simulate sending messages without an origination identity. While your AWS account remains in the sandbox, do not send SMS messages in production. When you're in the sandbox, Amazon Cognito can't send messages to your users' phone numbers.

**Topics**
+ [

### Prepare an IAM role that Amazon Cognito can use to send SMS messages with AWS End User Messaging SMS
](#sms-create-a-role)
+ [

### Choose the AWS Region for SMS messages
](#sms-choose-a-region)
+ [

### Obtain an origination identity to send SMS messages to US phone numbers
](#user-pool-sms-settings-first-time-origination)
+ [

### Confirm that you are in the SMS sandbox
](#user-pool-sms-settings-first-time-confirm-sandbox)
+ [

### Move your account out of the sandbox
](#user-pool-sms-settings-first-time-out-sandbox)
+ [

### Use simulator numbers or verified phone numbers with AWS End User Messaging SMS
](#user-pool-sms-settings-first-time-verify-numbers)
+ [

### Complete user pool setup in Amazon Cognito
](#user-pool-sms-settings-first-time-finish-user-pool)

### Prepare an IAM role that Amazon Cognito can use to send SMS messages with AWS End User Messaging SMS
<a name="sms-create-a-role"></a>

When you send an SMS message from your user pool, Amazon Cognito assumes an IAM role in your account. Amazon Cognito uses the `sns:Publish` permission assigned to that role to send SMS messages to your users. In the Amazon Cognito console, you can set an **IAM role selection** from the **Authentication methods** menu of your user pool, under **SMS** or make this selection during the user pool creation wizard.

The following example IAM role trust policy grants Amazon Cognito user pools a limited ability to assume the role. Amazon Cognito can only assume the role when it meets the following conditions:
+ The assume-role operation is on behalf of the user pool in the `aws:SourceArn` condition.
+ The assume-role operation is on behalf of a user pool in the AWS account set by the `aws:SourceAccount` condition.
+ The assume-role operation includes the external ID in the `sts:externalId` condition.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "cognito-idp.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "StringEquals": {
                    "sts:ExternalId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
                    "aws:SourceAccount": "111122223333"
                },
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:cognito-idp:us-west-2:111122223333:userpool/us-west-2_EXAMPLE"
                }
            }
        }
    ]
}
```

------

You can specify an exact [user pool ARN](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncognitouserpools.html#amazoncognitouserpools-resources-for-iam-policies) or a wildcard ARN in the value of the `aws:SourceArn` condition. Look up the ARNs of your user pools in the AWS Management Console or with a [DescribeUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPool.html) API request.

To send SMS messages for [multi-factor authentication](user-pool-settings-mfa-sms-email-message.md), your IAM role trust policy must have an `sts:ExternalId` condition. The value of this condition must match the `ExternalId` property of the [SmsConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-SmsConfiguration) of your user pool. When you create an IAM role during the process of user pool creation in the Amazon Cognito console, Amazon Cognito configures the external ID for you in the role and in the user pool settings. This isn't true when you use an existing IAM role.

You must update the user pool `ExternalId` parameter in an [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request and update the IAM role trust policy with an `sts:externalId` condition with the same value. To learn how to use the API to update a user pool in a way that preserves the original configuration, see [Updating user pool and app client configuration](cognito-user-pool-updating.md).

For more information about IAM roles and trust policies, see [Roles terms and concepts](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html) in the *AWS Identity and Access Management User Guide*.

### Choose the AWS Region for SMS messages
<a name="sms-choose-a-region"></a>

**Note**  
SMS messages in AWS are now managed in [AWS End User Messaging SMS](https://console.aws.amazon.com/sms-voice/home).

In some AWS Regions, you can choose the Region that contains the Amazon SNS resources that you want to use for Amazon Cognito SMS messages. In any AWS Region where Amazon Cognito is available, except for Asia Pacific (Seoul), you can use Amazon SNS resources in the AWS Region where you created your user pool. To make your SMS messaging faster and more reliable when you have a choice of Regions, use Amazon SNS resources in the same Region as your user pool.

Choose a Region for SMS resources in the **Configure message delivery** step of the new user pool wizard. You can also choose **Edit** under **SMS** in the **Authentication methods** menu of an existing user pool.

At launch, for some AWS Regions, Amazon Cognito sent SMS messages with Amazon SNS resources in an alternate Region. To set your preferred Region, use the `SnsRegion` parameter of the [SmsConfigurationType](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SmsConfigurationType.html) object for your user pool. When you programmatically create an Amazon Cognito user pools resource in an **Amazon Cognito Region** from the following table and you do not provide an `SnsRegion` parameter, your user pool can send SMS messages with Amazon SNS resources in a legacy **Amazon SNS Region**.

Amazon Cognito user pools in the Asia Pacific (Seoul) AWS Region must use your Amazon SNS configuration in the Asia Pacific (Tokyo) Region.

Amazon SNS (via AWS End User Messaging SMS) sets the spending quota for all new accounts at \$11.00 (USD) per month. You might have increased your spend limit in an AWS Region that you use with Amazon Cognito. Before you change the AWS Region for Amazon SNS SMS messages, open a quota increase case in the AWS Support Center to increase your limit in the new Region. For more information, see [Moving from the AWS End User Messaging SMS MMS and Voice sandbox to production](https://docs.aws.amazon.com/sms-voice/latest/userguide/sandbox.html#sandbox-sms-move-to-production) in the *AWS End User Messaging SMS User Guide*.

You can send SMS messages for any **Amazon Cognito Region** in the following table with AWS End User Messaging SMS resources in the corresponding **SMS message Region**.


| Amazon Cognito Region | SMS message Region | 
| --- | --- | 
|  US East (Ohio)  |  US East (Ohio), US East (N. Virginia)  | 
|  US East (N. Virginia)  |  US East (N. Virginia)  | 
|  US West (N. California)  |  US West (N. California)  | 
|  US West (Oregon)  |  US West (Oregon)  | 
|  Canada (Central)  |  Canada (Central), US East (N. Virginia)  | 
|  Canada West (Calgary)  |  Canada West (Calgary)  | 
|  Mexico (Central)  |  Mexico (Central)  | 
|  Europe (Frankfurt)  |  Europe (Frankfurt), Europe (Ireland)  | 
|  Europe (London)  |  Europe (London), Europe (Ireland)  | 
|  Europe (Ireland)  |  Europe (Ireland)  | 
|  Europe (Paris)  |  Europe (Paris)  | 
|  Europe (Stockholm)  |  Europe (Stockholm)  | 
|  Europe (Milan)  |  Europe (Milan)  | 
|  Europe (Spain)  |  Europe (Spain)  | 
|  Europe (Zurich)  |  Europe (Zurich)  | 
| Asia Pacific (Malaysia) | Asia Pacific (Singapore) | 
|  Asia Pacific (Thailand)  |  Asia Pacific (Mumbai)  | 
|  Asia Pacific (Mumbai)  |  Asia Pacific (Mumbai), Asia Pacific (Singapore)  | 
|  Asia Pacific (Hyderabad)  |  Asia Pacific (Hyderabad)  | 
|  Asia Pacific (Hong Kong)  |  Asia Pacific (Singapore)  | 
|  Asia Pacific (Seoul)  |  Asia Pacific (Tokyo)  | 
|  Asia Pacific (Singapore)  |  Asia Pacific (Singapore)  | 
|  Asia Pacific (Sydney)  |  Asia Pacific (Sydney)  | 
|  Asia Pacific (Tokyo)  |  Asia Pacific (Tokyo)  | 
|  Asia Pacific (Jakarta)  |  Asia Pacific (Jakarta)  | 
|  Asia Pacific (Osaka)  |  Asia Pacific (Osaka)  | 
|  Asia Pacific (Melbourne)  |  Asia Pacific (Melbourne)  | 
|  Middle East (Bahrain)  |  Middle East (Bahrain)  | 
|  Middle East (UAE)  |  Middle East (UAE)  | 
|  South America (São Paulo)  |  South America (São Paulo)  | 
|  Israel (Tel Aviv)  |  Israel (Tel Aviv)  | 
|  Africa (Cape Town)  |  Africa (Cape Town)  | 

### Obtain an origination identity to send SMS messages to US phone numbers
<a name="user-pool-sms-settings-first-time-origination"></a>

If you plan to send SMS text messages to US phone numbers, you must obtain an origination identity, regardless of whether you build an SMS sandbox testing environment, or a production environment.

US carriers require an origination identity to send messages to US phone numbers. If you don't already have an origination identity, you must get one. To learn how to obtain an origination identity, see [Request a phone number](https://docs.aws.amazon.com/sms-voice/latest/userguide/phone-numbers-request.html) in the *AWS End User Messaging SMS User Guide*.

When you have more than one origination identity in the same AWS Region, AWS End User Messaging SMS chooses an origination identity type in the following order of priority: short code, 10DLC, toll-free number. You can't change this priority. For more information, see [AWS End User Messaging SMS FAQs](https://aws.amazon.com/end-user-messaging/faqs/).

### Confirm that you are in the SMS sandbox
<a name="user-pool-sms-settings-first-time-confirm-sandbox"></a>

Use the following procedure to confirm that you are in the SMS sandbox. Repeat for each AWS Region where you have production Amazon Cognito user pools.

#### Review SMS sandbox status in the Amazon Cognito console
<a name="check-that-you-are-in-the-sms-sandbox"></a>

**To confirm that you are in the SMS sandbox**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list.

1. Choose the **Authentication methods** menu.

1. In the **SMS configuration** section, expand **Move to Amazon SNS production environment**. If your account is in the SMS sandbox, you will see the following message:

   **Configure AWS service dependencies to complete your SMS message setup**

   If you don’t see this message, then someone has set up SMS messages in your account already. Skip to [Complete user pool setup in Amazon Cognito](#user-pool-sms-settings-first-time-finish-user-pool).

1. Choose the [Amazon SNS](https://console.aws.amazon.com/sns/home) link under **Move to Amazon SNS production environment**. This opens the Amazon SNS console in a new tab.

1. Verify that you are in the sandbox environment. The console message indicates your sandbox status and AWS Region, as follows:

   `This account is in the SMS sandbox in US East (N. Virginia).`

### Move your account out of the sandbox
<a name="user-pool-sms-settings-first-time-out-sandbox"></a>

To use your app in production, move your account out of the SMS sandbox and into production. After you have configured an origination identity in the AWS Region that contains the AWS End User Messaging SMS resources that you want Amazon Cognito to use, you can verify US phone numbers while your AWS account remains in the SMS sandbox. When your environment is in production, you don't have to verify user phone numbers before you send SMS messages to them.

You can create a request to exit the sandbox from either the AWS End User Messaging SMS console or the Amazon SNS console. For detailed instructions, see [Moving from the SMS Sandbox](https://docs.aws.amazon.com/sms-voice/latest/userguide/sandbox.html#sandbox-sms-move-to-production) in the *AWS End User Messaging SMS User Guide*.

### Use simulator numbers or verified phone numbers with AWS End User Messaging SMS
<a name="user-pool-sms-settings-first-time-verify-numbers"></a>

If you have moved your account out of the SMS sandbox, skip this step.

If you're in the sandbox but you have set up an origination number, you can send messages to verified destination numbers. To set up verified destinations, see [Add a verified destination phone number](https://docs.aws.amazon.com/sms-voice/latest/userguide/verify-destination-phone-number.html) in the *AWS End User Messaging SMS User Guide*.

You can also send messages with simulated senders and destinations. Simulator messages produce logs but don't get sent out over the carrier network. From the [Shortcuts menu](https://console.aws.amazon.com/sms-voice/home?#/shortcuts), select **Test SMS sending with SMS simulator**. For more information, see [Simulator phone numbers](https://docs.aws.amazon.com/sms-voice/latest/userguide/test-phone-numbers.html) in the *AWS End User Messaging SMS User Guide*.

### Complete user pool setup in Amazon Cognito
<a name="user-pool-sms-settings-first-time-finish-user-pool"></a>

Return to the browser tab where you were creating or [editing](signing-up-users-in-your-app.md#verification-configure) your user pool. Complete the procedure. When you have successfully added SMS configuration to your user pool, Amazon Cognito sends a test message to an internal phone number to verify that your configuration works. Amazon SNS charges for each test SMS message.

# Using Amazon Cognito user pools security features
<a name="managing-security"></a>

You might want to secure your application against network intrusion, password guessing, user impersonation, and malicious sign-up and sign-in. Your configuration of Amazon Cognito user pools security features can be a key component in your security architecture. The security of your application is *Customer responsibility "Security in the cloud"* as described in the AWS [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/). The tools in this chapter contribute to the ability of your application security design to be in line with these goals.

An important decision that you must make when you configure your user pool is whether to permit public sign-up and sign-in. Some user pool option like confidential clients, administrative creation and confirmation of users, and user pools without a domain, are subject to a smaller degree to attacks over the internet. However, a common use case is public clients that accept sign-up from anyone on the internet and send all operations directly to your user pool. In any configuration, but especially in the case of these public configurations, we recommend that you plan and deploy your user pool with security features in mind. Insufficient security can also affect your AWS bill when unwanted sources create new active users or attempt to exploit existing users.

MFA and threat protection apply to [local users](cognito-terms.md#terms-localuser). Third-party IdPs are responsible for the security posture of [federated users](cognito-terms.md#terms-federateduser).User pools security features

**Multi-factor authentication (MFA)**  
Request a code that your user pool send by email (with the Essentials or Plus feature plan) or SMS message, or from an authenticator app, to confirm user pool sign-in.

**Threat protection**  
Monitor sign-in for indicators of risk and apply MFA or block sign-in. Add custom claims and scopes to access tokens. Send MFA codes by email.

**AWS WAF web ACLs**  
Inspect incoming traffic to your [user pool endpoints and authentication API](authentication-flows-public-server-side.md#user-pools-API-operations) for unwanted activity at the network and application layers.

**Case sensitvity**  
Prevent creation of users whose email address or preferred username is identical to another user except for character case.

**Deletion protection**  
Prevent automated systems from accidentally deleting your user pools. Require additional confirmation of user pool deletion in the AWS Management Console.

**User existence errors**  
Guard against disclosure of existing usernames and aliases in your user pool. Return a generic error in response to unsuccessful authentication, whether the username is valid or not.

**Topics**
+ [

# Adding MFA to a user pool
](user-pool-settings-mfa.md)
+ [

# Advanced security with threat protection
](cognito-user-pool-settings-threat-protection.md)
+ [

# Associate an AWS WAF web ACL with a user pool
](user-pool-waf.md)
+ [

# User pool case sensitivity
](user-pool-case-sensitivity.md)
+ [

# User pool deletion protection
](user-pool-settings-deletion-protection.md)
+ [

# Managing user existence error responses
](cognito-user-pool-managing-errors.md)

# Adding MFA to a user pool
<a name="user-pool-settings-mfa"></a>

MFA adds a *something you have* authentication factor to the initial *something you know* factor that is typically a username and password. You can choose SMS text messages, email messages, or time-based one-time passwords (TOTP) as additional factors to sign in your users who have passwords as their primary authentication factor.

Multi-factor authentication (MFA) increases security for the [local users](cognito-terms.md#terms-localuser) in your application. In the case of [federated users](cognito-terms.md#terms-federateduser), Amazon Cognito delegates all authentication processes to the IdP and doesn't offer them additional authentication factors.

**Note**  
The first time that a new user signs in to your app, Amazon Cognito issues OAuth 2.0 tokens, even if your user pool requires MFA. The second authentication factor when your user signs in for the first time is their confirmation of the verification message that Amazon Cognito sends to them. If your user pool requires MFA, Amazon Cognito prompts your user to register an additional sign-in factor to use during each sign-in attempt after the first.

With adaptive authentication, you can configure your user pool to require an additional authentication factor in response to an increased risk level. To add adaptive authentication to your user pool, see [Advanced security with threat protection](cognito-user-pool-settings-threat-protection.md).

When you set MFA to `required` for a user pool, all users must complete MFA to sign in. To sign in, each user must set up at least one MFA factor. When MFA is required, you must include the MFA setup in user onboarding so that your user pool permits them to sign in.

Managed login prompts users to set up MFA when you set MFA to be required. When you set MFA to be optional in your user pool, managed login doesn't prompt users. To work with optional MFA, you must build an interface in your app that prompts your users to select that they want to set up MFA, then guides them through the API inputs to verify their additional sign-in factor.

**Topics**
+ [

## Things to know about user pool MFA
](#user-pool-settings-mfa-prerequisites)
+ [

## User MFA preferences
](#user-pool-settings-mfa-preferences)
+ [

## Details of MFA logic at user runtime
](#user-pool-settings-mfa-user-outcomes)
+ [

## Configure a user pool for multi-factor authentication
](#user-pool-configuring-mfa)
+ [

# SMS and email message MFA
](user-pool-settings-mfa-sms-email-message.md)
+ [

# TOTP software token MFA
](user-pool-settings-mfa-totp.md)

## Things to know about user pool MFA
<a name="user-pool-settings-mfa-prerequisites"></a>

Before you set up MFA, consider the following:
+ Users can either have MFA *or* sign in with passwordless factors, with one exception: passkeys with user verification can satisfy MFA requirements when you set `FactorConfiguration` to `MULTI_FACTOR_WITH_USER_VERIFICATION` in your user pool `WebAuthnConfiguration`.
  + You can't set MFA to required in user pools that support [one-time passwords](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passwordless).
  + You can't add `EMAIL_OTP` or `SMS_OTP` to `AllowedFirstAuthFactors` when MFA is required in your user pool. You can add `WEB_AUTHN` when `FactorConfiguration` is set to `MULTI_FACTOR_WITH_USER_VERIFICATION`.
  + [Choice-based sign-in](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) only offers `PASSWORD` and `PASSWORD_SRP` factors in all app clients when MFA is required in the user pool. For more information about username-password flows, see [Sign-in with persistent passwords](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-password) and [Sign-in with persistent passwords and secure payload](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-srp) in the **Authentication** chapter of this guide.
  + In user pools where MFA is optional, users who have configured an MFA factor can only sign in with username-password authentication flows in choice-based sign-in. These users are eligible for all [client-based sign-in](authentication-flows-selection-sdk.md#authentication-flows-selection-client) flows.

  The following table describes the effect of user pool MFA settings and user configuration of MFA factors on users' ability to sign in with passwordless factors.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html)
+ A user's preferred MFA method influences the methods they can use to recover their password. Users whose preferred MFA is by email message can't receive a password-reset code by email. Users whose preferred MFA is by SMS message can't receive a password-reset code by SMS.

  Your [password recovery](managing-users-passwords.md#user-pool-password-reset-and-recovery) settings must provide an alternative option when users aren't eligible for your preferred password-reset method. For example, your recovery mechanisms might have email as first priority and email MFA might be an option in your user pool. In this case, add SMS-message account recovery as a second option or use administrative API operations to reset passwords for those users.

  Amazon Cognito replies to password-reset requests from users who don't have a valid recovery method with an `InvalidParameterException` error response.

  The example request body for [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html#API_UpdateUserPool_Examples) illustrates an `AccountRecoverySetting` where users can fall back to recovery by SMS message when email-message password reset is unavailable.
+ Users can't receive MFA and password reset codes at the same email address or phone number. If they use one-time passwords (OTPs) from email messages for MFA, they must use SMS messages for account recovery. If they use OTPs from SMS messages for MFA, they must use email messages for account recovery. In user pools with MFA, users might be unable to complete self-service password recovery if they have attributes for their email address but no phone number, or their phone number but no email address.

  To prevent the state where users can't reset their passwords in user pools with this configuration, set the `email` and `phone_number` [attributes as required](user-pool-settings-attributes.md). As an alternative, you can set up processes that always collect and set those attributes when users sign up or when your administrators create user profiles. When users have both attributes, Amazon Cognito automatically sends password-reset codes to the destination that is *not* the user's MFA factor.
+ When you activate MFA in your user pool and choose **SMS message** or **Email message** as a second factor, you can send messages to a phone number or email attribute that you haven't verified in Amazon Cognito. After your user completes MFA, Amazon Cognito sets their `phone_number_verified` or `email_verified` attribute to `true`.
+ After five unsuccessful attempts to present an MFA code, Amazon Cognito begins the exponential-timeout lockout process described at [Lockout behavior for failed sign-in attempts](authentication.md#authentication-flow-lockout-behavior).
+ If your account is in the SMS sandbox in the AWS Region that contains the Amazon Simple Notification Service (Amazon SNS) resources for your user pool, you must verify phone numbers in Amazon SNS before you can send an SMS message. For more information, see [SMS message settings for Amazon Cognito user pools](user-pool-sms-settings.md).
+ To change the MFA status of users in response to detected events with threat protection, activate MFA and set it as optional in the Amazon Cognito user pool console. For more information, see [Advanced security with threat protection](cognito-user-pool-settings-threat-protection.md).
+ Email and SMS messages require that your users have email address and phone number attributes respectively. You can set `email` or `phone_number` as required attributes in your user pool. In this case, users can't complete sign-up unless they provide a phone number. If you don't set these attributes as required but want to do email or SMS message MFA, you prompt users for their email address or phone number when they sign up. As a best practice, configure your user pool to automatically message users to [verify these attributes](signing-up-users-in-your-app.md).

  Amazon Cognito counts a phone number or email address as verified if a user has successfully received a temporary code by SMS or email message and returned that code in a [VerifyUserAttribute](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifyUserAttribute.html) API request. As an alternative, your team can set phone numbers and mark them as verified with an administrative application that performs [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) API requests.
+ If you have set MFA to be required and you activated more than one authentication factor, Amazon Cognito prompts new users to select an MFA factor that they want to use. Users must have a phone number to set up SMS message MFA, and an email address to set up email message MFA. If a user doesn't have the attribute defined for any available message-based MFA, Amazon Cognito prompts them to set up TOTP MFA. The prompt to choose an MFA factor (`SELECT_MFA_TYPE`) and to set up a chosen factor (`MFA_SETUP`) comes in as a challenge response to [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) API operations.

## User MFA preferences
<a name="user-pool-settings-mfa-preferences"></a>

Users can set up multiple MFA factors. Only one can be active. You can choose the effective MFA preference for your users in user pool settings or from user prompts. A user pools prompts a user for MFA codes when user pool settings and their own user-level settings meet the following conditions:

1. You set MFA to optional or required in your user pool.

1. The user has a valid `email` or `phone_number`attribute, or has set up an authenticator app for TOTP.

1. At least one MFA factor is active.

1. One MFA factor is set as preferred.

### Prevent the use of the same factor for sign-in and MFA
<a name="user-pool-settings-mfa-preferences-same-factor"></a>

It's possible to configure your user pool in a way that makes one sign-in factor the only available sign-in and MFA option for some or all users. This result can happen when your primary sign-in use case is email-message or SMS-message one-time passwords (OTPs). A user's preferred MFA might be the same type of factor as their sign-in under the following conditions:
+ MFA is required in the user pool.
+ Email and SMS OTP are available sign-in *and* MFA options in the user pool.
+ The user signs in with email or SMS message OTP.
+ They have an email-address attribute but no phone-number attribute, or a phone-number attribute but no email-address attribute.

In this scenario, the user can sign in with an email OTP and complete MFA with an email OTP. This option cancels out the essential function of MFA. Users who sign in with one-time passwords must be able to use different delivery methods for sign-in than for MFA. When users have both SMS and email options, Amazon Cognito automatically assigns a different factor. For example, when a user signs in with email OTP, their preferred MFA is SMS OTP.

Take the following steps to address same-factor authentication when your user pool supports OTP authentication for both sign-in and MFA.

1. Enable both email and SMS OTP as sign-in factors.

1. Enable both email and SMS OTP as MFA factors.

1. Collect

### User pool settings and their effect on MFA options
<a name="user-pool-settings-mfa-preferences-things-to-know"></a>

The configuration of your user pool influences the MFA methods that users can choose. The following are some user pool settings that influence users’ ability to set up MFA.
+ In the **Multi-factor authentication** configuration in the **Sign-in** menu of the Amazon Cognito console, you can set MFA to optional or required, or turn it off. The API equivalent of this setting is the [MfaConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-MfaConfiguration) parameter of `CreateUserPool`, `UpdateUserPool`, and `SetUserPoolMfaConfig`.

  Also in the **Multi-factor authentication** configuration, the **MFA methods** setting determines the MFA factors that users can set up. The API equivalent of this setting is the [SetUserPoolMfaConfig](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserPoolMfaConfig.html) operation. 
+ In the **Sign-in** menu, under **User account recovery**, you can configure the way that your user pool sends messages to users who forget their password. A user's MFA method can’t have the same MFA delivery method as the user pool delivery method for forgot-password codes. The API parameter for the forgot-password delivery method is the [AccountRecoverySetting](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-AccountRecoverySetting) parameter of `CreateUserPool` and `UpdateUserPool`.

  For example, users can’t set up email MFA when your recovery option is **Email only**. This is because you can't enable email MFA and set the recovery option to **Email only** in the same user pool. When you set this option to **Email if available, otherwise SMS**, email is the priority recovery option but your user pool can fall back to SMS message when a user isn't eligible for email-message recovery. In this scenario, users can set email MFA as preferred and can only receive an SMS message when they attempt to reset their password.
+ If you set only one MFA method as available, you don’t need to manage user MFA preferences.
+ An active SMS configuration automatically makes SMS messages an available MFA method in your user pool.

  An active [email configuration](user-pool-email.md) with your own Amazon SES resources in a user pool, and the Essentials or Plus feature plan, automatically makes email messages an available MFA method in your user pool.
+ When you set MFA to required in a user pool, users can’t enable or disable any MFA methods. You can only set a preferred method.
+ When you set MFA to optional in a user pool, managed login doesn’t prompt users to set up MFA, but it does prompt users for an MFA code when they have a preferred MFA method.
+ When you activate [threat protection](cognito-user-pool-settings-threat-protection.md) and configure adaptive-authentication responses in full-function mode, MFA must be optional in your user pool. One of the response options with adaptive authentication is to require MFA for a user whose sign-in attempt is evaluated to contain a level of risk.

  The **Required attributes** setting in the **Sign-up** menu of the console determines whether users must provide an email address or phone number to sign up in your application. Email and SMS messages become eligible MFA factors when a user has the corresponding attribute. The [Schema](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#CognitoUserPools-CreateUserPool-request-Schema) parameter of `CreateUserPool` sets attributes as required.
+ When you set MFA to required in a user pool and a user signs in with managed login, Amazon Cognito prompts them to select an MFA method from the available methods for your user pool. Managed login handles the collection of an email address or phone number and the setup of TOTP. The diagram that follows demonstrates the logic behind the options that Amazon Cognito presents to users.

### Configure MFA preferences for users
<a name="user-pool-settings-mfa-preferences-configure"></a>

You can configure MFA preferences for users in a self-service model with access-token authorization, or in an administrator-managed model with administrative API operations. These operations enable or disable MFA methods and set one of multiple methods as the preferred option. After your user has set an MFA preference, Amazon Cognito prompts them at sign-in to provide a code from their preferred MFA method. Users who have not set a preference receive a prompt to choose a preferred method in a `SELECT_MFA_TYPE` challenge.
+ In a user self-service model or public application, [SetUserMfaPreference](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserMFAPreference.html), authorized with a signed-in user’s access token, sets MFA configuration.
+ In an administrator-managed or confidential application, [AdminSetUserPreference](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserMFAPreference.html), authorized with administrative AWS credentials, sets MFA configuration.

You can also set user MFA preferences from the **Users** menu of the Amazon Cognito console. For more information about the public and confidential authentication models in the Amazon Cognito user pools API, see [Understanding API, OIDC, and managed login pages authentication](authentication-flows-public-server-side.md#user-pools-API-operations).

## Details of MFA logic at user runtime
<a name="user-pool-settings-mfa-user-outcomes"></a>

To determine the steps to take when users sign in, your user pool evaluates user MFA preferences, [user attributes](user-pool-settings-attributes.md), the [user pool MFA setting](#user-pool-configuring-mfa), [threat protection](cognito-user-pool-settings-adaptive-authentication.md) actions, and [self-service account recovery](managing-users-passwords.md#user-pool-password-reset-and-recovery) settings. It then signs users in, prompts them to choose an MFA method, prompts them to set up an MFA method, or prompts them for MFA. To set up an MFA method, users must provide an [email address or phone number](user-pool-settings-mfa-sms-email-message.md) or [register a TOTP authenticator](user-pool-settings-mfa-totp.md#totp-mfa-set-up-api). They can also set up MFA options and [register a preferred option](#user-pool-settings-mfa-preferences-configure) in advance. The following diagram lists the detailed effects of user pool configuration on sign-in attempts immediately after initial sign-up.

The logic illustrated here applies to SDK-based applications and [managed login](cognito-user-pools-managed-login.md) sign-in, but is less visible in managed login. When you troubleshoot MFA, work backward from your users' outcomes to the user-profile and user-pool configurations that contributed to the decision.

![\[A diagram of the Amazon Cognito user pools decision process for end-user MFA selection.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/cup-mfa-decision-tree.png)


The following list corresponds to the numbering in the decision logic diagram and describes each step in detail. A ![\[checkmark\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png) indicates a successful authentication and the conclusion of the flow. A ![\[error\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/error.png) indicates unsuccessful authentication.

1. A user presents their username or username and password at your sign-in screen. If they don't present valid credentials, their sign-in request is denied. 

1. If they succeed username-password authentication, determine whether MFA is required, optional, or off. If it is off, the correct username and password results in successful authentication. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

   1. If MFA is optional, determine if the user has previously set up a TOTP authenticator. If they have set up TOTP, prompt for TOTP MFA. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

   1. Determine if the adaptive authentication feature of threat protection has required the user to set up MFA. If it hasn't assigned MFA, the user is signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

1. If MFA is required or adaptive authentication has assigned MFA, determine if the user has set an MFA factor as enabled and preferred. If they have, prompt for MFA with that factor. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

1. If the user hasn't set an MFA preference, determine if the user has registered a TOTP authenticator.

   1. If the user has registered a TOTP authenticator, determine if TOTP MFA is available in the user pool (TOTP MFA can be disabled after users have previously set up authenticators).

   1. Determine whether email-message or SMS-message MFA is also available in the user pool.

   1.  If neither email nor SMS MFA is available, prompt the user for TOTP MFA. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

   1. If email or SMS MFA are available, determine whether the user has the corresponding `email` or `phone_number` attribute. If so, any attribute that isn't the primary method for self-service account recovery and is enabled for MFA is available to them.

   1. Prompt the user with a `SELECT_MFA_TYPE` challenge with `MFAS_CAN_SELECT` options that include TOTP and the available SMS or email MFA factors.

   1.  Prompt the user for the factor that they select in response to the `SELECT_MFA_TYPE` challenge. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

1. If the user hasn't registered a TOTP authenticator, or if they have but TOTP MFA is currently disabled, determine whether the user has an `email` or `phone_number` attribute.

1.  If the user has only an email address or only a phone number, determine whether that attribute is also the method the user pool implements to send account-recovery messages for password reset. If true, they can't complete sign-in with MFA required and Amazon Cognito returns an error. To activate sign-in for this user, you must add a non-recovery attribute or register a TOTP authenticator for them. ![\[alt text not found\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/error.png)

   1. If they have an available non-recovery email address or phone number, determine whether the corresponding email or SMS MFA factor is enabled.

   1. If they have a non-recovery email address attribute and email MFA is enabled, prompt them with an `EMAIL_OTP` challenge. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

   1. If they have a non-recovery phone number attribute and SMS MFA is enabled, prompt them with an `SMS_MFA` challenge. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

   1. If they don't have an attribute that's eligible for an enabled email or SMS MFA factor, determine whether TOTP MFA is enabled. If TOTP MFA is disabled, they can't complete sign-in with MFA required and Amazon Cognito returns an error. To activate sign-in for this user, you must add a non-recovery attribute or register a TOTP authenticator for them. ![\[alt text not found\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/error.png)
**Note**  
This step has already been evaluated as **No** if the user has a TOTP authenticator but TOTP MFA is disabled.

   1. If TOTP MFA is enabled, present the user with a `MFA_SETUP` challenge with `SOFTWARE_TOKEN_MFA` in the `MFAS_CAN_SETUP` options. To complete this challenge, you must separately register a TOTP authenticator for the user and respond with `"ChallengeName": "MFA_SETUP", "ChallengeResponses": {"USERNAME": "[username]", "SESSION": "[Session ID from VerifySoftwareToken]}"`.

   1. After the user responds to the `MFA_SETUP` challenge with the session token from a [VerifySoftwareToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifySoftwareToken.html) request, prompt them with an `SOFTWARE_TOKEN_MFA` challenge. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

1. If the user has both an email address and phone number, determine which attribute, if any, is the primary method for account-recovery messages for password reset.

   1. If self-service account recovery is disabled, either attribute can be used for MFA. Determine whether one or both of the email and SMS MFA factors are enabled.

   1. If both attributes are enabled as an MFA factor, prompt the user with a `SELECT_MFA_TYPE` challenge with `MFAS_CAN_SELECT` options `SMS_MFA` and `EMAIL_OTP`.

   1. Prompt them for the factor that they select in response to the `SELECT_MFA_TYPE` challenge. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

   1. If only one attribute is an eligible MFA factor, prompt them with a challenge for the remaining factor. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

      This outcome happens in the following scenarios.

      1. When they have `email` and `phone_number` attributes, SMS and email MFA are enabled, and the primary account-recovery method is by email or SMS message.

      1. When they have `email` and `phone_number` attributes, only SMS MFA or email MFA is enabled, and self-service account recovery is disabled.

1. If the user hasn't registered a TOTP authenticator and has neither an `email` nor `phone_number` attribute, prompt them with an `MFA_SETUP` challenge. The list in `MFAS_CAN_SETUP` includes all enabled MFA factors in the user pool that aren't the primary account-recovery option. They can respond to this challenge with `ChallengeResponses` for email or TOTP MFA. To set up SMS MFA, add a phone number attribute separately and restart authentication.

   For TOTP MFA, respond with `"ChallengeName": "MFA_SETUP", "ChallengeResponses": {"USERNAME": "[username]", "SESSION": "[Session ID from VerifySoftwareToken]"}`.

   For email MFA, respond with `"ChallengeName": "MFA_SETUP", "ChallengeResponses": {"USERNAME": "[username]", "email": "[user's email address]"}`.

   1. Prompt them for the factor that they select in response to the `SELECT_MFA_TYPE` challenge. If they successfully respond to the MFA challenge, they're signed in. ![\[Green circular icon with a checkmark symbol inside.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/checkmark.png)

## Configure a user pool for multi-factor authentication
<a name="user-pool-configuring-mfa"></a>

You can configure MFA in the Amazon Cognito console or with the [SetUserPoolMfaConfig](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserPoolMfaConfig.html) API operation and SDK methods.

**To configure MFA in the Amazon Cognito console**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home).

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Sign-in** menu. Locate **Multi-factor authentication** and choose **Edit**.

1. Choose the **MFA enforcement** method that you want to use with your user pool.  
![\[A screenshot from the Amazon Cognito console with MFA options.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/cup-mfa.png)

   1. **Require MFA**. All users in your user pool must sign in with an additional SMS, email, or time-based one-time password (TOTP) code as an additional authentication factor.

   1. **Optional MFA**. You can give your users the option to register an additional sign-in factor but still permit users who haven't configured MFA to sign in. If you use adaptive authentication, choose this option. For more information about adaptive authentication, see [Advanced security with threat protection](cognito-user-pool-settings-threat-protection.md).

   1. **No MFA**. Your users can't register an additional sign-in factor.

1. Choose the **MFA methods** that you support in your app. You can set **Email message**, **SMS message** or TOTP-generating **Authenticator apps** as a second factor.

1. If you use SMS text messages as a second factor and you haven't configured an IAM role to use with Amazon Simple Notification Service (Amazon SNS) for SMS messages, create one in the console. In the **Authentication methods** menu for your user pool, locate **SMS** and choose **Edit**. You can also use an existing role that allows Amazon Cognito to send SMS messages to your users for you. For more information, see [IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html).

   If you use email messages as a second factor and you haven't configured an originating identity to use with Amazon Simple Email Service (Amazon SES) for email messages, create one in the console. You must choose the **Send email with SES** option. In the **Authentication methods** menu for your user pool, locate **Email** and choose **Edit**. Select a **FROM email address** from the available verified identities in the list. If you choose a verified domain, for example `example.com`, you must also configure a **FROM sender name** in the verified domain, for example `admin-noreply@example.com`.

1. Choose **Save changes**.

# SMS and email message MFA
<a name="user-pool-settings-mfa-sms-email-message"></a>

SMS and email MFA messages confirm that users have access to a message destination before they can sign in. They confirm that they not only have access to a password, but to the SMS messages or the email inbox of the original user. Amazon Cognito requests that users provide a short code that your user pool sent after they successfully provide a username and password.

SMS and email message MFA require no additional configuration after your user adds an email address or phone number to their profile. Amazon Cognito can send messages to unverified email addresses and phone numbers. When a user completes their first MFA, Amazon Cognito marks their email address or phone number as verified.

MFA authentication begins when a user with MFA enters their username and password in your application. Your application submits these initial parameters in an SDK method that invokes an [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) API request. The `ChallengeParameters` in the API response includes a `CODE_DELIVERY_DESTINATION` value that indicates where the authorization code was sent. In your application, display a form that prompts the user to check their phone and includes an input element for the code. When they enter their code, submit it in a challenge-response API request to complete the sign-in process.

After a user with MFA signs in with username and password in the [managed login](cognito-user-pools-managed-login.md) pages, they're automatically prompted for the MFA code.

User pools send SMS messages for MFA and other Amazon Cognito notifications with Amazon Simple Notification Service (Amazon SNS) resources in your AWS account. Similarly, users pools send email messages with Amazon Simple Email Service (Amazon SES) resources in your account. These linked services incur their own costs on your AWS bill for message delivery. They also have additional requirements for sending messages at production volumes. See the following links for more information:
+ [SMS message settings for Amazon Cognito user pools](user-pool-sms-settings.md)
+ [Worldwide SMS Pricing](https://aws.amazon.com/sns/sms-pricing/)
+ [Email settings for Amazon Cognito user pools](user-pool-email.md)
+ [Amazon SES pricing](https://aws.amazon.com/ses/pricing)

## Considerations for SMS and email message MFA
<a name="user-pool-settings-mfa-sms-email-message-considerations"></a>
+ To permit users to sign in with email MFA, your user pool must have the following configuration options:

  1. You have the Plus or Essentials feature plan in your user pool. For more information, see [User pool feature plans](cognito-sign-in-feature-plans.md).

  1. Your user pool sends email messages with your own Amazon SES resources. For more information, see [Amazon SES email configuration](user-pool-email.md#user-pool-email-developer).
+ The MFA code is valid for the **Authentication flow session duration** that you set for your app client.

  Set the duration of an authentication flow session in the Amazon Cognito console in the **App clients** menu when you **Edit** your app client. You can also set the authentication flow session duration in a `CreateUserPoolClient` or `UpdateUserPoolClient` API request. For more information, see [An example authentication session](authentication.md#amazon-cognito-user-pools-authentication-flow).
+ When a user successfully provides a code from an SMS or email message that Amazon Cognito sent to an unverified phone number or email address, Amazon Cognito marks the corresponding attribute as verified.
+ For a user to make a self-service change to the value of a phone number or email address that's associated with MFA, they must sign in and authorize the request with an access token. If they can't access their current phone number or email address, they can't sign in. Your team must change these values with administrator AWS credentials in [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html) API requests.
+ After you [configure SMS](user-pool-sms-settings.md) in your user pool, you can't disable SMS messages as an available MFA factor.

# TOTP software token MFA
<a name="user-pool-settings-mfa-totp"></a>

When you set up TOTP software token MFA in your user pool, your user signs in with a username and password, then uses a TOTP to complete authentication. After your user sets and verifies a username and password, they can activate a TOTP software token for MFA. If your app uses the Amazon Cognito managed login to sign in users, your user submits their username and password, and then submits the TOTP password on an additional sign-in page.

You can activate TOTP MFA for your user pool in the Amazon Cognito console, or you can use Amazon Cognito API operations. At the user pool level, you can call [SetUserPoolMfaConfig](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserPoolMfaConfig.html) to configure MFA and enable TOTP MFA.

**Note**  
If you haven't activated TOTP software token MFA for the user pool, Amazon Cognito can't use the token to associate or verify users. In this case, users receive a `SoftwareTokenMFANotFoundException` exception with the description `Software Token MFA has not been enabled by the userPool`. If you deactivate software token MFA for the user pool later, users who previously associated and verified a TOTP token can continue to use it for MFA.

Configuring TOTP for your user is a multi-step process where your user receives a secret code that they validate by entering a one-time password. Next, you can enable TOTP MFA for your user or set TOTP as the preferred MFA method for your user.

When you configure your user pool to require TOTP MFA and your users sign up for your app in managed login, Amazon Cognito automates the user process. Amazon Cognito prompts your user to choose an MFA method, displays a QR code to set up their authenticator app, and verifies their MFA registration. In user pools where you have allowed users to choose between SMS and TOTP MFA, Amazon Cognito also presents your user with a choice of method.

**Important**  
When you have an AWS WAF web ACL associated with a user pool, and a rule in your web ACL presents a CAPTCHA, this can cause an unrecoverable error in managed login TOTP registration. To create a rule that has a CAPTCHA action and doesn't affect managed login TOTP, see [Configuring your AWS WAF web ACL for managed login TOTP MFA](#totp-waf). For more information about AWS WAF web ACLs and Amazon Cognito, see [Associate an AWS WAF web ACL with a user pool](user-pool-waf.md).

To implement TOTP MFA in a custom-built UI with an AWS SDK and the [Amazon Cognito user pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html), see [Configuring TOTP MFA for a user](#totp-mfa-set-up-api).

To add MFA to your user pool, see [Adding MFA to a user pool](user-pool-settings-mfa.md).

**TOTP MFA considerations and limitations**

1. Amazon Cognito supports software token MFA through an authenticator app that generates TOTP codes. Amazon Cognito doesn't support hardware-based MFA.

1. When your user pool requires TOTP for a user who has not configured it, your user receives a one-time access token that your app can use to activate TOTP MFA for the user. Subsequent sign-in attempts fail until your user has registered an additional TOTP sign-in factor.
   + A user who signs up in your user pool with the `SignUp` API operation or through managed login receives one-time tokens when the user completes sign-up.
   + After you create a user, and the user sets their initial password, Amazon Cognito issues one-time tokens from managed login to the user. If you set a permanent password for the user, Amazon Cognito issues one-time tokens when the user first signs in.
   + Amazon Cognito doesn't issue one-time tokens to an administrator-created user who signs in with the [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) API operations. After your user succeeds in the challenge to set their initial password, or if you set a permanent password for the user, Amazon Cognito immediately challenges the user to set up MFA.

1. If a user in a user pool that requires MFA has already received a one-time access token but hasn't set up TOTP MFA, the user can't sign in with managed login until they have set up MFA. Instead of the access token, you can use the `session` response value from an `MFA_SETUP` challenge to [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) or [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) in an [AssociateSoftwareToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AssociateSoftwareToken.html) request.

1. If your users have set up TOTP, they can use it for MFA, even if you deactivate TOTP for the user pool later.

1. Amazon Cognito only accepts TOTPs from authenticator apps that generate codes with the HMAC-SHA1 hash function. Codes generated with SHA-256 hashing return a `Code mismatch` error.

## Configuring TOTP MFA for a user
<a name="totp-mfa-set-up-api"></a>

When a user first signs in, your app uses their one-time access token to generate the TOTP private key and present it to your user in text or QR code format. Your user configures their authenticator app and provides a TOTP for subsequent sign-in attempts. Your app or managed login presents the TOTP to Amazon Cognito in MFA challenge responses.

Under some circumstances, managed login prompts new users to set up a TOTP authenticator. for more information, see [Details of MFA logic at user runtime](user-pool-settings-mfa.md#user-pool-settings-mfa-user-outcomes).

**Topics**
+ [

### Associate the TOTP software token
](#user-pool-settings-mfa-totp-associate-token)
+ [

### Verify the TOTP token
](#user-pool-settings-mfa-totp-verification)
+ [

### Sign in with TOTP MFA
](#user-pool-settings-mfa-totp-sign-in)
+ [

### Remove the TOTP token
](#user-pool-settings-mfa-totp-remove)

### Associate the TOTP software token
<a name="user-pool-settings-mfa-totp-associate-token"></a>

To associate the TOTP token, send your user a secret code that they must validate with a one-time password. Associating the token requires three steps.

1. When your user chooses TOTP software token MFA, call [AssociateSoftwareToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AssociateSoftwareToken.html) to return a unique generated shared secret key code for the user account. You can authorize AssociateSoftwareToken with either an access token or a session string. 

1. Your app presents the user with the private key, or a QR code that you generate from the private key. Your user must enter the key into a TOTP-generating app like Google Authenticator, either by scanning the QR code that your application generates from the private key or by manually entering the key.

1. Your user enters the key, or scans the QR code into a authenticator app such as Google Authenticator, and the app begins generating codes.

### Verify the TOTP token
<a name="user-pool-settings-mfa-totp-verification"></a>

Next, verify the TOTP token. Request sample codes from your user and provide them to the Amazon Cognito service to confirm that the user is successfully generating TOTP codes, as follows.

1. Your app prompts your user for a code to demonstrate that they have set up their authenticator app properly.

1. The user's authenticator app displays a temporary password. The authenticator app bases the password on the secret key you gave to the user.

1. Your user enters their temporary password. Your app passes the temporary password to Amazon Cognito in a `[VerifySoftwareToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifySoftwareToken.html)` API request.

1.  Amazon Cognito has retained the secret key associated with the user, and generates a TOTP and compares it with the one that your user provided. If they match, `VerifySoftwareToken` returns a `SUCCESS` response.

1. Amazon Cognito associates the TOTP factor with the user.

1. If the `VerifySoftwareToken` operation returns an `ERROR` response, make sure that the user's clock is correct and that they have not exceeded the maximum number of retries. Amazon Cognito accepts TOTP tokens that are within 30 seconds before or after the attempt, to account for minor clock skew. When you have resolved the issue, try the VerifySoftwareToken operation again.

### Sign in with TOTP MFA
<a name="user-pool-settings-mfa-totp-sign-in"></a>

At this point, your user signs in with the time-based one-time password. The process is as follows.

1. Your user enters their username and password to sign in to your client app.

1. The TOTP MFA challenge is invoked, and your user is prompted by your app to enter a temporary password.

1. Your user gets the temporary password from an associated TOTP-generating app.

1. Your user enters the TOTP code into your client app. Your app notifies the Amazon Cognito service to verify it. For each sign-in, [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) should be called to get a response to the new TOTP authentication challenge.

1. If the token is verified by Amazon Cognito, the sign-in is successful and your user continues with the authentication flow. 

### Remove the TOTP token
<a name="user-pool-settings-mfa-totp-remove"></a>

Finally, your app should allow your user to deactivate their TOTP configuration. Currently, you can't delete a user's TOTP software token. To replace your user's software token, associate and verify a new software token. To deactivate TOTP MFA for a user, call [SetUserMFAPreference](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserMFAPreference.html) to modify your user to use no MFA, or only SMS MFA.

1. Create an interface in your app for users who want to reset MFA. Prompt a user in this interface to enter their password.

1. If Amazon Cognito returns a TOTP MFA challenge, update your user's MFA preference with [SetUserMFAPreference](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserMFAPreference.html).

1. In your app, communicate to your user that they have deactivated MFA and prompt them to sign in again.

## Configuring your AWS WAF web ACL for managed login TOTP MFA
<a name="totp-waf"></a>

When you have an AWS WAF web ACL associated with a user pool, and a rule in your web ACL presents a CAPTCHA, this can cause an unrecoverable error in managed login TOTP registration. AWS WAF CAPTCHA rules *only* have this effect on TOTP MFA in managed login and the classic hosted UI. SMS MFA is unaffected.

Amazon Cognito displays the following error when your CAPTCHA rule doesn't let a user complete TOTP MFA setup. 

Request not allowed due to WAF captcha.

This error results when AWS WAF prompts for a CAPTCHA in response to [AssociateSoftwareToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AssociateSoftwareToken.html) and [VerifySoftwareToken](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerifySoftwareToken.html) API requests that your user pool makes in the background. To create a rule that has a CAPTCHA action and doesn't affect TOTP in managed login pages, exclude the `x-amzn-cognito-operation-name` header values of `AssociateSoftwareToken` and `VerifySoftwareToken` from the CAPTCHA action in your rule.

The following screenshot shows an example AWS WAF rule that applies a CAPTCHA action to all requests that don't have a `x-amzn-cognito-operation-name` header value of `AssociateSoftwareToken` or `VerifySoftwareToken`.

![\[A screenshot of a AWS WAF rule that applies a CAPTCHA action to all requests that don't have a x-amzn-cognito-operation-name header value of AssociateSoftwareToken or VerifySoftwareToken.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/cup-WAF-rule-TOTP.png)


For more information about AWS WAF web ACLs and Amazon Cognito, see [Associate an AWS WAF web ACL with a user pool](user-pool-waf.md).

# Advanced security with threat protection
<a name="cognito-user-pool-settings-threat-protection"></a>

After you create your user pool, you have access to **Threat protection** in the navigation menu in the Amazon Cognito console. You can turn threat protection features on and customize the actions that are taken in response to different risks. Or you can use audit mode to gather metrics on detected risks without applying any security mitigations. In audit mode, threat protection publishes metrics to Amazon CloudWatch. You can see metrics after Amazon Cognito generates its first event. See [Viewing threat protection metrics](metrics-for-cognito-user-pools.md#user-pool-settings-viewing-threat-protection-metrics).

Threat protection, formerly called *advanced security features*, is a set of monitoring tools for unwanted activity in your user pool, and configuration tools to automatically shut down potentially malicious activity. Threat protection has different configuration options for standard and custom authentication operations. For example, you might want to send a notification to a user with a suspicious custom authentication sign-in, where you have set up additional security factors, but block a user at the same risk level with basic username-password authentication.

Threat protection is available in the Plus feature plan. For more information, see [User pool feature plans](cognito-sign-in-feature-plans.md).

The following user pool options are the components of threat protection.

**Compromised credentials**  
Users reuse passwords for multiple user accounts. The compromised credentials feature of Amazon Cognito compiles data from public leaks of user names and passwords, and compares your users' credentials to lists of leaked credentials. Compromised credentials detection also checks for commonly-guessed passwords. You can check for compromised credentials in username-and-password standard authentication flows in user pools. Amazon Cognito doesn't detect compromised credentials in secure remote password (SRP) or custom authentication.  
You can choose the user actions that prompt a check for compromised credentials, and the action that you want Amazon Cognito to take in response. For sign-in, sign-up, and password-change events, Amazon Cognito can **Block sign-in**, or **Allow sign-in**. In both cases, Amazon Cognito generates a user activity log where you can find more information about the event.  
**Learn more**  
[Working with compromised-credentials detection](cognito-user-pool-settings-compromised-credentials.md)

**Adaptive authentication**  
Amazon Cognito can review location and device information from your users' sign-in requests and apply an automatic response to secure the user accounts in your user pool against suspicious activity. You can monitor user activity and automate responses to detected risk levels in username-password and SRP, and custom authentication.  
When you activate threat protection, Amazon Cognito assigns a risk score to user activity. You can assign an automatic response to suspicious activity: you can **Require MFA**, **Block sign-in**, or just log the activity details and risk score. You can also automatically send email messages that notify your user of the suspicious activity so that they can reset their password or take other self-guided actions.  
**Learn more**  
[Working with adaptive authentication](cognito-user-pool-settings-adaptive-authentication.md)

**IP address allowlist and denylist**  
With Amazon Cognito threat protection in **Full function** mode, you can create IP address **Always block** and **Always allow** exceptions. A session from an IP address on the **Always block** exception list isn't assigned a risk level by adaptive authentication, and can't sign in to your user pool.  

**Things to know about IP-address allowlists and blocklists**
+ You must express **Always block** and **Always allow** in CIDR format, for example `192.0.2.0/24`, a 24-bit mask, or `192.0.2.252/32`, a single IP address.
+  Devices with IP addresses in an **Always block** IP range can't sign up or sign in with SDK-based or managed login applications, but they can sign in with third-party IdPs. 
+ **Always allow** and **Always block** lists don't affect token refresh.
+ Amazon Cognito doesn't apply adaptive authentication MFA rules to devices from an **Always allow** IP range, but does apply compromised-credentials rules.

**Log export**  
Threat protection logs granular details of users' authentication requests to your user pool. These logs feature threat assessments, user information, and session metadata like location and device. You can create external archives of these logs for retention and analysis. Amazon Cognito user pools export threat protection logs to Amazon S3, CloudWatch Logs, and Amazon Data Firehose. For more information, see [Viewing and exporting user event history](cognito-user-pool-settings-adaptive-authentication.md#user-pool-settings-adaptive-authentication-event-user-history).  
**Learn more**  
[Exporting threat protection user activity logs](exporting-quotas-and-usage.md#exporting-quotas-and-usage-user-activity)

**Topics**
+ [

## Considerations and limitations for threat protection
](#cognito-user-pool-threat-protection-considerations)
+ [

## Turning on threat protection in user pools
](#cognito-user-pool-threat-protection-activating)
+ [

## Threat protection enforcement concepts
](#cognito-user-pool-settings-threat-protection-threat-protection-enforcement)
+ [

## Threat protection for standard authentication and custom authentication
](#cognito-user-pool-settings-threat-protection-threat-protection-types)
+ [

## Threat protection prerequisites
](#cognito-user-pool-threat-protection-prerequisites)
+ [

## Setting up threat protection
](#cognito-user-pool-settings-configure-threat-protection)
+ [

# Working with compromised-credentials detection
](cognito-user-pool-settings-compromised-credentials.md)
+ [

# Working with adaptive authentication
](cognito-user-pool-settings-adaptive-authentication.md)
+ [

# Collecting data for threat protection in applications
](user-pool-settings-viewing-threat-protection-app.md)

## Considerations and limitations for threat protection
<a name="cognito-user-pool-threat-protection-considerations"></a>

**Threat protection options differ between authentication flows**  
Amazon Cognito supports both adaptive authentication and compromised-credentials detection with the authentication flows `USER_PASSWORD_AUTH` and `ADMIN_USER_PASSWORD_AUTH`. You can enable only adaptive authentication for `USER_SRP_AUTH`. You can't use threat protection with federated sign-in.

**Always-block IPs contribute to request quotas**  
Blocked requests from IP addresses on an **Always block** exception list in your user pool contribute to the [request rate quotas](https://docs.aws.amazon.com/cognito/latest/developerguide/limits.html#category_operations) for your user pools.

**Threat protection doesn't apply rate limits**  
Some malicious traffic has the characteristic of a high volume of requests, like distributed denial of service (DDoS) attacks. The risk ratings that Amazon Cognito applies to incoming traffic are per-request and don't take request volume into account. Individual requests in a high-volume event might receive a risk score and an automated response for application-layer reasons that aren't related to their role in a volumetric attack. To implement defenses against volumetric attacks in your user pools, add AWS WAF web ACLs. For more information, see [Associate an AWS WAF web ACL with a user pool](user-pool-waf.md).

**Threat protection doesn't affect M2M requests**  
Client credentials grants are intended for machine-to-machine (M2M) authorization with no connection to user accounts. Threat protection only monitors user accounts and passwords in your user pool. To implement security features with your M2M activity, consider the capabilities of AWS WAF for monitoring request rates and content. For more information, see [Associate an AWS WAF web ACL with a user pool](user-pool-waf.md).

## Turning on threat protection in user pools
<a name="cognito-user-pool-threat-protection-activating"></a>

------
#### [ Amazon Cognito user pools console ]

**To activate threat protection for a user pool**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. If you haven't already, activate the Plus feature plan from the **Settings** menu.

1. Choose the **Threat protection** menu and select **Activate**.

1. Choose **Save changes**.

------
#### [ API ]

Set your feature plan to Plus in a [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request. The following partial example request body sets threat protection to full-function mode. For a complete example request, see [Examples](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html#API_CreateUserPool_Examples).

```
"UserPoolAddOns": { 
      "AdvancedSecurityMode": "ENFORCED"
   }
```

------

Threat protection is the collective term for the features that monitor user operations for signs of account takeover and automatically respond to secure affected user accounts. You can apply threat protection settings to users when they sign in with standard and custom authentication flows.

Threat protection [generates logs](cognito-user-pool-settings-adaptive-authentication.md#user-pool-settings-adaptive-authentication-event-user-history) that detail users' sign-in, sign-out, and other activity. You can export these logs to a third-party system. For more information, see [Viewing and exporting user event history](cognito-user-pool-settings-adaptive-authentication.md#user-pool-settings-adaptive-authentication-event-user-history).

## Threat protection enforcement concepts
<a name="cognito-user-pool-settings-threat-protection-threat-protection-enforcement"></a>

Threat protection starts out in an *audit-only* mode where your user pool monitors user activity, assigns risk levels, and generates logs. As a best practice, run in audit-only mode for two weeks or more before you enable *full-function mode*. Full-function mode includes a set of automatic reactions to detected risky activity and compromised passwords. With audit-only mode, you can monitor the threat assessments that Amazon Cognito is performing. You can also [provide feedback](cognito-user-pool-settings-adaptive-authentication.md#user-pool-settings-adaptive-authentication-feedback) that trains the feature on false positives and negatives.

You can configure threat protection enforcement at the user pool level to cover all app clients in the user pool, and at the level of individual app clients. App client threat-protection configurations override the user pool configuration. To configure threat protection for an app client, navigate to the app client settings from the **App clients** menu of your user pool in the Amazon Cognito console. There, you can **Use client-level settings** and configure enforcement exclusive to the app client.

Additionally, you can configure threat protection separately for standard and custom authentication types.

## Threat protection for standard authentication and custom authentication
<a name="cognito-user-pool-settings-threat-protection-threat-protection-types"></a>

The ways that you can configure threat protection depend on the type of authentication you're doing in your user pool and app clients. Each of the following types of authentication can have their own enforcement mode and automated responses.

**Standard authentication**  
*Standard authentication* is user sign-in, sign-out and password management with username-password flows and in managed login. Amazon Cognito threat protection monitors operations for indicators of risk when they sign in with managed login or use the following API `AuthFlow` parameters:    
**[InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-request-AuthFlow)**  
`USER_PASSWORD_AUTH`, `USER_SRP_AUTH`. The compromised credentials feature doesn't have access to passwords in `USER_SRP_AUTH` sign-in, and doesn't monitor or act on events with this flow.  
**[AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html#CognitoUserPools-AdminInitiateAuth-request-AuthFlow)**  
`ADMIN_USER_PASSWORD_AUTH`, `USER_SRP_AUTH`. The compromised credentials feature doesn't have access to passwords in `USER_SRP_AUTH` sign-in, and doesn't monitor or act on events with this flow.
You can set the **Enforcement mode** for standard authentication to **Audit only** or **Full function**. To disable threat monitoring for standard authentication, set threat protection to **No enforcement**.

**Custom authentication**  
*Custom authentication* is user sign-in with [custom challenge Lambda triggers](user-pool-lambda-challenge.md). You can't do custom authentication in managed login. Amazon Cognito threat protection monitors operations for indicators of risk when they sign in with the API `AuthFlow` parameter `CUSTOM_AUTH` of `InitiateAuth` and `AdminInitiateAuth`.  
You can set the **Enforcement mode** for custom authentication to **Audit only**, **Full function**, or **No enforcement**. The **No enforcement** option disables threat monitoring for custom authentication without affecting other threat protection features.

## Threat protection prerequisites
<a name="cognito-user-pool-threat-protection-prerequisites"></a>

Before you begin, you need the following:
+ A user pool with an app client. For more information, see [Getting started with user pools](getting-started-user-pools.md).
+ Set multi-factor authentication (MFA) to **Optional** in the Amazon Cognito console to use the risk-based adaptive authentication feature. For more information, see [Adding MFA to a user pool](user-pool-settings-mfa.md).
+ If you're using email notifications, go to the [Amazon SES console](https://console.aws.amazon.com/ses/home) to configure and verify an email address or domain to use with your email notifications. For more information about Amazon SES, see [Verifying Identities in Amazon SES](https://docs.aws.amazon.com/ses/latest/dg/verify-addresses-and-domains.html).

## Setting up threat protection
<a name="cognito-user-pool-settings-configure-threat-protection"></a>

Follow these instructions to set up user pool threat protection.

**Note**  
To set up a different threat protection configuration for an app client in the Amazon Cognito user pools console, select the app client from the **App clients** menu and choose **Use client-level settings**.

------
#### [ AWS Management Console ]

**To configure threat protection for a user pool**

1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Threat protection** menu and select **Activate**.

1. Choose the threat protection method that you want to configure: **Standard and custom authentication**. You can set different enforcement modes for custom and standard authentication, but they share the configuration of automated responses in **Full function** mode.

1. Select **Edit**.

1. Choose an **Enforcement mode**. To start responding to detected risks immediately, select **Full function** and configure the automated responses for compromised credentials and adaptive authentication. To gather information in user-level logs and in CloudWatch, select **Audit only** .

   We recommend that you keep threat protection in audit mode for two weeks before enabling actions. During this time, Amazon Cognito can learn the usage patterns of your app users and you can provide event feedback to adjust responses.

1. If you selected **Audit only**, choose **Save changes**. If you selected **Full function**:

   1. Select whether you will take **Custom** action or use or **Cognito defaults** to respond to suspected **Compromised credentials**. **Cognito defaults** are:

      1. Detect compromised credentials on **Sign-in**, **Sign-up**, and **Password change**.

      1. Respond to compromised credentials with the action **Block sign-in**.

   1. If you selected **Custom** actions for **Compromised credentials**, choose the user pool actions that Amazon Cognito will use for **Event detection** and the **Compromised credentials responses** that you would like Amazon Cognito to take. You can **Block sign-in** or **Allow sign-in** with suspected compromised credentials.

   1. Choose how to respond to malicious sign-in attempts under **Adaptive authentication**. Select whether you will take **Custom** action or use or **Cognito defaults** to respond to suspected malicious activity. When you select** Cognito defaults**, Amazon Cognito blocks sign-in at all risk levels and does not notify the user.

   1. If you selected **Custom** actions for **Adaptive authentication**, choose the **Automatic risk response** actions that Amazon Cognito will take in response to detected risks based on severity level. When you assign a response to a level of risk, you can't assign a less-restrictive response to a higher level of risk. You can assign the following responses to risk levels:

      1. **Allow sign-in** - Take no preventative action.

      1. **Optional MFA** - If the user has MFA configured, Amazon Cognito will always require the user to provide an additional SMS or time-based one-time password (TOTP) factor when they sign in. If the user does not have MFA configured, they can continue signing in normally.

      1. **Require MFA** - If the user has MFA configured, Amazon Cognito will always require the user to provide an additional SMS or TOTP factor when they sign in. If the user does not have MFA configured, Amazon Cognito will prompt them to set up MFA. Before you automatically require MFA for your users, configure a mechanism in your app to capture phone numbers for SMS MFA, or to register authenticator apps for TOTP MFA.

      1. **Block sign-in** - Prevent the user from signing in.

      1. **Notify user** - Send an email message to the user with information about the risk that Amazon Cognito detected and the response you have taken. You can customize email message templates for the messages you send.

1. If you chose **Notify user** in the previous step, you can customize your email delivery settings and email message templates for adaptive authentication.

   1. Under **Email configuration**, choose the **SES Region**, **FROM email address**, **FROM sender name**, and **REPLY-TO email address** that you want to use with adaptive authentication. For more information about integrating your user pool email messages with Amazon Simple Email Service, see [Email settings for Amazon Cognito user pools](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-email.html).  
![\[User event history\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/cup-advanced-security-ses-notification.png)

   1. Expand **Email templates** to customize adaptive authentication notifications with both HTML and plaintext versions of email messages. To learn more about email message templates, see [Message templates](cognito-user-pool-settings-message-customizations.md#cognito-user-pool-settings-message-templates).

1. Expand **IP address exceptions** to create an **Always-allow** or an **Always-block** list of IPv4 or IPv6 address ranges that will always be allowed or blocked, regardless of the threat protection risk assessment. Specify the IP address ranges in [CIDR notation](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation) (such as 192.168.100.0/24).

1. Choose **Save changes**.

------
#### [ API (user pool) ]

To set the threat protection configuration for a user pool, send a [SetRiskConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetRiskConfiguration.html) API request that includes a `UserPoolId` parameter, but not a `ClientId` parameter. The following is an example request body for a user pool. This risk configuration takes an escalating series of actions based on the severity of risk and notifies users at all risk levels. It applies a compromised-credentials block to sign-up operations.

To enforce this configuration, you must set `AdvancedSecurityMode` to `ENFORCED` in a separate [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request. For more information about the placeholder templates like `{username}` in this example, see [Configuring MFA, authentication, verification and invitation messages](cognito-user-pool-settings-message-customizations.md).

```
{
   "AccountTakeoverRiskConfiguration": { 
      "Actions": { 
         "HighAction": { 
            "EventAction": "MFA_REQUIRED",
            "Notify": true
         },
         "LowAction": { 
            "EventAction": "NO_ACTION",
            "Notify": true
         },
         "MediumAction": { 
            "EventAction": "MFA_IF_CONFIGURED",
            "Notify": true
         }
      },
      "NotifyConfiguration": { 
         "BlockEmail": { 
            "Subject": "You have been blocked for suspicious activity",
            "TextBody": "We blocked {username} at {login-time} from {ip-address}."
         },
         "From": "admin@example.com",
         "MfaEmail": { 
            "Subject": "Suspicious activity detected, MFA required",
            "TextBody": "Unexpected sign-in from {username} on device {device-name}. You must use MFA."
         },
         "NoActionEmail": { 
            "Subject": "Suspicious activity detected, secure your user account",
            "TextBody": "We noticed suspicious sign-in activity by {username} from {city}, {country} at {login-time}. If this was not you, reset your password."
         },
         "ReplyTo": "admin@example.com",
         "SourceArn": "arn:aws:ses:us-west-2:123456789012:identity/admin@example.com"
      }
   },
   "CompromisedCredentialsRiskConfiguration": { 
      "Actions": { 
         "EventAction": "BLOCK"
      },
      "EventFilter": [ "SIGN_UP" ]
   },
   "RiskExceptionConfiguration": { 
      "BlockedIPRangeList": [ "192.0.2.0/24","198.51.100.0/24" ],
      "SkippedIPRangeList": [ "203.0.113.0/24" ]
   },
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

------
#### [ API (app client) ]

To set the threat protection configuration for an app client, send a [SetRiskConfiguration](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetRiskConfiguration.html) API request that includes a `UserPoolId` parameter and a `ClientId` parameter. The following is an example request body for an app client. This risk configuration is more severe than the user pool configuration, blocking high-risk entries. It also applies compromised-credentials blocks to sign-up, sign-in, and password-reset operations.

To enforce this configuration, you must set `AdvancedSecurityMode` to `ENFORCED` in a separate [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html) or [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) API request. For more information about the placeholder templates like `{username}` in this example, see [Configuring MFA, authentication, verification and invitation messages](cognito-user-pool-settings-message-customizations.md).

```
{
   "AccountTakeoverRiskConfiguration": { 
      "Actions": { 
         "HighAction": { 
            "EventAction": "BLOCK",
            "Notify": true
         },
         "LowAction": { 
            "EventAction": "NO_ACTION",
            "Notify": true
         },
         "MediumAction": { 
            "EventAction": "MFA_REQUIRED",
            "Notify": true
         }
      },
      "NotifyConfiguration": { 
         "BlockEmail": { 
            "Subject": "You have been blocked for suspicious activity",
            "TextBody": "We blocked {username} at {login-time} from {ip-address}."
         },
         "From": "admin@example.com",
         "MfaEmail": { 
            "Subject": "Suspicious activity detected, MFA required",
            "TextBody": "Unexpected sign-in from {username} on device {device-name}. You must use MFA."
         },
         "NoActionEmail": { 
            "Subject": "Suspicious activity detected, secure your user account",
            "TextBody": "We noticed suspicious sign-in activity by {username} from {city}, {country} at {login-time}. If this was not you, reset your password."
         },
         "ReplyTo": "admin@example.com",
         "SourceArn": "arn:aws:ses:us-west-2:123456789012:identity/admin@example.com"
      }
   },
   "ClientId": "1example23456789",
   "CompromisedCredentialsRiskConfiguration": { 
      "Actions": { 
         "EventAction": "BLOCK"
      },
      "EventFilter": [ "SIGN_UP", "SIGN_IN", "PASSWORD_CHANGE" ]
   },
   "RiskExceptionConfiguration": { 
      "BlockedIPRangeList": [ "192.0.2.1/32","192.0.2.2/32" ],
      "SkippedIPRangeList": [ "192.0.2.3/32","192.0.2.4/32" ]
   },
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

------

# Working with compromised-credentials detection
<a name="cognito-user-pool-settings-compromised-credentials"></a>

Amazon Cognito can detect if a user's username and password have been compromised elsewhere. This can happen when users reuse credentials at more than one site, or when they use insecure passwords. Amazon Cognito checks [local users](cognito-terms.md#terms-localuser) who sign in with username and password, in managed login and with the Amazon Cognito API.

From the **Threat protection** menu of the Amazon Cognito console, you can configure **Compromised credentials**. Configure **Event detection** to choose the user events that you want to monitor for compromised credentials. Configure **Compromised credentials responses** to choose whether to allow or block the user if compromised credentials are detected. Amazon Cognito can check for compromised credentials during sign-in, sign-up, and password changes.

When you choose **Allow sign-in**, you can review Amazon CloudWatch Logs to monitor the evaluations that Amazon Cognito makes on user events. For more information, see [Viewing threat protection metrics](metrics-for-cognito-user-pools.md#user-pool-settings-viewing-threat-protection-metrics). When you choose **Block sign-in**, Amazon Cognito prevents sign-in by users who use compromised credentials. When Amazon Cognito blocks sign-in for a user, it sets the user's [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UserType.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UserType.html) to `RESET_REQUIRED`. A user with a `RESET_REQUIRED` status must change their password before they can sign in again.

Compromised credentials can check passwords for the following user activity.

**Sign-up**  
Your user pool checks the passwords that users transmit in the [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) operation and from the sign-up page of managed login for indicators of compromise.

**Sign-in**  
Your user pool checks passwords that users submit in password-based sign-in for indicators of compromise. Amazon Cognito can review the `ADMIN_USER_PASSWORD_AUTH` flow in [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html), the `USER_PASSWORD_AUTH` flow in [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html), and the `PASSWORD` option of the `USER_AUTH` flow in both.  
Currently, Amazon Cognito doesn't check for compromised credentials for sign-in operations with Secure Remote Password (SRP) flow. SRP sends a hashed proof of password during sign-in. Amazon Cognito doesn't have access to passwords internally, so it can only evaluate a password that your client passes to it in plaintext.

**Password reset**  
Your user pool checks for indicators of compromise in operations that set new user passwords with the [ConfirmForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html) self-service password reset operation. The code that's required for this operation is generated by [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html) and [AdminResetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html).  
Compromised credentials doesn't check temporary or permanent administrator-set passwords set with [AdminSetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html). However, with temporary passwords, your user pool checks passwords from responses to the `NEW_PASSWORD_REQUIRED` challenge in [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html) and [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html).

To add compromised credentials protections to your user pool, see [Advanced security with threat protection](cognito-user-pool-settings-threat-protection.md).

# Working with adaptive authentication
<a name="cognito-user-pool-settings-adaptive-authentication"></a>

With adaptive authentication, you can configure your user pool to block suspicious sign-ins or add second factor authentication in response to an increased risk level. For each sign-in attempt, Amazon Cognito generates a risk score for how likely the sign-in request is to be from a compromised source. This risk score is based on device and user factors that your application provides, and others that Amazon Cognito derives from the request. Some factors that contribute to the risk evaluation by Amazon Cognito are IP address, user agent, and geographical distance from other sign-in attempts. Adaptive authentication can turn on or require multi-factor authentication (MFA) for a user in your user pool when Amazon Cognito detects risk in a user's session, and the user hasn't yet chosen an MFA method. When you activate MFA for a user, they always receive a challenge to provide or set up a second factor during authentication, regardless of how you configured adaptive authentication. From your user's perspective, your app offers to help them set up MFA, and optionally Amazon Cognito prevents them from signing in again until they have configured an additional factor.

Amazon Cognito publishes metrics about sign-in attempts, their risk levels, and failed challenges to Amazon CloudWatch. For more information, see [Viewing threat protection metrics](metrics-for-cognito-user-pools.md#user-pool-settings-viewing-threat-protection-metrics).

To add adaptive authentication to your user pool, see [Advanced security with threat protection](cognito-user-pool-settings-threat-protection.md).

**Topics**
+ [

## Adaptive authentication overview
](#security-cognito-user-pool-settings-adaptive-authentication-overview)
+ [

## Adding user device and session data to API requests
](#user-pool-settings-adaptive-authentication-device-fingerprint)
+ [

## Viewing and exporting user event history
](#user-pool-settings-adaptive-authentication-event-user-history)
+ [

## Providing event feedback
](#user-pool-settings-adaptive-authentication-feedback)
+ [

## Sending notification messages
](#user-pool-settings-adaptive-authentication-messages)

## Adaptive authentication overview
<a name="security-cognito-user-pool-settings-adaptive-authentication-overview"></a>

From the **Threat protection** menu in the Amazon Cognito console, you can choose settings for adaptive authentication, including what actions to take at different risk levels and customization of notification messages to users. You can assign a global threat protection configuration to all of your app clients, but apply a client-level configuration to individual app clients.

Amazon Cognito adaptive authentication assigns one of the following risk levels to each user session: **High**, **Medium**, **Low**, or **No Risk**.

Consider your options carefully when you change your **Enforcement method** from **Audit-only** to **Full-function**. The automatic responses that you apply to risk levels influence the risk level that Amazon Cognito assigns to subsequent user sessions with the same characteristics. For example, after you choose to take no action, or **Allow**, user sessions that Amazon Cognito initially evaluates to be high-risk, Amazon Cognito considers similar sessions to have a lower risk.


**For each risk level, you can choose from the following options:**  

|  Option  |  Action  | 
| --- | --- | 
| Allow | Users can sign in without an additional factor. | 
| Optional MFA | Users who have a second factor configured must complete a second factor challenge to sign in. A phone number for SMS and a TOTP software token are the available second factors. Users without a second factor configured can sign in with only one set of credentials. | 
| Require MFA | Users who have a second factor configured must complete a second factor challenge to sign in. Amazon Cognito blocks sign-in for users who don't have a second factor configured. | 
| Block | Amazon Cognito blocks all sign-in attempts at the designated risk level. | 

**Note**  
You don't have to verify phone numbers to use them for SMS as a second authentication factor.

## Adding user device and session data to API requests
<a name="user-pool-settings-adaptive-authentication-device-fingerprint"></a>

You can collect and pass information about your user's session to Amazon Cognito threat protection when you use the API to sign them up, sign them in, and reset their password. This information includes your user's IP address and a unique device identifier.

You might have a intermediate network device between your users and Amazon Cognito, like a proxy service or an application server. You can collect users' context data and pass it to Amazon Cognito so that adaptive authentication calculates your risk based on the characteristics of the user endpoint, instead of your server or proxy. If your client-side app calls Amazon Cognito API operations directly, adaptive authentication automatically records the source IP address. However, it does not record other device information like the `user-agent` unless you also collect a device fingerprint.

Generate this data with the Amazon Cognito context data collection library and submit it to Amazon Cognito threat protection with the [ContextData](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ContextDataType.html) and [UserContextData](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UserContextDataType.html) parameters. The context data collection library is included in the AWS SDKs. For more information, see [Integrating Amazon Cognito authentication and authorization with web and mobile apps](cognito-integrate-apps.md). You can submit `ContextData` if you have the Plus feature plan. For more information, see [Setting up threat protection](cognito-user-pool-settings-threat-protection.md#cognito-user-pool-settings-configure-threat-protection).

When you call the following Amazon Cognito authenticated API operations from your application server, pass the IP of the user’s device in the `ContextData` parameter. In addition, pass your server name, server path, and encoded device-fingerprinting data.
+ [AdminInitiateAuth ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html)
+ [AdminRespondToAuthChallenge ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html)

When you call Amazon Cognito unauthenticated API operations, you can submit `UserContextData` to Amazon Cognito threat protection. This data includes a device fingerprint in the `EncodedData` parameter. You can also submit an `IpAddress` parameter in your `UserContextData` if you meet the following conditions:
+ Your user pool is on the Plus feature plan. For more information, see [User pool feature plans](cognito-sign-in-feature-plans.md).
+ Your app client has a client secret. For more information, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).
+ You have activated **Accept additional user context data** in your app client. For more information, see [Accepting additional user context data (AWS Management Console)](#user-pool-settings-adaptive-authentication-accept-user-context-data).

Your app can populate the `UserContextData` parameter with encoded device-fingerprinting data and the IP address of the user's device in the following Amazon Cognito unauthenticated API operations.
+ [InitiateAuth ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html)
+ [RespondToAuthChallenge ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html)
+ [SignUp ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html)
+ [ConfirmSignUp ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html)
+ [ForgotPassword ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html)
+ [ConfirmForgotPassword ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.html)
+ [ResendConfirmationCode ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html)

### Accepting additional user context data (AWS Management Console)
<a name="user-pool-settings-adaptive-authentication-accept-user-context-data"></a>

Your user pool accepts an IP address in a `UserContextData` parameter after you activate the **Accept additional user context data** feature. You don’t need to activate this feature if:
+ Your users only sign in with authenticated API operations like [AdminInitiateAuth ](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html), and you use the `ContextData` parameter.
+ You only want your unauthenticated API operations to send a device fingerprint, but not an IP address, to Amazon Cognito threat protection.

Update your app client as follows in the Amazon Cognito console to add support for additional user context data.

1. Sign in to the [Amazon Cognito console ](https://console.aws.amazon.com/cognito/home).

1. In the navigation pane, choose **Manage your User Pools**, and choose the user pool you want to edit.

1. Choose the **App clients** menu.

1. Choose or create an app client. For more information, see [ Configuring a user pool app client](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-idp-settings.html).

1. Choose **Edit** from the **App client information** container.

1. In the **Advanced authentication settings** for your app client, choose **Accept additional user context data**.

1. Choose **Save changes**.

To configure your app client to accept user context data in the Amazon Cognito API, set `EnablePropagateAdditionalUserContextData` to `true` in a [CreateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html) or [UpdateUserPoolClient](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) request. For information about how to work with threat protection in your web or mobile app, see [Collecting data for threat protection in applications](user-pool-settings-viewing-threat-protection-app.md). When your app calls Amazon Cognito from your server, collect user context data from the client side. The following is an example that uses the JavaScript SDK method `getData`.

```
var EncodedData = AmazonCognitoAdvancedSecurityData.getData(username, userPoolId, clientId);
```

When you design your app to use adaptive authentication, we recommend that you incorporate the latest Amazon Cognito SDK into your app.. The latest version of the SDK collects device fingerprinting information like device ID, model, and time zone. For more information about Amazon Cognito SDKs, see [Install a user pool SDK](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-sdk-links.html). Amazon Cognito threat protection only saves and assigns a risk score to events that your app submits in the correct format. If Amazon Cognito returns an error response, check that your request includes a valid secret hash and that the `IPaddress` parameter is a valid IPv4 or IPv6 address.

**`ContextData` and `UserContextData` resources**
+ AWS Amplify SDK for Android: [GetUserContextData](https://github.com/aws-amplify/aws-sdk-android/blob/main/aws-android-sdk-cognitoidentityprovider/src/main/java/com/amazonaws/mobileconnectors/cognitoidentityprovider/CognitoUserPool.java#L626)
+ AWS Amplify SDK for iOS: [userContextData](https://github.com/aws-amplify/aws-sdk-ios/blob/d3cd4fa0086b526f2f5c9c6c58880c9da7004c66/AWSCognitoIdentityProviderASF/AWSCognitoIdentityProviderASF.m#L21)
+ JavaScript: [amazon-cognito-advanced-security-data.min.js](https://amazon-cognito-assets.us-east-1.amazoncognito.com/amazon-cognito-advanced-security-data.min.js)

## Viewing and exporting user event history
<a name="user-pool-settings-adaptive-authentication-event-user-history"></a>

Amazon Cognito generates a log for each authentication event by a user when you enable threat protection. By default, you can view user logs in the **Users** menu in the Amazon Cognito console or with the [AdminListUserAuthEvents](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListUserAuthEvents.html) API operation. You can also export these events to an external system like CloudWatch Logs, Amazon S3, or Amazon Data Firehose. The export feature can make security information about user activity in your application more accessible to your own security-analysis systems.

**Topics**
+ [

### Viewing user event history (AWS Management Console)
](#user-pool-settings-adaptive-authentication-event-user-history-console)
+ [

### Viewing user event history (API/CLI)
](#user-pool-settings-adaptive-authentication-event-user-history-api-cli)
+ [

### Exporting user authentication events
](#user-pool-settings-adaptive-authentication-event-user-history-exporting)

### Viewing user event history (AWS Management Console)
<a name="user-pool-settings-adaptive-authentication-event-user-history-console"></a>

To see the sign-in history for a user, you can choose the user from the **Users** menu in the Amazon Cognito console. Amazon Cognito retains user event history for two years.

![\[User event history\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/cup-advanced-security-event-history.png)


Each sign-in event has an event ID. The event also has corresponding context data, such as location, device details, and risk detection results.

You can also correlate the event ID with the token that Amazon Cognito issued at the time that it recorded the event. The ID and access tokens include this event ID in their payload. Amazon Cognito also correlates refresh token use to the original event ID. You can trace the original event ID back to the event ID of the sign-in event that resulted in issuing the Amazon Cognito tokens. You can trace token usage within your system to a particular authentication event. For more information, see [Understanding user pool JSON web tokens (JWTs)](amazon-cognito-user-pools-using-tokens-with-identity-providers.md).

### Viewing user event history (API/CLI)
<a name="user-pool-settings-adaptive-authentication-event-user-history-api-cli"></a>

You can query user event history with the Amazon Cognito API operation [AdminListUserAuthEvents](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminListUserAuthEvents.html) or with the AWS Command Line Interface (AWS CLI) with [admin-list-user-auth-events](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-list-user-auth-events.html).

------
#### [ AdminListUserAuthEvents request ]

The following request body for `AdminListUserAuthEvents` returns the most recent activity log for one user.

```
{
  "UserPoolId": "us-west-2_EXAMPLE", 
  "Username": "myexampleuser", 
  "MaxResults": 1
}
```

------
#### [ admin-list-user-auth-events request ]

The following request for `admin-list-user-auth-events` returns the most recent activity log for one user.

```
aws cognito-idp admin-list-user-auth-events --max-results 1 --username myexampleuser --user-pool-id us-west-2_EXAMPLE
```

------
#### [ Response ]

Amazon Cognito returns the same JSON response body to both requests. The following is an example response for a managed login sign-in event that wasn't found to contain risk factors:

```
{
    "AuthEvents": [
        {
            "EventId": "[event ID]",
            "EventType": "SignIn",
            "CreationDate": "[Timestamp]",
            "EventResponse": "Pass",
            "EventRisk": {
                "RiskDecision": "NoRisk",
                "CompromisedCredentialsDetected": false
            },
            "ChallengeResponses": [
                {
                    "ChallengeName": "Password",
                    "ChallengeResponse": "Success"
                }
            ],
            "EventContextData": {
                "IpAddress": "192.168.2.1",
                "DeviceName": "Chrome 125, Windows 10",
                "Timezone": "-07:00",
                "City": "Bellevue",
                "Country": "United States"
            }
        }
    ],
    "NextToken": "[event ID]#[Timestamp]"
}
```

------

### Exporting user authentication events
<a name="user-pool-settings-adaptive-authentication-event-user-history-exporting"></a>

Configure your user pool to export user events from threat protection to an external system. The supported external systems–Amazon S3, CloudWatch Logs, and Amazon Data Firehose–might add costs to your AWS bill for data that you send or retrieve. For more information, see [Exporting threat protection user activity logs](exporting-quotas-and-usage.md#exporting-quotas-and-usage-user-activity).

------
#### [ AWS Management Console ]

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home).

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Log streaming** menu. Select **Edit**.

1. Under **Logging status**, select the checkbox next to **Activate user activity log export**.

1. Under **Logging destination**, choose the AWS service that you want to handle your logs: **CloudWatch log group**, **Amazon Data Firehose stream**, or **S3 bucket**.

1. Your selection will populate the resource selector with the corresponding resource type. Select a log group, stream, or bucket from the list. You can also select the **Create** button to navigate to the AWS Management Console for the selected service and create a new resource.

1. Select **Save changes**.

------
#### [ API ]

Choose one type of destination for your user activity logs.

The following is an example `SetLogDeliveryConfiguration` request body that sets a Firehose stream as the log destination.

```
{
   "LogConfigurations": [
      {
         "EventSource": "userAuthEvents",
         "FirehoseConfiguration": {
            "StreamArn": "arn:aws:firehose:us-west-2:123456789012:deliverystream/example-user-pool-activity-exported"
         },
         "LogLevel": "INFO"
      }
   ],
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

The following is an example `SetLogDeliveryConfiguration` request body that sets a Amazon S3 bucket as the log destination.

```
{
   "LogConfigurations": [
      {
         "EventSource": "userAuthEvents",
         "S3Configuration": { 
            "BucketArn": "arn:aws:s3:::amzn-s3-demo-logging-bucket"
         },
         "LogLevel": "INFO"
      }
   ],
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

The following is an example `SetLogDeliveryConfiguration` request body that sets a CloudWatch log group as the log destination.

```
{
   "LogConfigurations": [
      {
         "EventSource": "userAuthEvents",
         "CloudWatchLogsConfiguration": { 
            "LogGroupArn": "arn:aws:logs:us-west-2:123456789012:log-group:DOC-EXAMPLE-LOG-GROUP"
         },
         "LogLevel": "INFO"
      }
   ],
   "UserPoolId": "us-west-2_EXAMPLE"
}
```

------

## Providing event feedback
<a name="user-pool-settings-adaptive-authentication-feedback"></a>

Event feedback affects risk evaluation in real time and improves the risk evaluation algorithm over time. You can provide feedback on the validity of sign-in attempts through the Amazon Cognito console and API operations. 

**Note**  
Your event feedback influences the risk level that Amazon Cognito assigns to subsequent user sessions with the same characteristics.

In the Amazon Cognito console, choose a user from the **Users** menu and select **Provide event feedback**. You can review the event details and **Set as valid** or **Set as invalid**.

The console lists the sign-in history in user details in the **Users** menu. If you select an entry, you can mark the event as valid or not valid. You can also provide feedback through the user pool API operation [AdminUpdateAuthEventFeedback](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateAuthEventFeedback.html), and through the AWS CLI command [admin-update-auth-event-feedback](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-update-auth-event-feedback.html). 

When you select **Set as valid** in the Amazon Cognito console or provide a `FeedbackValue` value of `valid` in the API, you tell Amazon Cognito that you trust a user session where Amazon Cognito has evaluated some level of risk. When you select **Set as invalid** in the Amazon Cognito console or provide a `FeedbackValue` value of `invalid` in the API, you tell Amazon Cognito that you don't trust a user session, or you don't believe that Amazon Cognito evaluated a high-enough risk level.

## Sending notification messages
<a name="user-pool-settings-adaptive-authentication-messages"></a>

With threat protection, Amazon Cognito can notify your users of risky sign-in attempts. Amazon Cognito can also prompt users to select links to indicate if the sign-in was valid or not valid. Amazon Cognito uses this feedback to improve the risk detection accuracy for your user pool. 

**Note**  
Amazon Cognito only sends notification messages to users when their action generates an automated risk response: block sign-in, allow sign-in, set MFA to optional, or require MFA. Some requests might be assigned a level of risk but don't generate adaptive authentication automated risk responses; for these, your user pool doesn't send notifications. For example, incorrect passwords might be logged with a risk rating, but the response by Amazon Cognito is to fail sign-in, not to apply an adaptive authentication rule.

In the **Automatic risk response** section choose **Notify Users** for low, medium, or high-risk cases.

![\[Notify users\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/cup-adaptive-auth.png)


Amazon Cognito sends email notifications to your users regardless of whether they have verified their email address.

You can customize notification email messages, and provide both plaintext and HTML versions of these messages. To customize your email notifications, open **Email templates** from **Adaptive authentication messages** in your threat protection configuration. To learn more about email templates, see [Message templates](cognito-user-pool-settings-message-customizations.md#cognito-user-pool-settings-message-templates).

# Collecting data for threat protection in applications
<a name="user-pool-settings-viewing-threat-protection-app"></a>

Amazon Cognito [adaptive authentication](cognito-user-pool-settings-adaptive-authentication.md) evaluates risk levels for attempted account takeover from contextual details of users' sign-in attempts. Your application must add *context data* to API requests so that Amazon Cognito threat protection can more accurately evaluate risk. Context data is information like IP address, browser agent, device information, and request headers that provides contextual information about how a user connected to your user pool.

The central responsibility of an application that submits this context to Amazon Cognito is an `EncodedData` parameter in authentication requests to user pools. To add this data to your requests, you can implement Amazon Cognito with an SDK that automatically generates this information for you, or you can implement a module for JavaScript, iOS, or Android that collects this data. *Client-only* applications that make direct requests to Amazon Cognito must implement AWS Amplify SDKs. *Client-server* applications that have an intermediate server or API component must implement a separate SDK module.

In the following scenarios, your authentication front end manages user context data collection without any additional configuration:
+ Managed login automatically collects and submits context data to threat protection.
+ All AWS Amplify libraries have context-data collection built into their authentication methods.

## Submitting user context data in client-only applications with Amplify
<a name="user-pool-settings-viewing-threat-protection-app-amplify"></a>

![\[An overview of data collection for threat protection in an Amplify application.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/user-pools-asf-amplify-data-collection.png)


Amplify SDKs support mobile clients that authenticate with Amazon Cognito directly. Clients of this kind make direct API requests to Amazon Cognito public API operations. Amplify clients automatically collect context data for threat protection by default.

Amplify applications with JavaScript are an exception. They require the addition of a [JavaScript module](#user-pool-settings-viewing-threat-protection-app-additional-resources-js) that collects user context data.

Typically, an application in this configuration uses unauthenticated API operations like [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html). The [UserContextData](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UserContextDataType.html) object helps evaluate risks more accurately for these operations. The Amplify SDKs add device and session information to an `EncodedData`parameter of `UserContextData`.

## Collecting context data in client-server applications
<a name="user-pool-settings-viewing-threat-protection-app-server-side"></a>

Some applications have a front-end tier that collects user authentication data and an application back-end tier that submits authentication requests to Amazon Cognito. This is a common architecture in webservers and applications backed by microservices. In these applications, you must import a public context-data collection library.

![\[An overview of server-side authentication with threat protection context data in JavaScript.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/user-pools-asf-non-amplify-data-collection.png)


Typically, an application server in this configuration uses authenticated API operations like [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) and [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html). The [ContextData](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html#CognitoUserPools-AdminInitiateAuth-request-ContextData) object helps Amazon Cognito evaluate risks more accurately for these operations. . The contents of `ContextData` are the encoded data that your front end passed to your server, and additional details from the user's HTTP request to your server. These additional context details, like the HTTP headers and IP address, provide your application server with the characteristics of the user's environment.

Your application server might also do sign-in with unauthenticated API operations like [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) and [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html). The [UserContextData](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html#CognitoUserPools-InitiateAuth-request-UserContextData) object informs threat protection risk analysis in these operations. The operations in the available public context data collection libraries add security information to the `EncodedData` parameter in authentication requests. Additionally, configure your user pool to accept additional context data and add the user’s source IP to the `IpAddress` parameter of `UserContextData`.

**To add context data to client-server applications**

1. In your front-end application, collect encoded context data from the client with an [iOS, Android, or JavaScript module](#user-pool-settings-viewing-threat-protection-app-additional-resources).

1. Pass the encoded data and the details of the authentication request to your application server.

1. In your application server, extract the user's IP address, relevant HTTP headers, requested server name, and requested path from the HTTP request. Populate these values to the [ContextData](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html#CognitoUserPools-AdminInitiateAuth-request-ContextData) parameter of your API request to Amazon Cognito.

1. Populate the `EncodedData` parameter of `ContextData` in your API request with the encoded device data that your SDK module collected. Add this context data to the authentication request.

## Context data libraries for client-server applications
<a name="user-pool-settings-viewing-threat-protection-app-additional-resources"></a>

### JavaScript
<a name="user-pool-settings-viewing-threat-protection-app-additional-resources-js"></a>

The `amazon-cognito-advanced-security-data.min.js` module collects `EncodedData` that you can pass to your application server.

Add the `amazon-cognito-advanced-security-data.min.js` module to your JavaScript configuration. Replace `<region>` with an AWS Region from the following list: `us-east-1`, `us-east-2`, `us-west-2`, `eu-west-1`, `eu-west-2`, or `eu-central-1`.

```
<script src="https://amazon-cognito-assets.<region>.amazoncognito.com/amazon-cognito-advanced-security-data.min.js"></script>
```

To generate an `encodedContextData` object that you can use in the `EncodedData` parameter, add the following to your JavaScript application source:

```
var encodedContextData = AmazonCognitoAdvancedSecurityData.getData(_username, _userpoolId, _userPoolClientId);
```

### iOS/Swift
<a name="user-pool-settings-viewing-threat-protection-app-additional-resources-ios"></a>

To generate context data, iOS applications can integrate the [Mobile SDK for iOS](https://github.com/aws-amplify/aws-sdk-ios/tree/main) module [AWSCognitoIdentityProviderASF](https://github.com/aws-amplify/aws-sdk-ios/tree/main/AWSCognitoIdentityProviderASF).

To collect encoded context data for threat protection, add the following snippet to your application:

```
import AWSCognitoIdentityProviderASF

let deviceId = getDeviceId()
let encodedContextData = AWSCognitoIdentityProviderASF.userContextData(
                            userPoolId, 
                            username: username, 
                            deviceId: deviceId, 
                            userPoolClientId: userPoolClientId)
                                
/**
 * Reuse DeviceId from keychain or generate one for the first time.
 */
func getDeviceId() -> String {
    let deviceIdKey = getKeyChainKey(namespace: userPoolId, key: "AWSCognitoAuthAsfDeviceId")
    
   if let existingDeviceId = self.keychain.string(forKey: deviceIdKey) {
        return existingDeviceId
    }

    let newDeviceId = UUID().uuidString
    self.keychain.setString(newDeviceId, forKey: deviceIdKey)
    return newDeviceId
}

/**
 * Get a namespaced keychain key given a namespace and key
 */    
func getKeyChainKey(namespace: String, key: String) -> String {
    return "\(namespace).\(key)"
}
```

### Android
<a name="user-pool-settings-viewing-threat-protection-app-additional-resources-android"></a>

To generate context data, Android applications can integrate the [Mobile SDK for Android](https://github.com/aws-amplify/aws-sdk-android/tree/main) module [aws-android-sdk-cognitoidentityprovider-asf](https://github.com/aws-amplify/aws-sdk-android/tree/main/aws-android-sdk-cognitoidentityprovider-asf).

To collect encoded context data for threat protection, add the following snippet to your application:

```
UserContextDataProvider provider = UserContextDataProvider.getInstance();
// context here is android application context.
String encodedContextData = provider.getEncodedContextData(context, username, userPoolId, userPoolClientId);
```

# Associate an AWS WAF web ACL with a user pool
<a name="user-pool-waf"></a>

AWS WAF is a web application firewall. With an AWS WAF web access control list (web ACL), you can protect your user pool from unwanted requests to your classic hosted UI, managed login, and Amazon Cognito API service endpoints. A web ACL gives you fine-grained control over all of the HTTPS web requests that your user pool responds to. For more information about AWS WAF web ACLs, see [Managing and using a web access control list (web ACL)](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html) in the *AWS WAF Developer Guide*.

When you have an AWS WAF web ACL associated with a user pool, Amazon Cognito forwards selected non-confidential headers and contents of requests from your users to AWS WAF. AWS WAF inspects the contents of the request, compares it to the rules that you specified in your web ACL, and returns a response to Amazon Cognito.

## Things to know about AWS WAF web ACLs and Amazon Cognito
<a name="user-pool-waf-things-to-know"></a>
+ You can't configure web ACL rules to match on personally identifiable information (PII) in user pool requests, for example usernames, passwords, phone numbers, or email addresses. This data won't be available to AWS WAF. Instead, configure your web ACL rules to match on session data in the headers, path, and body like IP addresses, browser agents, and requested API operations.
+ Web ACL rule conditions can only return custom block responses to users' **first** request to a user-interactive managed login page. When subsequent connections match a custom block response condition, they return your custom status code, header, and redirect responses, but a default block message.
+ Requests blocked by AWS WAF do not count towards the request rate quota for any request type. The AWS WAF handler is called before the API-level throttling handlers.
+ When you create a web ACL, a small amount of time passes before the web ACL has fully propagated and is available to Amazon Cognito. The propagation time can be from a few seconds to a number of minutes. AWS WAF returns a [https://docs.aws.amazon.com/waf/latest/APIReference/API_AssociateWebACL.html#API_AssociateWebACL_Errors](https://docs.aws.amazon.com/waf/latest/APIReference/API_AssociateWebACL.html#API_AssociateWebACL_Errors) when you attempt to associate a web ACL before it has fully propagated.
+ You can associate one web ACL with each user pool.
+ Your request might result in a payload that is larger than the limits of what AWS WAF can inspect. See [Oversize request component handling](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statement-oversize-handling.html) in the *AWS WAF Developer Guide* to learn how to configure how AWS WAF handles oversize requests from Amazon Cognito.
+ You can’t associate a web ACL that uses AWS WAF [Fraud Control account takeover prevention (ATP)](https://docs.aws.amazon.com/waf/latest/developerguide/waf-atp.html) with an Amazon Cognito user pool. The ATP feature is in the `AWS-AWSManagedRulesATPRuleSet` managed rule group. Before you associate a web ACL with a user pool, be sure that it doesn’t use this managed rule group.
+ When you have an AWS WAF web ACL associated with a user pool, and a rule in your web ACL presents a CAPTCHA, this can cause an unrecoverable error in managed login TOTP registration. To create a rule that has a CAPTCHA action and doesn't affect managed login TOTP, see [Configuring your AWS WAF web ACL for managed login TOTP MFA](user-pool-settings-mfa-totp.md#totp-waf).

AWS WAF inspects requests to the following endpoints.

**Managed login and the classic hosted UI**  
Requests to all endpoints in the [User pool endpoints and managed login reference](cognito-userpools-server-contract-reference.md).

**Public API operations**  
Requests from your app to the Amazon Cognito API that don't use AWS credentials to authorize. This includes API operations like [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html), [RespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html), and [GetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html). The API operations that are in scope of AWS WAF don't require authentication with AWS credentials. They are unauthenticated, or authorized with a session string or access token. For more information, see [List of API operations grouped by authorization model](authentication-flows-public-server-side.md#user-pool-apis-auth-unauth).

You can configure the rules in your web ACL with rule actions that **Count**, **Allow**, **Block**, or present a **CAPTCHA** in response to a request that matches a rule. For more information, see [AWS WAF rules](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rules.html) in the *AWS WAF Developer Guide*. Depending on the rule action, you can customize the response that Amazon Cognito returns to your users.

**Important**  
Your options to customize the error response depends on the way you make an API request.  
You can customize the error code and response body of managed login requests. You can only present a CAPTCHA for your user to solve in managed login.
For requests that you make with the Amazon Cognito[ user pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html), you can customize the response body of a request that receives a **Block** response. You can also specify a custom error code in the range 400–499.
The AWS Command Line Interface (AWS CLI) and the AWS SDKs return a `ForbiddenException` error to requests that produce a **Block** or **CAPTCHA** response.

## Associating a web ACL with your user pool
<a name="user-pool-waf-setting-up"></a>

To work with a web ACL in your user pool, your AWS Identity and Access Management (IAM) principal must have the following Amazon Cognito and AWS WAF permissions. For information about AWS WAF permissions, see [AWS WAF API permissions](https://docs.aws.amazon.com/waf/latest/developerguide/waf-api-permissions-ref.html) in the *AWS WAF Developer Guide*.

------
#### [ JSON ]

****  

```
{
	"Version":"2012-10-17",		 	 	 
	"Statement": [
		{
			"Sid": "AllowWebACLUserPool",
			"Effect": "Allow",
			"Action": [
				"cognito-idp:ListResourcesForWebACL",
				"cognito-idp:GetWebACLForResource",
				"cognito-idp:AssociateWebACL"
			],
			"Resource": [
				"arn:aws:cognito-idp:*:123456789012:userpool/*"
			]
		},
		{
			"Sid": "AllowWebACLUserPoolWAFv2",
			"Effect": "Allow",
			"Action": [
				"wafv2:ListResourcesForWebACL",
				"wafv2:AssociateWebACL",
				"wafv2:DisassociateWebACL",
				"wafv2:GetWebACLForResource"
			],
			"Resource": "arn:aws:wafv2:*:123456789012:*/webacl/*/*"
		},
		{
			"Sid": "DisassociateWebACL1",
			"Effect": "Allow",
			"Action": "wafv2:DisassociateWebACL",
			"Resource": "*"
		},
		{
			"Sid": "DisassociateWebACL2",
			"Effect": "Allow",
			"Action": [
				"cognito-idp:DisassociateWebACL"
			],
			"Resource": [
				"arn:aws:cognito-idp:*:123456789012:userpool/*"
			]
		}
	]
}
```

------

Though you must grant IAM permissions, the listed actions are permission-only and don't correspond to any [API operation](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html).

**To activate AWS WAF for your user pool and associate a web ACL**

1. Sign in to the [Amazon Cognito console ](https://console.aws.amazon.com/cognito/home).

1. In the navigation pane, choose **User Pools**, and choose the user pool you want to edit.

1. Choose the **AWS WAF** tab in the **Security** section.

1. Choose **Edit**.

1. Select **Use AWS WAF with your user pool**.  
![\[Screenshot of the AWS WAF dialog box with Use AWS WAF with your user pool selected.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/cup-WAF-console.png)

1. Choose an **AWS WAF Web ACL** that you already created, or choose **Create web ACL in AWS WAF** to create one in a new AWS WAF session in the AWS Management Console.

1. Choose **Save changes**.

To programmatically associate a web ACL with your user pool in the AWS Command Line Interface or an SDK, use [AssociateWebACL](https://docs.aws.amazon.com/waf/latest/APIReference/API_AssociateWebACL.html) from the AWS WAF API. Amazon Cognito doesn't have a separate API operation that associates a web ACL.

## Testing and logging AWS WAF web ACLs
<a name="user-pool-waf-evaluating-and-logging"></a>

When you set a rule action to **Count** in your web ACL, AWS WAF adds the request to a count of requests that match the rule. To test a web ACL with your user pool, set rule actions to **Count** and consider the volume of requests that match each rule. For example, if a rule that you want to set to a **Block** action matches a large number of requests that you determine to be normal user traffic, you might need to reconfigure your rule. For more information, see [Testing and tuning your AWS WAF protections](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-testing.html) in the *AWS WAF Developer Guide.*

You can also configure AWS WAF to log request headers to an Amazon CloudWatch Logs log group, an Amazon Simple Storage Service (Amazon S3) bucket, or an Amazon Data Firehose. You can identify the Amazon Cognito requests that you make with the user pools API by the `x-amzn-cognito-client-id` and `x-amzn-cognito-operation-name`. Managed login requests only include the `x-amzn-cognito-client-id` header. For more information, see [Logging web ACL traffic](https://docs.aws.amazon.com/waf/latest/developerguide/logging.html) in the *AWS WAF Developer Guide*.

AWS WAF web ACLs are available in all user pool [feature plans](cognito-sign-in-feature-plans.md). The security features of AWS WAF complement Amazon Cognito threat protection. You can activate both features in a user pool. AWS WAF bills separately for the inspection of user pool requests. For more information, see [AWS WAF Pricing](https://aws.amazon.com/waf/pricing).

Logging AWS WAF request data is subject to additional billing by the service where you target your logs. For more information, see [Pricing for logging web ACL traffic information](https://docs.aws.amazon.com/waf/latest/developerguide/logging.html#logging-pricing) in the *AWS WAF Developer Guide*.

# User pool case sensitivity
<a name="user-pool-case-sensitivity"></a>

Amazon Cognito user pools that you create in the AWS Management Console are case insensitive by default. When a user pool is case insensitive, *user@example.com* and *User@example.com* refer to the same user. When usernames in a user pool are case insensitive, the `preferred_username` and `email` attributes also are case insensitive.

Case insensitivity applies not only to attribute inputs, but outputs too. Mixed-case attribute values in case-insensitive user pools are flattened to lowercase in user pool text output. Examples of user pool text output are [userInfo](userinfo-endpoint.md) responses, user query responses like the output of [GetUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html), and input events to [Lambda triggers](cognito-user-pools-working-with-lambda-triggers.md).

To account for user pool case sensitivity settings, identify users in your app code based on an alternative user attribute. Because the case of a username, preferred username, or email address attribute can vary in different user profiles, refer instead to the `sub` attribute. You can also create an immutable custom attribute in your user pool, and assign your own unique identifier value to the attribute in each new user profile. When you first create a user, you can write a value to the immutable custom attribute that you created.

**Note**  
Regardless of the case sensitivity settings of your user pool, Amazon Cognito requires that a federated user from a SAML or OIDC identity provider (IdP) pass a unique and case-sensitive `NameId` or `sub` claim. For more information about unique identifier case sensitivity and SAML IdPs, see [Implement SP-initated SAML sign-in](cognito-user-pools-SAML-session-initiation.md#cognito-user-pools-saml-idp-authentication).

Creating a case-sensitive user pool  
If you create resources with the AWS Command Line Interface (AWS CLI) and API operations such as [CreateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html), you must set the Boolean `CaseSensitive` parameter to `false`. This setting creates a case-insensitive user pool. If you do not specify a value, `CaseSensitive` defaults to `true`. User pools that you create in the Amazon Cognito console are not case-sensitive. To produce a case-sensitive user pool, you must use the `CreateUserPool` operation. Before February 12, 2020, user pools defaulted to case sensitive regardless of platform.   
In the **Sign-in** menu of the AWS Management Console and in the `UsernameConfiguration` property of [DescribeUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UserPoolType.html#CognitoUserPools-Type-UserPoolType-UsernameConfiguration), you can review the case sensitivity settings for each user pool in your account.

Migrating to a new user pool  
Because of potential conflicts between user profiles, you can't change an Amazon Cognito user pool from case-sensitive to case-insensitive. Instead, migrate your users to a new user pool. You must build migration code to resolve case-related conflicts. This code must either return a unique new user or reject the sign-in attempt when it detects a conflict. In a new case-insensitive user pool, assign a [Migrate user Lambda trigger](user-pool-lambda-migrate-user.md). The AWS Lambda function can create users in the new case-insensitive user pool. When the user fails sign-in with the case-insensitive user pool, the Lambda function finds and duplicates the user from the case-sensitive user pool. You can also activate a migrate user Lambda trigger on [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html) events. Amazon Cognito passes user information and event metadata from the sign-in or password-recovery action to your Lambda function. You can use event data to manage conflicts between usernames and email addresses when your function creates the new user in your case-insensitive user pool. These conflicts are between usernames and email addresses that would be unique in a case-sensitive user pool, but identical in a case-insensitive user pool.   
For more information about how to use a migrate user Lambda trigger between Amazon Cognito user pools, see [Migrating Users to Amazon Cognito user pools](https://aws.amazon.com/blogs/mobile/migrating-users-to-amazon-cognito-user-pools/) in the AWS blog.

# User pool deletion protection
<a name="user-pool-settings-deletion-protection"></a>

To make it so that your administrators don't accidentally delete your user pool, activate deletion protection. With deletion protection active, you must confirm that you want to delete your user pool before you delete it. When you delete a user pool in the AWS Management Console, you can deactivate deletion protection at the same time. When you accept the prompt to deactivate deletion protection and confirm your intention to delete, as shown in the following image, Amazon Cognito deletes your user pool.

![\[A screenshot from the AWS Management Console showing a prompt to delete a user pool with an included prompt to also deactivate deletion protection.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/amazon-cognito-delete-user-pool-deactivate-deletion-protection.png)


When you want to delete a user pool with an Amazon Cognito API request, you must first change `DeletionProtection` to `Inactive` in an [UpdateUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPool.html) request. If you don't deactivate deletion protection, Amazon Cognito returns an `InvalidParameterException` error. After you deactivate deletion protection, you can delete the user pool in a [DeleteUserPool](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DeleteUserPool.html) request.

Amazon Cognito activates **Deletion protection** by default when you create a new user pool in the AWS Management Console. When you create a user pool with the `CreateUserPool` API, deletion protection is inactive by default. To use this feature in user pools that you create with the AWS CLI or an AWS SDK, set the `DeletionProtection` parameter to `True`.

You can activate or deactivate deletion protection status in the **Deletion protection** container in the **Settings** menu in the Amazon Cognito console.

# To configure deletion protection


1. Go to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). You might be prompted for your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or [create a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html).

1. Choose the **Settings** menu and navigate to the **Deletion Protection** tab. Select **Activate** or **Deactivate**.

1. Confirm your choice in the next dialogue.

# Managing user existence error responses
<a name="cognito-user-pool-managing-errors"></a>

Amazon Cognito supports customizing error responses returned by user pools. Custom error responses are available for user creation and authentication, password recovery, and confirmation operations.

Use the `PreventUserExistenceErrors` setting of a user pool app client to enable or disable user existence related errors. When you create a new app client with the Amazon Cognito user pools API, `PreventUserExistenceErrors` is `LEGACY`, or disabled, by default. In the Amazon Cognito console, the option **Prevent user existence errors **—a setting of `ENABLED` for `PreventUserExistenceErrors`—is selected by default. To update your `PreventUserExistenceErrors` configuration, do one of the following:
+ Change the value of `PreventUserExistenceErrors` between `ENABLED` and `LEGACY` in an [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserPoolClient.html) API request.
+ Edit your app client in the Amazon Cognito console and change the state of **Prevent user existence errors** between selected (`ENABLED`) and deselected (`LEGACY`).

When this property has a value of `LEGACY`, your app client returns a `UserNotFoundException` error response when a user attempts to sign in with a username that doesn't exist in your user pool.

When this property has a value of `ENABLED`, your app client doesn't disclose the nonexistence of a user account in your user pool with a `UserNotFoundException` error. A `PreventUserExistenceErrors` configuration of `ENABLED` has the following effects when you submit a request for a username that doesn't exist:
+ Amazon Cognito responds with nonspecific information to API requests where its response might otherwise disclose that a valid user exists.
+ Amazon Cognito returns a generic authentication failure response to forgot-password requests, and to authentication requests with authentication flows *except* for [choice-based authentication](authentication-flows-selection-sdk.md#authentication-flows-selection-choice) (`USER_AUTH`)—for example, `USER_SRP_AUTH` or `CUSTOM_AUTH`. The error response tells you the user name or password is incorrect.
+ Amazon Cognito responds to requests for choice-based authentication with a random selection from the challenge types allowed for the user pool. Your user pool might return a passkey, one-time password, or password challenge.
+ The behavior of Amazon Cognito account confirmation and password recovery APIs alternates between returning a response indicating a code was sent to a simulated delivery medium and returning an `InvalidParameterException` error.

The following information details the behaviors of user pool operations when `PreventUserExistenceErrors` is set to `ENABLED`.

## Authentication and user creation operations
<a name="cognito-user-pool-managing-errors-user-auth"></a>

You can configure error responses in username-password, and Secure Remote Password (SRP) authentication. You can also customize the errors that you return with custom authentication. Choice-based authentication is unaffected by your `PreventUserExistenceErrors` configuration.User-existence disclosure details in authentication flows

**Choice-based authentication**  
In the `USER_AUTH` choice-based authentication flow, Amazon Cognito returns a challenge from the primary authentication factors that are available, depending on your user pool configuration and users' attributes. This authentication flow can return password, secure remote password (SRP), WebAuthn (passkey), SMS one-time password (OTP), or email OTP challenges. With `PreventUserExistenceErrors` active, Amazon Cognito issues a challenge to nonexistent users to complete one or more of the available forms of authentication. With `PreventUserExistenceErrors` inactive, Amazon Cognito returns a `UserNotFound` exception.

**Username and password authentication**  
The authentication flows `ADMIN_USER_PASSWORD_AUTH`, `USER_PASSWORD_AUTH`, and the `PASSWORD` flow of `USER_AUTH` return a `NotAuthorizedException` with the message `Incorrect username or password` when `PreventUserExistenceErrors` is active. When `PreventUserExistenceErrors` is inactive, these flows return `UserNotFoundException`.

**Secure Remote Password (SRP) based authentication**  
As a best practice, only implement `PreventUserExistenceErrors` with `USER_SRP_AUTH` or the `PASSWORD_SRP` flow of `USER_AUTH` in user pools without email address, phone number, or preferred username [alias attributes](user-pool-settings-attributes.md#user-pool-settings-aliases). Users with alias attributes might not be subject to user-existence suppression in the SRP authentication flow. Username-password authentication flows—`ADMIN_USER_PASSWORD_AUTH`, `USER_PASSWORD_AUTH`, and the `USER_AUTH` `PASSWORD` challenge—fully suppress the existence of users from alias attributes.  
When someone attempts SRP sign-in with a username that isn't known to your app client, Amazon Cognito returns a simulated response in the first step as described in [RFC 5054](https://tools.ietf.org/html/rfc5054#section-2.5.1.3). Amazon Cognito returns the same salt and an internal user ID in [UUID](cognito-terms.md#terms-uuid) format for the same username and user pool combination. When you send a `RespondToAuthChallenge` API request with proof of password, Amazon Cognito returns a generic `NotAuthorizedException` error when either username or password is incorrect. For more information about implementation of SRP authentication, see [Sign-in with persistent passwords and secure payload](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-srp).  
You can simulate a generic response with username and password authentication if you are using verification-based alias attributes, and the immutable username isn't formatted as a [UUID](cognito-terms.md#terms-uuid).

**Custom authentication challenge Lambda trigger**  
Amazon Cognito invokes the [custom authentication challenge Lambda triggers](user-pool-lambda-challenge.md) when users attempt to sign in with the `CUSTOM_AUTH` authentication flow, but their username isn't found. The input event includes a boolean parameter named `UserNotFound` with a value of `true` for any nonexistent user. This parameter appears in the request events that your user pool sends to the create, define, and verify auth challenge Lambda functions that make up the custom-authentication architecture. When you examine this indicator in the logic of your Lambda function, you can simulate custom authentication challenges for a user that doesn't exist.

**Pre authentication Lambda trigger**  
Amazon Cognito invokes the [pre authentication trigger](user-pool-lambda-pre-authentication.md) when users attempt to sign in but their username isn't found. The input event includes a `UserNotFound` parameter with a value of `true` for any nonexistent user.

The following list describes the effect of `PreventUserExistenceErrors` on user account creation.User-existence disclosure details in user creation flows

**SignUp**  
The `SignUp` operation always returns `UsernameExistsException` when a username is already taken. If you don't want Amazon Cognito to return a `UsernameExistsException` error for email addresses and phone numbers when you sign up users in your app, use verification-based alias attributes. For more information about aliases, see [Customizing sign-in attributes](user-pool-settings-attributes.md#user-pool-settings-aliases).  
For an example of how Amazon Cognito can prevent the use of `SignUp` API requests to discover users in your user pool, see [Preventing `UsernameExistsException` errors for email addresses and phone numbers on sign-up](#cognito-user-pool-managing-errors-prevent-userexistence-errors).

**Imported users**  
If `PreventUserExistenceErrors` is enabled, during authentication of imported users a generic `NotAuthorizedException` error is returned indicating either the username or password was incorrect instead of returning `PasswordResetRequiredException`. See [Requiring imported users to reset their passwords](cognito-user-pools-using-import-tool.md#cognito-user-pools-using-import-tool-password-reset) for more information.

**Migrate user Lambda trigger**  
Amazon Cognito returns a simulated response for users that don't exist when an empty response was set in the original event context by the Lambda trigger. For more information, see [Importing users with a user migration Lambda trigger](cognito-user-pools-import-using-lambda.md). 

### Preventing `UsernameExistsException` errors for email addresses and phone numbers on sign-up
<a name="cognito-user-pool-managing-errors-prevent-userexistence-errors"></a>

The following example demonstrates how, when you configure alias attributes in your user pool, you can keep duplicate email addresses and phone numbers from generating `UsernameExistsException` errors in response to `SignUp` API requests. You must have created your user pool with email address or phone number as an alias attribute. For more information, see the *Customizing sign-in attributes* section of [User pool attributes](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases).

1. Jie signs up for a new username, and also provides the email address `jie@example.com`. Amazon Cognito sends a code to their email address.

   **Example AWS CLI command**

   ```
   aws cognito-idp sign-up --client-id 1234567890abcdef0 --username jie --password PASSWORD --user-attributes Name="email",Value="jie@example.com"
   ```

   **Example response**

   ```
   {
       "UserConfirmed": false, 
       "UserSub": "<subId>", 
       "CodeDeliveryDetails": {
           "AttributeName": "email", 
           "Destination": "j****@e****", 
           "DeliveryMedium": "EMAIL"
       }
   }
   ```

1. Jie provides the code sent to them to confirm their ownership of the email address. This completes their registration as a user.

   **Example AWS CLI command**

   ```
   aws cognito-idp confirm-sign-up --client-id 1234567890abcdef0 --username=jie --confirmation-code xxxxxx
   ```

1. Shirley registers a new user account and provides the email address `jie@example.com`. Amazon Cognito doesn't return a `UsernameExistsException` error, and sends a confirmation code to Jie's email address.

   **Example AWS CLI command**

   ```
   aws cognito-idp sign-up --client-id 1234567890abcdef0 --username shirley --password PASSWORD --user-attributes Name="email",Value="jie@example.com"
   ```

   **Example response**

   ```
   {
       "UserConfirmed": false, 
       "UserSub": "<new subId>", 
       "CodeDeliveryDetails": {
           "AttributeName": "email", 
           "Destination": "j****@e****", 
           "DeliveryMedium": "EMAIL"
       }
   }
   ```

1. In a different scenario, Shirley has ownership of `jie@example.com`. Shirley retrieves the code that Amazon Cognito sent to Jie's email address and attempts to confirm the account.

   **Example AWS CLI command**

   ```
   aws cognito-idp confirm-sign-up --client-id 1234567890abcdef0 --username=shirley --confirmation-code xxxxxx
   ```

   **Example response**

   ```
   An error occurred (AliasExistsException) when calling the ConfirmSignUp operation: An account with the email already exists.
   ```

Amazon Cognito doesn't return an error to Shirley's `aws cognito-idp sign-up` request, despite `jie@example.com` being assigned to an existing user. Shirley must demonstrate ownership of the email address before Amazon Cognito returns an error response. In a user pool with alias attributes, this behavior prevents use of the public `SignUp` API to check whether a user exists with a given email address or phone number.

This behavior is different from the response that Amazon Cognito returns to `SignUp` request with an existing username, as shown in the following example. While Shirley learns from this response that a user already exists with the username `jie`, they don't learn about any email addresses or phone numbers associated with the user.

**Example CLI command**

```
aws cognito-idp sign-up --client-id 1example23456789 --username jie --password PASSWORD
      --user-attributes Name="email",Value="shirley@example.com"
```

**Example response**

```
An error occurred (UsernameExistsException) when calling the SignUp operation: User already exists
```

## Password reset operations
<a name="cognito-user-pool-managing-errors-password-reset"></a>

Amazon Cognito returns the following responses to user password reset operations when you prevent user existence errors.

**ForgotPassword**  
When a user isn't found, is deactivated, or doesn't have a verified delivery mechanism to recover their password, Amazon Cognito returns `CodeDeliveryDetails` with a simulated delivery medium for a user. The simulated delivery medium is determined by the input username format and verification settings of the user pool.

**ConfirmForgotPassword**  
Amazon Cognito returns the `CodeMismatchException` error for users that don't exist or are disabled. If a code isn't requested when using `ForgotPassword`, Amazon Cognito returns the `ExpiredCodeException` error.

## Confirmation operations
<a name="cognito-user-pool-managing-errors-confirmation"></a>

Amazon Cognito returns the following responses to user confirmation and verification operations when you prevent user existence errors.

**ResendConfirmationCode**  
Amazon Cognito returns `CodeDeliveryDetails` for a disabled user or a user that doesn't exist. Amazon Cognito sends a confirmation code to the existing user's email or phone number.

**ConfirmSignUp**  
 `ExpiredCodeException` returns if a code has expired. Amazon Cognito returns `NotAuthorizedException` when a user isn't authorized. If the code doesn't match what the server expects Amazon Cognito returns `CodeMismatchException`. 

# User pool endpoints and managed login reference
<a name="cognito-userpools-server-contract-reference"></a>

Amazon Cognito has two models of user pool authentication: with the user pools API and with the OAuth 2.0 authorization server. Use the API when you want to retrieve OpenID Connect (OIDC) tokens with an AWS SDK in your application back end. Use the authorization server when you want to implement your user pool as an OIDC provider. The authorization server adds features like [federated sign-in](cognito-user-pools-identity-federation.md), [API and M2M authorization with access token scopes](cognito-user-pools-define-resource-servers.md), and [managed login](cognito-user-pools-managed-login.md). You can use the API and OIDC models each on their own or together, configured at the user pool level or at the [app client](user-pool-settings-client-apps.md) level. This section is a reference for the implementation of the OIDC model. For more information about the two authentication models, see [Understanding API, OIDC, and managed login pages authentication](authentication-flows-public-server-side.md#user-pools-API-operations).

Amazon Cognito activates the public webpages listed here when you assign a domain to your user pool. Your domain serves as a central access point for all of your app clients. They include managed login, where your users can sign up and sign in ([Login endpoint](login-endpoint.md)), and sign out ([Logout endpoint](logout-endpoint.md)). For more information about these resources, see [User pool managed login](cognito-user-pools-managed-login.md).

These pages also include the public web resources that allow your user pool to communicate with third-party SAML, OpenID Connect (OIDC) and OAuth 2.0 identity providers (IdPs). To sign in a user with a federated identity provider, your users must initiate a request to the interactive managed login [Login endpoint](login-endpoint.md) or the OIDC [Authorize endpoint](authorization-endpoint.md). The Authorize endpoint redirects your users either to your managed login pages or your IdP sign-in page.

Your app can also sign in *local users* with the [Amazon Cognito user pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html). A local user exists exclusively in your user pool directory without federation through an external IdP.

In addition to managed login, Amazon Cognito integrates with SDKs for Android, iOS, JavaScript, and more. The SDKs provide tools to perform user pool API operations with Amazon Cognito API service endpoints. For more information about service endpoints, see [Amazon Cognito Identity endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html).

**Warning**  
Don't pin the end-entity or intermediate Transport Layer Security (TLS) certificates for Amazon Cognito domains. AWS manages all certificates for all of your user pool endpoints and prefix domains. The certificate authorities (CAs) in the chain of trust that supports Amazon Cognito certificates dynamically rotate and renew. When you pin your app to an intermediate or leaf certificate, your app can fail without notice when AWS rotates certificates.  
Instead, pin your application to all available [Amazon root certificates](https://www.amazontrust.com/repository/). For more information, see best practices and recommendations at [Certificate pinning](https://docs.aws.amazon.com/acm/latest/userguide/acm-bestpractices.html#best-practices-pinning) in the *AWS Certificate Manager User Guide*.

**Topics**
+ [

# User-interactive managed login and classic hosted UI endpoints
](managed-login-endpoints.md)
+ [

# Identity provider and relying party endpoints
](federation-endpoints.md)
+ [

# OAuth 2.0 grants
](federation-endpoints-oauth-grants.md)
+ [

# Using PKCE in authorization code grants
](using-pkce-in-authorization-code.md)
+ [

# Managed login and federation error responses
](federation-endpoint-idp-responses.md)

# User-interactive managed login and classic hosted UI endpoints
<a name="managed-login-endpoints"></a>

Amazon Cognito activates the managed login endpoints in this section when you add a domain to your user pool. They are webpages where your users can complete the core authentication operations of a user pool. They include pages for password management, multi-factor authentication (MFA), and attribute verification.

The webpages that make up managed login are a front-end web application for interactive user sessions with your customers. Your app must invoke managed login in your users' browsers. Amazon Cognito doesn't support programmatic access to the webpages in this chapter. Those federation endpoints in the [Identity provider and relying party endpoints](federation-endpoints.md) that return a JSON response can be queried directly in your app code. The [Authorize endpoint](authorization-endpoint.md) redirects either to managed login or to an IdP sign-in page and also must be opened in users' browsers.

All user pool endpoints accept traffic from IPv4 and IPv6 source IP addresses.

The topics in this guide describe frequently-used managed login and classic hosted UI endpoints in detail. The difference between managed login and the hosted UI is visible, not functional. Except for `/passkeys/add`, all paths are shared between the two versions of managed login branding.

Amazon Cognito makes the webpages that follow available when you assign a domain to your user pool.


**Managed login endpoints**  

| Endpoint URL | Description | How it's accessed | 
| --- | --- | --- | 
| https://Your user pool domain/login | Signs in user pool local and federated users. |  Redirect from endpoints like [Authorize endpoint](authorization-endpoint.md), `/logout`, and `/confirmforgotPassword`. See [Login endpoint](login-endpoint.md).  | 
| https://Your user pool domain/logout | Signs out user pool users. |  Direct link. See [Logout endpoint](logout-endpoint.md).  | 
| https://Your user pool domain/confirmUser | Confirms users who have selected an email link to verify their user account. |  User selected link in an email message.  | 
| https://Your user pool domain/signup | Signs up a new user. The /login page directs your user to /signup when they select Sign up. |  Direct link with same parameters as `/oauth2/authorize`.  | 
| https://Your user pool domain/confirm | After your user pool sends a confirmation code to a user who signed up, prompts your user for the code. |  Redirect-only from `/signup`.  | 
| https://Your user pool domain/forgotPassword | Prompts your user for their user name and sends a password-reset code. The /login page directs your user to /forgotPassword when they select Forgot your password?. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/managed-login-endpoints.html)  | 
| https://Your user pool domain/confirmforgotPassword | Prompts your user for their password-reset code and a new password. The /forgotPassword page directs your user to /confirmforgotPassword when they select Reset your password. | Redirect-only from /forgotPassword. | 
| https://Your user pool domain/resendcode | Sends a new confirmation code to a user who has signed up in your user pool. |  Redirect-only from **Send a new code** link at `/confirm`.  | 
| https://Your user pool domain/passkeys/add | Registers a new [passkey](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passkey). Only available in managed login. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/managed-login-endpoints.html)  | 

**Topics**
+ [

# The managed login sign-in endpoint: `/login`
](login-endpoint.md)
+ [

# The managed login sign-out endpoint: `/logout`
](logout-endpoint.md)

# The managed login sign-in endpoint: `/login`
<a name="login-endpoint"></a>

The login endpoint is an authentication server and a redirect destination from [Authorize endpoint](authorization-endpoint.md). It's the entry point to managed login when you don't specify an identity provider. When you generate a redirect to the login endpoint, it loads the login page and presents the authentication options configured for the client to the user.

**Note**  
The login endpoint is a component of managed login. In your app, invoke federation and managed login pages that redirect to the login endpoint. Direct access by users to the login endpoint isn't a best practice.

## GET /login
<a name="get-login"></a>

The `/login` endpoint only supports `HTTPS GET` for your user's initial request. Your app invokes the page in a browser like Chrome or Firefox. When you redirect to `/login` from the [Authorize endpoint](authorization-endpoint.md), it passes along all the parameters that you provided in your initial request. The login endpoint supports all the request parameters of the authorize endpoint. You can also access the login endpoint directly. As a best practice, originate all your users' sessions at `/oauth2/authorize`.

**Example – prompt the user to sign in**

This example displays the login screen.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/login?
                response_type=code&
                client_id=ad398u21ijw3s9w3939&
                redirect_uri=https://YOUR_APP/redirect_uri&
                state=STATE&
                scope=openid+profile+aws.cognito.signin.user.admin
```

**Example – response**  
The authentication server redirects to your app with the authorization code and state. The server must return the code and state in the query string parameters and not in the fragment.

```
HTTP/1.1 302 Found
                    Location: https://YOUR_APP/redirect_uri?code=AUTHORIZATION_CODE&state=STATE
```

## User-initiated sign-in request
<a name="post-login"></a>

After your user loads the `/login` endpoint, they can enter a user name and password and choose **Sign in**. When they do this, they generate an `HTTPS POST` request with the same header request parameters as the `GET` request, and a request body with their username, password, and a device fingerprint.

# The managed login sign-out endpoint: `/logout`
<a name="logout-endpoint"></a>

The `/logout` endpoint is a redirection endpoint. It signs out the user and redirects either to an authorized sign-out URL for your app client, or to the `/login` endpoint. The available parameters in a GET request to the `/logout` endpoint are tailored to Amazon Cognito managed login use cases.

The logout endpoint is a front-end web application for interactive user sessions with your customers. Your app must invoke this and other managed login endpoints in your users' browsers.

To redirect your user to managed login to sign in again, add a `redirect_uri` parameter to your request. A `logout` request with a `redirect_uri` parameter must also include parameters for your subsequent request to the [Login endpoint](login-endpoint.md), like `client_id`, `response_type`, and `scope`.

To redirect your user to a page that you choose, add **Allowed sign-out URLs** to your app client. In your users' requests to the `logout` endpoint, add `logout_uri` and `client_id` parameters. If the value of `logout_uri` is one of the **Allowed sign-out URLs** for your app client, Amazon Cognito redirects users to that URL.

With single logout (SLO) for SAML 2.0 IdPs, Amazon Cognito first redirects your user to the SLO endpoint you defined in your IdP configuration. After your IdP redirects your user back to `saml2/logout`, Amazon Cognito responds with one more redirect to the `redirect_uri` or `logout_uri` from your request. For more information, see [Signing out SAML users with single sign-out](cognito-user-pools-saml-idp-sign-out.md).

The logout endpoint doesn't sign users out of OIDC or social identity providers (IdPs). To sign users out from their session with an external IdP, direct them to the sign-out page for that provider.

## GET /logout
<a name="get-logout"></a>

The `/logout` endpoint only supports `HTTPS GET`. The user pool client typically makes this request through the system browser. The browser is typically Custom Chrome Tab in Android or Safari View Control in iOS.

### Request parameters
<a name="get-logout-request-parameters"></a>

*client\$1id*  
The app client ID for your app. To get an app client ID, you must register the app in the user pool. For more information, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).  
Required.

*logout\$1uri*  
Redirect your user to a custom sign-out page with a *logout\$1uri* parameter. Set its value to the app client **sign-out URL** where you want to redirect your user after they sign out. Use *logout\$1uri* only with a *client\$1id* parameter. For more information, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).  
You can also use the *logout\$1uri* parameter to redirect your user to the sign-in page for another app client. Set the sign-in page for the other app client as an **Allowed callback URL** in your app client. In your request to the `/logout` endpoint, set the value of the *logout\$1uri* parameter to the URL-encoded sign-in page.  
Amazon Cognito requires either a *logout\$1uri* or a *redirect\$1uri* parameter in your request to the `/logout` endpoint. A *logout\$1uri* parameter redirects your user to another website. If both *logout\$1uri* and *redirect\$1uri* parameters are included in your request to the `/logout` endpoint, Amazon Cognito will utilize the *logout\$1uri* parameter exclusively, overriding the *redirect\$1uri* parameter.

*`nonce`*  
(Optional) A random value that you can add to the request. The nonce value that you provide is included in the ID token that Amazon Cognito issues. To guard against replay attacks, your app can inspect the `nonce` claim in the ID token and compare it to the one you generated. For more information about the `nonce` claim, see [ID token validation](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation) in the *OpenID Connect standard*.

**redirect\$1uri**  
Redirect your user to your sign-in page to authenticate with a *redirect\$1uri* parameter. Set its value to the app client **Allowed callback URL** where you want to redirect your user after they sign in again. Add *client\$1id*, *scope*, *state*, and *response\$1type* parameters that you want to pass to your `/login` endpoint.  
Amazon Cognito requires either a *logout\$1uri* or a *redirect\$1uri* parameter in your request to the `/logout` endpoint. To redirect your user to your `/login` endpoint to reauthenticate and pass tokens to your app, add a *redirect\$1uri* parameter. If both *logout\$1uri* and *redirect\$1uri* parameters are included in your request to the `/logout` endpoint, Amazon Cognito overrides the *redirect\$1uri* parameter and processes the *logout\$1uri* parameter exclusively.

*response\$1type*  
The OAuth 2.0 response that you want to receive from Amazon Cognito after your user signs in. `code` and `token` are the valid values for the *response\$1type* parameter.  
Required if you use a *redirect\$1uri* parameter.

*state*  
When your application adds a *state* parameter to a request, Amazon Cognito returns its value to your app when the `/oauth2/logout` endpoint redirects your user.  
Add this value to your requests to guard against [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) attacks.  
You can't set the value of a `state` parameter to a URL-encoded JSON string. To pass a string that matches this format in a `state` parameter, encode the string to base64, then decode it in your application.  
Strongly recommended if you use a *redirect\$1uri* parameter.

*scope*  
The OAuth 2.0 scopes that you want to request from Amazon Cognito after you sign them out with a *redirect\$1uri* parameter. Amazon Cognito redirects your user to the `/login` endpoint with the *scope* parameter in your request to the `/logout` endpoint.  
Optional if you use a *redirect\$1uri* parameter. If you don't include a *scope* parameter, Amazon Cognito redirects your user to the `/login` endpoint with a *scope* parameter. When Amazon Cognito redirects your user and automatically populates `scope`, the parameter includes all authorized scopes for your app client.

### Example requests
<a name="get-logout-request-sample"></a>

**Example – log out and redirect user to client**

Amazon Cognito redirects user sessions to the URL in the value of `logout_uri`, ignoring all other request parameters, when requests include `logout_uri` and `client_id`. This URL must be an authorized sign-out URL for the app client.

The following is an example request for sign-out and redirect to `https://www.example.com/welcome`.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/logout?
  client_id=1example23456789&
  logout_uri=https%3A%2F%2Fwww.example.com%2Fwelcome
```

**Example – log out and prompt the user to sign in as another user**

When requests omit `logout_uri` but otherwise provide the parameters that make up a well-formed request to the authorize endpoint, Amazon Cognito redirects users to managed login sign-in. The logout endpoint appends the parameters in your original request to the redirect destination.

The additional parameters that you add to the logout request must be in the list at [Request parameters](#get-logout-request-parameters). For example, the logout endpoint doesn't support automatic IdP redirect with `identity_provider` or `idp_identifier` parameters. The parameter `redirect_uri` in a request to the logout endpoint is not a sign-out URL, but a post-sign-in URL that you want to pass through to the authorize endpoint.

The following is an example request that signs a user out, redirects to the sign-in page, and provides an authorization code to `https://www.example.com` after sign-in.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/logout?
  response_type=code&
  client_id=1example23456789&
  redirect_uri=https%3A%2F%2Fwww.example.com&
  state=example-state-value&
  nonce=example-nonce-value&
  scope=openid+profile+aws.cognito.signin.user.admin
```

# Identity provider and relying party endpoints
<a name="federation-endpoints"></a>

*Federation endpoints* are user pool endpoints that serve a purpose for one of the authentication standards used by user pools. They include SAML ACS URLs, OIDC discovery endpoints, and service endpoints for user pool roles both as identity provider and relying party. Federation endpoints initiate authentication flows, receive proof of authentication from IdPs, and issue tokens to clients. They interact with IdPs, applications, and administrators, but not with users.

The full-page topics after this page have details about the OAuth 2.0 and OIDC provider endpoints that become available when you add a domain to your user pool. The following chart is a list of all federation endpoints.

Examples of [user pool domains](cognito-user-pools-assign-domain.md) are:

1. Prefix domain: `mydomain.auth.us-east-1.amazoncognito.com`

1. Custom domain: `auth.example.com`


**User pool federation endpoints**  

| Endpoint URL | Description | How it's accessed | 
| --- | --- | --- | 
| https://Your user pool domain/oauth2/authorize | Redirects a user to either managed login or to sign in with their IdP. | Invoked in customer browser to begin user authentication. See [Authorize endpoint](authorization-endpoint.md). | 
| https://Your user pool domain/oauth2/token | Returns tokens based on an authorization code or client credentials request. | Requested by app to retrieve tokens. See [Token endpoint](token-endpoint.md). | 
| https://Your user pool domain/oauth2/userInfo | Returns user attributes based on OAuth 2.0 scopes and user identity in an access token. | Requested by app to retrieve user profile. See [userInfo endpoint](userinfo-endpoint.md). | 
| https://Your user pool domain/oauth2/revoke | Revokes a refresh token and the associated access tokens. | Requested by app to revoke a token. See [Revoke endpoint](revocation-endpoint.md). | 
| https://cognito-idp.Region.amazonaws.com/your user pool ID/.well-known/openid-configuration | A directory of the OIDC architecture of your user pool.[1](#cognito-federation-oidc-discovery-note) | Requested by app to locate user pool issuer metadata. | 
| https://cognito-idp.Region.amazonaws.com/your user pool ID/.well-known/jwks.json | Public keys that you can use to validate Amazon Cognito tokens.[2](#cognito-federation-oidc-jwks-note) | Requested by app to verify JWTs. | 
| https://Your user pool domain/oauth2/idpresponse | Social identity providers must redirect your users to this endpoint with an authorization code. Amazon Cognito redeems the code for a token when it authenticates your federated user. | Redirected from OIDC IdP sign-in as the IdP client callback URL. | 
| https://Your user pool domain/saml2/idpresponse | The Assertion Consumer Response (ACS) URL for integration with SAML 2.0 identity providers. | Redirected from SAML 2.0 IdP as the ACS URL, or the origination point for IdP-initiated sign-in[3](#cognito-federation-idp-init-note). | 
| https://Your user pool domain/saml2/logout | The [Single Logout](cognito-user-pools-saml-idp-sign-out.md#cognito-user-pools-saml-idp-sign-out.title) (SLO) URL for integration with SAML 2.0 identity providers. | Redirected from SAML 2.0 IdP as the single logout (SLO) URL. Accepts POST binding only. | 

1 The `openid-configuration` document might be updated at any time with additional information that keeps the endpoint compliant with the OIDC and OAuth2 specifications.

2The `jwks.json` JSON file might be updated at any time to with new public token signing keys.

3 For more information about IdP-initiated SAML sign-in, see [Implement IdP-initiated SAML sign-in](cognito-user-pools-SAML-session-initiation.md#cognito-user-pools-SAML-session-initiation-idp-initiation).

For more information on the OpenID Connect and OAuth standards, see [OpenID Connect 1.0](http://openid.net/specs/openid-connect-core-1_0.html) and [OAuth 2.0](https://tools.ietf.org/html/rfc6749).

**Topics**
+ [

# The redirect and authorization endpoint
](authorization-endpoint.md)
+ [

# The token issuer endpoint
](token-endpoint.md)
+ [

# The user attributes endpoint
](userinfo-endpoint.md)
+ [

# The token revocation endpoint
](revocation-endpoint.md)
+ [

# The IdP SAML assertion endpoint
](saml2-idpresponse-endpoint.md)

# The redirect and authorization endpoint
<a name="authorization-endpoint"></a>

The `/oauth2/authorize` endpoint is a redirection endpoint that supports two redirect destinations. If you include an `identity_provider` or `idp_identifier` parameter in the URL, it silently redirects your user to the sign-in page for that identity provider (IdP). Otherwise, it redirects to the [Login endpoint](login-endpoint.md) with the same URL parameters that you included in your request. 

The authorize endpoint redirects either to managed login or to an IdP sign-in page. The destination of a user session at this endpoint is a webpage that your user must interact with directly in their browser.

To use the authorize endpoint, invoke your user's browser at `/oauth2/authorize` with parameters that provide your user pool with information about the following user pool details.
+ The app client that you want to sign in to.
+ The callback URL that you want to end up at.
+ The OAuth 2.0 scopes that you want to request in your user's access token.
+ Optionally, the third-party IdP that you want to use to sign in.

You can also supply `state` and `nonce` parameters that Amazon Cognito uses to validate incoming claims.

## GET `/oauth2/authorize`
<a name="get-authorize"></a>

The `/oauth2/authorize` endpoint only supports `HTTPS GET`. Your app typically initiates this request in your user's browser. You can only make requests to the `/oauth2/authorize` endpoint over HTTPS.

You can learn more about the definition of the authorization endpoint in the OpenID Connect (OIDC) standard at [Authorization Endpoint](http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthorizationEndpoint).

### Request parameters
<a name="get-authorize-request-parameters"></a>

**`response_type`**  
Required.  
The response type. Must be `code` or `token`.   
A successful request with a `response_type` of `code` returns an authorization code grant. An authorization code grant is a `code` parameter that Amazon Cognito appends to your redirect URL. Your app can exchange the code with the [Token endpoint](token-endpoint.md) for access, ID, and refresh tokens. As a security best practice, and to receive refresh tokens for your users, use an authorization code grant in your app.  
A successful request with a `response_type` of `token` returns an implicit grant. An implicit grant is an ID and access token that Amazon Cognito appends to your redirect URL. An implicit grant is less secure because it exposes tokens and potential identifying information to users. You can deactivate support for implicit grants in the configuration of your app client.

**`client_id`**  
Required.  
The app client ID.  
The value of `client_id` must be the ID of an app client in the user pool where you make the request. Your app client must support sign-in by Amazon Cognito local users or at least one third-party IdP.

**`redirect_uri`**  
Required.  
The URL where the authentication server redirects the browser after Amazon Cognito authorizes the user.  
A redirect uniform resource identifier (URI) must have the following attributes:  
+ It must be an absolute URI.
+ You must have pre-registered the URI with a client.
+ It can't include a fragment component.
See [OAuth 2.0 - Redirection Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1.2).  
Amazon Cognito requires that your redirect URI use HTTPS, except for `http://localhost`, which you can set as a callback URL for testing purposes.  
Amazon Cognito also supports app callback URLs such as `myapp://example`.

**`state`**  
Optional, recommended.  
When your app adds a *state* parameter to a request, Amazon Cognito returns its value to your app when the `/oauth2/authorize` endpoint redirects your user.  
Add this value to your requests to guard against [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) attacks.  
You can't set the value of a `state` parameter to a URL-encoded JSON string. To pass a string that matches this format in a `state` parameter, encode the string to base64, then decode it in your app.

**`identity_provider`**  
Optional.  
Add this parameter to bypass managed login and redirect your user to a provider sign-in page. The value of the *identity\$1provider* parameter is the name of the identity provider (IdP) as it appears in your user pool.  
+ For social providers, you can use the *identity\$1provider* values `Facebook`, `Google`, `LoginWithAmazon`, and `SignInWithApple`.
+ For Amazon Cognito user pools, use the value `COGNITO`.
+ For SAML 2.0 and OpenID Connect (OIDC) identity providers (IdPs), use the name that you assigned to the IdP in your user pool.

**`idp_identifier`**  
Optional.  
Add this parameter to redirect to a provider with an alternative name for the *identity\$1provider* name. You can enter identifiers for your SAML 2.0 and OIDC IdPs from the **Social and external providers** menu of the Amazon Cognito console.

**`scope`**  
Optional.  
Can be a combination of any system-reserved scopes or custom scopes that are associated with a client. Scopes must be separated by spaces. System reserved scopes are `openid`, `email`, `phone`, `profile`, and `aws.cognito.signin.user.admin`. Any scope used must be associated with the client, or it will be ignored at runtime.  
If the client doesn't request any scopes, the authentication server uses all scopes that are associated with the client.  
An ID token is only returned if `openid` scope is requested. The access token can be only used against Amazon Cognito user pools if `aws.cognito.signin.user.admin` scope is requested. The `phone`, `email`, and `profile` scopes can only be requested if `openid` scope is also requested. These scopes dictate the claims that go inside the ID token.

**`code_challenge_method`**  
Optional.  
The hashing protocol that you used to generate the challenge. The [PKCE RFC](https://tools.ietf.org/html/rfc7636) defines two methods, S256 and plain; however, Amazon Cognito authentication server supports only S256.

**`code_challenge`**  
Optional.  
The proof of key code exchange (PKCE) challenge that you generated from the `code_verifier`. For more information, see [Using PKCE in authorization code grants](using-pkce-in-authorization-code.md).  
Required only when you specify a `code_challenge_method` parameter.

**`nonce`**  
Optional.  
A random value that you can add to the request. The nonce value that you provide is included in the ID token that Amazon Cognito issues. To guard against replay attacks, your app can inspect the `nonce` claim in the ID token and compare it to the one you generated. For more information about the `nonce` claim, see [ID token validation](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation) in the *OpenID Connect standard*.

**`lang`**  
Optional.  
The language that you want to display user-interactive pages in. Managed login pages can be localized, but hosted UI (classic) pages can't. For more information, see [Managed login localization](cognito-user-pools-managed-login.md#managed-login-localization).

**`login_hint`**  
Optional.  
A username prompt that you want to pass to the authorization server. You can collect a username, email address or phone number from your user and allow the destination provider to pre-populate the user's sign-in name. When you submit a `login_hint` parameter and no `idp_identifier` or `identity_provider` parameters to the `oauth2/authorize` endpoint, managed login fills the username field with your hint value. You can also pass this parameter to the [Login endpoint](login-endpoint.md) and automatically fill the username value.  
When your authorization request invokes a redirect to OIDC IdPs, Amazon Cognito adds a `login_hint` parameter to the request to that third-party authorizer. You can't forward login hints to SAML, Apple, Login With Amazon, Google, or Facebook (Meta) IdPs.

**`prompt`**  
Optional.  
An OIDC parameter that controls authentication behavior for existing sessions. Available in the managed login branding version only, not in the classic hosted UI. For more information from the OIDC specification, see [Authentication request](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest). The values `none` and `login` have an effect on user pool authentication behavior.  
Amazon Cognito forwards all values of `prompt` except `none` to your IdPs when users select authentication with third-party providers. This is true when the URL that users access includes an `identity_provider` or `idp_identifier` parameter, or when the authorization server redirects them to the [Login endpoint](login-endpoint.md) and they select and IdP from the available buttons.  
**Prompt parameter values**    
`prompt=none`  
Amazon Cognito silently continues authentication for users who have a valid authenticated session. With this prompt, users can silently authenticate between different app clients in your user pool. If the user is not already authenticated, the authorization server returns a `login_required` error.  
`prompt=login`  
Amazon Cognito requires users to re-authenticate even if they have an existing session. Send this value when you want to verify the user's identity again. Authenticated users who have an existing session can return to sign-in without invalidating that session. When a user who has an existing session signs in again, Amazon Cognito assigns them a new session cookie. This parameter can also be forwarded to your IdPs. IdPs that accept this parameter also request a new authentication attempt from the user.  
`prompt=select_account`  
This value has no effect on local sign-in and must be submitted in requests that redirect to IdPs. When included in your authorization request, this parameter adds `prompt=select_account` to the URL path for the IdP redirect destination. When IdPs support this parameter, they request that users select the account that they want to log in with.  
`prompt=consent`  
This value has no effect on local sign-in and must be submitted in requests that redirect to IdPs. When included in your authorization request, this parameter adds `prompt=consent` to the URL path for the IdP redirect destination. When IdPs support this parameter, they request user consent before they redirect back to your user pool. 
When you omit the `prompt` parameter from your request, managed login follows the default behavior: users must sign in unless their browser has a valid managed login session cookie. You can combine multiple values for `prompt` with a space-character delimiter, for example `prompt=login consent`.

**`resource`**  
Optional.  
The identifier of a resource that you want to bind to the access token in the `aud` claim. When you include this parameter, Amazon Cognito validates that the value is a URL and sets the audience of the resulting access token to the requested resource. You can request a user pool [resource server](cognito-user-pools-define-resource-servers.md) with an identifier in a URL format, or a URL of your choosing. Values for this parameter must begin with `https://`, `http://localhost`, or a custom URL scheme like `myapp://`.  
Resource binding is defined in [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html). For more information about resource servers and resource binding, see [Resource binding](cognito-user-pools-define-resource-servers.md#cognito-user-pools-resource-binding).

## Example: authorization code grant
<a name="sample-authorization-code-grant"></a>

This is an example request for an authorization code grant.

The following request initiates a session to retrieve an authorization code that your user passes to your app at the `redirect_uri` destination. This session requests scopes for user attributes and for access to Amazon Cognito self-service API operations.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=openid+profile+aws.cognito.signin.user.admin
```

The Amazon Cognito authentication server redirects back to your app with the authorization code and state. The authorization code is valid for five minutes.

```
HTTP/1.1 302 Found
Location: https://www.example.com?code=a1b2c3d4-5678-90ab-cdef-EXAMPLE11111&state=abcdefg
```

## Example: authorization code grant with PKCE
<a name="sample-authorization-code-grant-with-pkce"></a>

This example flow performs an authorization code grant with [PKCE](using-pkce-in-authorization-code.md#using-pkce-in-authorization-code.title).

This request adds a `code_challenge` parameter. To complete the exchange of a code for a token, you must include the `code_verifier` parameter in your request to the `/oauth2/token` endpoint.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=aws.cognito.signin.user.admin&
code_challenge_method=S256&
code_challenge=a1b2c3d4...
```

The authorization server redirects back to your application with the authorization code and state. Your application processes the authorization code and exchanges it for tokens.

```
HTTP/1.1 302 Found
Location: https://www.example.com?code=a1b2c3d4-5678-90ab-cdef-EXAMPLE11111&state=abcdefg
```

## Example: require re-authentication with `prompt=login`
<a name="sample-authorization-code-with-prompt-login"></a>

The following request adds a `prompt=login` parameter that requires the user to authenticate again, even if they have an existing session.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=openid+profile+aws.cognito.signin.user.admin&
prompt=login
```

The authorization server redirects to the [login endpoint](login-endpoint.md), requiring re-authentication.

```
HTTP/1.1 302 Found Location: https://mydomain.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com&state=abcdefg&scope=openid+profile+aws.cognito.signin.user.admin&prompt=login
```

## Example: silent authentication with `prompt=none`
<a name="sample-authorization-code-with-prompt-none"></a>

The following request adds a `prompt=none` parameter that silently checks if the user has a valid session.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=openid+profile+aws.cognito.signin.user.admin&
prompt=none
```

When no valid session exists, the authorization server returns an error to the redirect URI

```
HTTP/1.1 302 Found Location: https://www.example.com?error=login_required&state=abcdefg
```

When a valid session exists, the authorization server returns an authorization code.

```
HTTP/1.1 302 Found Location: https://www.example.com?code=AUTHORIZATION_CODE&state=abcdefg
```

## Example: authorization code grant with resource binding
<a name="sample-authorization-code-with-resource-binding"></a>

The following request adds a `resource` parameter to bind the access token to a specific resource server. The resulting access token creates the conditions for the target API to validate that it is the intended audience of the authenticated user's request.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=solar-system-data-api.example.com/asteroids.add&
resource=https://solar-system-data-api.example.com
```

The authorization server returns an authorization code that results in an access token with an `aud` claim of `https://solar-system-data-api.example.com`.

```
HTTP/1.1 302 Found Location: https://www.example.com?code=AUTHORIZATION_CODE&state=abcdefg
```

## Example: Token (implicit) grant without `openid` scope
<a name="sample-token-grant-without-openid-scope"></a>

This example flow generates an implicit grant and returns JWTs directly to the user's session.

The request is for an implicit grant from your authorization server. It requests scopes in the access token that authorize user profile self-service operations.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=token&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=aws.cognito.signin.user.admin
```

The authorization server redirects back to your application with an access token only. Because `openid` scope was not requested, Amazon Cognito doesn't return an ID token. Also, Amazon Cognito doesn't return a refresh token in this flow.

```
HTTP/1.1 302 Found
Location: https://example.com/callback#access_token=eyJra456defEXAMPLE&token_type=bearer&expires_in=3600&state=STATE
```

## Example: Token (implicit) grant with `openid` scope
<a name="sample-token-grant-with-openid-scope"></a>

This example flow generates an implicit grant and returns tokens to the user's browser.

The request is for an implicit grant from your authorization server. It requests scopes in the access token that authorize access to user attributes and self-service operations.

```
GET
https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize? 
response_type=token& 
client_id=1example23456789& 
redirect_uri=https://www.example.com& 
state=abcdefg&
scope=aws.cognito.signin.user.admin+openid+profile
```

The authorization server redirects back to your application with access token and ID token (because `openid` scope was included):

```
HTTP/1.1 302 Found
Location: https://www.example.com#id_token=eyJra67890EXAMPLE&access_token=eyJra12345EXAMPLE&token_type=bearer&expires_in=3600&state=abcdefg
```

## Examples of negative responses
<a name="get-authorize-negative"></a>

Amazon Cognito might deny your request. Negative requests come with an HTTP error code and a description that you can use to correct your request parameters. The following are examples of negative responses.
+ If `client_id` and `redirect_uri` are valid, but the request parameters aren't formatted correctly, the authentication server redirects the error to the client's `redirect_uri` and appends an error message in a URL parameter. The following are examples of incorrect formatting.
  + The request doesn't include a `response_type` parameter.
  + The authorization request provided a `code_challenge` parameter, but not a `code_challenge_method` parameter.
  + The value of the `code_challenge_method` parameter isn't `S256`.

  The following is the response to an example request with incorrect formatting.

  ```
  HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request
  ```
+ If the client requests `code` or `token` in `response_type`, but doesn't have permission for these requests, the Amazon Cognito authorization server returns `unauthorized_client` to client's `redirect_uri`, as follows:

  ```
  HTTP 1.1 302 Found Location: https://client_redirect_uri?error=unauthorized_client
  ```
+  If the client requests scope that is unknown, malformed, or not valid, the Amazon Cognito authorization server returns `invalid_scope` to the client's `redirect_uri`, as follows: 

  ```
  HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_scope
  ```
+ If there is any unexpected error in the server, the authentication server returns `server_error` to the client's `redirect_uri`. Because the HTTP 500 error doesn't get sent to the client, the error doesn't display in the user's browser. The authorization server returns the following error.

  ```
  HTTP 1.1 302 Found Location: https://client_redirect_uri?error=server_error
  ```
+ When Amazon Cognito authenticates through federation to third-party IdPs, Amazon Cognito might experience connection issues, such as the following:
  + If a connection timeout occurs while requesting token from the IdP, the authentication server redirects the error to the client’s `redirect_uri` as follows:

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=Timeout+occurred+in+calling+IdP+token+endpoint
    ```
  + If a connection timeout occurs while calling the `jwks_uri` endpoint for ID token validation, the authentication server redirects with an error to the client’s `redirect_uri` as follows:

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=error_description=Timeout+in+calling+jwks+uri
    ```
+ When authenticating by federating to third-party IdPs, the providers may return error responses. This can be due to configuration errors or other reasons, such as the following:
  + If an error response is received from other providers, the authentication server redirects the error to the client’s `redirect_uri` as follows:

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=[IdP name]+Error+-+[status code]+error getting token
    ```
  + If an error response is received from Google, the authentication server redirects the error to the client’s `redirect_uri` as follows: 

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=Google+Error+-+[status code]+[Google-provided error code]
    ```
+ When Amazon Cognito encounters an communication exception when it connects to an external IdP, the authentication server redirects with an error to the client's `redirect_uri` with either of the following messages:
  + 

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=Connection+reset
    ```
  + 

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=Read+timed+out
    ```

# The token issuer endpoint
<a name="token-endpoint"></a>

The OAuth 2.0 [token endpoint](https://www.rfc-editor.org/rfc/rfc6749#section-3.2) at `/oauth2/token` issues JSON web tokens (JWTs) to applications that want to complete authorization-code and client-credentials grant flows. These tokens are the end result of authentication with a user pool. They contain information about the user (ID token), the user's level of access (access token), and the user's entitlement to persist their signed-in session (refresh token). OpenID Connect (OIDC) relying-party libraries handle requests to and response payloads from this endpoint. Tokens provide verifiable proof of authentication, profile information, and a mechanism for access to back-end systems.

Your user pool OAuth 2.0 authorization server issues JSON web tokens (JWTs) from the token endpoint to the following types of sessions:

1. Users who have completed a request for an authorization code grant. Successful redemption of a code returns ID, access, and refresh tokens.

1. Machine-to-machine (M2M) sessions that have completed a client-credentials grant. Successful authorization with the client secret returns an access token.

1. Users who have previously signed in and received refresh tokens. Refresh token authentication returns new ID and access tokens.
**Note**  
Users who sign in with an authorization code grant in managed login or through federation can always refresh their tokens from the token endpoint. Users who sign in with the API operations `InitiateAuth` and `AdminInitiateAuth` can refresh their tokens with the token endpoint when [remembered devices](amazon-cognito-user-pools-device-tracking.md) is *not* active in your user pool. If remembered devices is active, refresh tokens with the [relevant API or SDK token-refresh operation](amazon-cognito-user-pools-using-the-refresh-token.md#using-the-refresh-token-api) for your app client.

The token endpoint becomes publicly available when you add a domain to your user pool. It accepts HTTP POST requests. For application security, use PKCE with your authorization code sign-in events. PKCE verifies that the user passing an authorization code is that same user who authenticated. For more information about PKCE, see [IETF RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636).

You can learn more about the user pool app clients and their grant types, client secrets, allowed scopes, and client IDs at [Application-specific settings with app clients](user-pool-settings-client-apps.md). You can learn more about M2M authorization, client credentials grants, and authorization with access token scopes at [Scopes, M2M, and resource servers](cognito-user-pools-define-resource-servers.md).

To retrieve information about a user from their access token, pass it to your [userInfo endpoint](userinfo-endpoint.md) or to a [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html) API request. The access token must contain the appropriate scopes for these requests,

## Format a POST request to the token endpoint
<a name="post-token"></a>

The `/oauth2/token` endpoint only supports `HTTPS POST`. This endpoint is not user-interactive. Handle token requests with an [OpenID Connect (OIDC) library](https://openid.net/developers/certified-openid-connect-implementations/) in your application.

The token endpoint supports `client_secret_basic` and `client_secret_post` authentication. For more information about the OIDC specification, see [Client Authentication](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication). For more information about the token endpoint from the OpenID Connect specification, see [Token Endpoint](http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint).

### Request parameters in header
<a name="post-token-request-parameters"></a>

You can pass the following parameters in the header of your request to the token endpoint.

**`Authorization`**  
If the client was issued a secret, the client can pass its `client_id` and `client_secret` in the authorization header as `client_secret_basic` HTTP authorization. You can also include the `client_id` and `client_secret` in the request body as `client_secret_post` authorization.  
The authorization header string is [Basic](https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side) `Base64Encode(client_id:client_secret)`. The following example is an authorization header for app client `djc98u3jiedmi283eu928` with client secret `abcdef01234567890`, using the Base64-encoded version of the string `djc98u3jiedmi283eu928:abcdef01234567890`:  

```
Authorization: Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw
```

**`Content-Type`**  
Set the value of this parameter to `'application/x-www-form-urlencoded'`.

### Request parameters in body
<a name="post-token-request-parameters-in-body"></a>

The following are parameters that you can request in `x-www-form-urlencoded` format in the request body to the token endpoint.

**`grant_type`**  
*Required.*  
The type of OIDC grant that you want to request.  
Must be `authorization_code` or `refresh_token` or `client_credentials`. You can request an access token for a custom scope from the token endpoint under the following conditions:  
+ You enabled the requested scope in your app client configuration.
+ You configured your app client with a client secret.
+ You enable client credentials grant in your app client.
The token endpoint returns a refresh token only when the `grant_type` is `authorization_code`.

**`client_id`**  
*Optional. Not required when you provide the app client ID in the `Authorization` header.*  
The ID of an app client in your user pool. Specify the same app client that authenticated your user.  
You must provide this parameter if the client is public and does not have a secret, or with `client_secret` in `client_secret_post` authorization.

**`client_secret`**  
*Optional. Not required when you provide the client secret in the `Authorization` header and when the app client doesn't have a secret.*  
The app client secret, if the app client has one, for `client_secret_post` authorization.

**`scope`**  
*Optional.*  
Can be a combination of any scopes that are associated with your app client. Amazon Cognito ignores scopes in the request that aren't allowed for the requested app client. If you don't provide this request parameter, the authorization server returns an access token `scope` claim with all authorization scopes that you enabled in your app client configuration. You can request any of the scopes allowed for the requested app client: standard scopes, custom scopes from resource servers, and the `aws.cognito.signin.user.admin` user self-service scope.

**`redirect_uri`**  
*Optional. Not required for client-credentials grants.*  
Must be the same `redirect_uri` that was used to get `authorization_code` in `/oauth2/authorize`.  
You must provide this parameter if `grant_type` is `authorization_code`.

**`refresh_token`**  
*Optional. Used only when the user already has a refresh token and wishes to get new ID and access tokens.*  
To generate new access and ID tokens for a user's session, set the value of `refresh_token` to a valid refresh token that the requested app client issued.  
Returns a new refresh token with new ID and access token when [refresh token rotation](amazon-cognito-user-pools-using-the-refresh-token.md#using-the-refresh-token-rotation) is active, otherwise returns only ID and access tokens. If the original access token was [bound to an API resource](cognito-user-pools-define-resource-servers.md#cognito-user-pools-resource-binding), the new access token maintains the requested API url in the `aud` claim.

**`code`**  
*Optional. Only required in authorization-code grants.*  
The authorization code from an authorization code grant. You must provide this parameter if your authorization request included a `grant_type` of `authorization_code`.

**`aws_client_metadata`**  
*Optional.*  
Information that you want to pass to the [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md) in [machine-to-machine (M2M)](cognito-user-pools-define-resource-servers.md) authorization flows. Your application can collect context information about the session and pass it in this parameter. When you pass `aws_client_metadata` in URL-encoded JSON format, Amazon Cognito includes it in the input event to your trigger Lambda function. Your pre token trigger event version or global Lambda trigger version must be configured for version three or later. Although Amazon Cognito accepts requests to this endpoint in authorization code and client credentials M2M flows, your user pool only passes `aws_client_metadata` to the pre token generation trigger from client credentials requests.

**`code_verifier`**  
Optional. Required only if you provided `code_challenge_method` and `code_challenge` parameters in your initial authorization request.  
The generated code verifier that your application calculated the `code_challenge` from in an authorization code grant request with [PKCE](using-pkce-in-authorization-code.md).

## Exchanging an authorization code for tokens
<a name="post-token-positive-exchanging-authorization-code-for-tokens"></a>

The following request successfully generates ID, access, and refresh tokens after authentication with an authorization-code grant. The request passes the client secret in `client_secret_basic` format in the `Authorization` header.

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token&
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=authorization_code&
client_id=1example23456789&
code=AUTHORIZATION_CODE&
redirect_uri=com.myclientapp://myclient/redirect
```

The response issues new ID, access, and refresh tokens to the user, with additional metadata.

```
HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJra1example",
    "id_token": "eyJra2example",
    "refresh_token": "eyJj3example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Client credentials with basic authorization
<a name="exchanging-client-credentials-for-an-access-token-in-request-body"></a>

The following request from an M2M application requests a client credentials grant. Because client credentials requires a client secret, the request is authorized with an `Authorization` header derived from the app client ID and secret. The request results in an access token with the two requested scopes. The request also includes client metadata that provides IP-address information and a token issued to the user who this grant is on behalf of. Amazon Cognito passes the client metadata to the pre token generation Lambda trigger.

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token >
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=client_credentials&
client_id=1example23456789&
scope=resourceServerIdentifier1%2Fscope1%20resourceServerIdentifier2%2Fscope2&
&aws_client_metadata=%7B%22onBehalfOfToken%22%3A%22eyJra789ghiEXAMPLE%22,%20%22ClientIpAddress%22%3A%22192.0.2.252%22%7D
```

Amazon Cognito passes the following input event to the pre token generation Lambda trigger.

```
{
    version: '3',
    triggerSource: 'TokenGeneration_ClientCredentials',
    region: 'us-east-1',
    userPoolId: 'us-east-1_EXAMPLE',
    userName: 'ClientCredentials',
    callerContext: {
        awsSdkVersion: 'aws-sdk-unknown-unknown',
        clientId: '1example23456789'
    },
    request: {
        userAttributes: {},
        groupConfiguration: null,
        scopes: [
           'resourceServerIdentifier1/scope1',
           'resourceServerIdentifier2/scope2'
        ],
        clientMetadata: {
            'onBehalfOfToken': 'eyJra789ghiEXAMPLE',
            'ClientIpAddress': '192.0.2.252'
        }
    },
    response: { claimsAndScopeOverrideDetails: null }
}
```

The response returns an access token. Client credentials grants are for machine-to-machine (M2M) authorization and only return access tokens.

```
HTTP/1.1 200 OK
Content-Type: application/json
{
    "access_token": "eyJra1example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Client credentials with POST body authorization
<a name="post-token-positive-exchanging-client-credentials-for-an-access-token-in-request-body"></a>

The following client-credentials grant request includes the `client_secret` parameter in the request body and doesn't include an `Authorization` header. This request uses the `client_secret_post` authorization syntax. The request results in an access token with the requested scope. The request also includes client metadata that provides IP-address information and a token issued to the user who this grant is on behalf of. Amazon Cognito passes the client metadata to the pre token generation Lambda trigger.

```
POST /oauth2/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
X-Amz-Target: AWSCognitoIdentityProviderService.Client credentials request
User-Agent: USER_AGENT
Accept: /
Accept-Encoding: gzip, deflate, br
Content-Length: 177
Referer: http://auth.example.com/oauth2/token
Host: auth.example.com
Connection: keep-alive

grant_type=client_credentials&
client_id=1example23456789&
scope=my_resource_server_identifier%2Fmy_custom_scope&
client_secret=9example87654321&
aws_client_metadata=%7B%22onBehalfOfToken%22%3A%22eyJra789ghiEXAMPLE%22,%20%22ClientIpAddress%22%3A%22192.0.2.252%22%7D
```

Amazon Cognito passes the following input event to the pre token generation Lambda trigger.

```
{
    version: '3',
    triggerSource: 'TokenGeneration_ClientCredentials',
    region: 'us-east-1',
    userPoolId: 'us-east-1_EXAMPLE',
    userName: 'ClientCredentials',
    callerContext: {
        awsSdkVersion: 'aws-sdk-unknown-unknown',
        clientId: '1example23456789'
    },
    request: {
        userAttributes: {},
        groupConfiguration: null,
        scopes: [
           'resourceServerIdentifier1/my_custom_scope'
        ],
        clientMetadata: {
            'onBehalfOfToken': 'eyJra789ghiEXAMPLE',
            'ClientIpAddress': '192.0.2.252'
        }
    },
    response: { claimsAndScopeOverrideDetails: null }
}
```

The response returns an access token. Client credentials grants are for machine-to-machine (M2M) authorization and only return access tokens.

```
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Date: Tue, 05 Dec 2023 16:11:11 GMT
x-amz-cognito-request-id: 829f4fe2-a1ee-476e-b834-5cd85c03373b

{
    "access_token": "eyJra12345EXAMPLE",
    "expires_in": 3600,
    "token_type": "Bearer"
}
```

## Authorization code grant with PKCE
<a name="post-token-positive-exchanging-authorization-code-grant-with-pkce-for-tokens"></a>

The following example request completes an authorization request that included `code_challenge_method` and `code_challenge` parameters in an authorization code grant request with [PKCE](using-pkce-in-authorization-code.md).

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=authorization_code&
client_id=1example23456789&
code=AUTHORIZATION_CODE&
code_verifier=CODE_VERIFIER&
redirect_uri=com.myclientapp://myclient/redirect
```

The response returns ID, access, and refresh tokens from the successful PKCE verification by the application.

```
HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJra1example",
    "id_token": "eyJra2example",
    "refresh_token": "eyJj3example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Token refresh without refresh token rotation
<a name="post-token-positive-exchanging-a-refresh-token-for-tokens"></a>

The following example requests provides a refresh token to an app client where [refresh token rotation](amazon-cognito-user-pools-using-the-refresh-token.md#using-the-refresh-token-rotation) is inactive. Because the app client has a client secret, the request provides an `Authorization` header.

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token >
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=refresh_token&
client_id=1example23456789&
refresh_token=eyJj3example
```

The response returns new ID and access tokens.

```
HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJra1example",
    "id_token": "eyJra2example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Token refresh with refresh token rotation
<a name="post-token-positive-refresh-token-rotation"></a>

The following example requests provides a refresh token to an app client where [refresh token rotation](amazon-cognito-user-pools-using-the-refresh-token.md#using-the-refresh-token-rotation) is active. Because the app client has a client secret, the request provides an `Authorization` header.

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token >
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=refresh_token&
client_id=1example23456789&
refresh_token=eyJj3example
```

The response returns new ID, access, and refresh tokens.

```
HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJra1example",
    "id_token": "eyJra2example",
    "refresh_token": "eyJj4example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Examples of negative responses
<a name="post-token-negative"></a>

Malformed requests generate errors from the token endpoint. The following is a general map of the response body when token requests generate an error.

```
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=UTF-8

{
"error":"invalid_request|invalid_client|invalid_grant|unauthorized_client|unsupported_grant_type"
}
```

**`invalid_request`**  
The request is missing a required parameter, includes an unsupported parameter value (other than `unsupported_grant_type`), or is otherwise malformed. For example, `grant_type` is `refresh_token` but `refresh_token` is not included. 

**`invalid_client`**  
Client authentication failed. For example, when the client includes `client_id` and `client_secret` in the authorization header, but there's no such client with that `client_id` and `client_secret`. 

**`invalid_grant`**  
Refresh token has been revoked.   
Authorization code has been consumed already or does not exist.   
App client doesn't have read access to all [attributes](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html) in the requested scope. For example, your app requests the `email` scope and your app client can read the `email` attribute, but not `email_verified`.

**`unauthorized_client`**  
Client is not allowed for code grant flow or for refreshing tokens. 

**`unsupported_grant_type`**  
Returned if `grant_type` is anything other than `authorization_code` or `refresh_token` or `client_credentials`. 

# The user attributes endpoint
<a name="userinfo-endpoint"></a>

Where OIDC issues ID tokens that contain user attributes, OAuth 2.0 implements the `/oauth2/userInfo` endpoint. An authenticated user or client receives an access token with a `scopes` claim. This claim determines the attributes that the authorization server should return. When an application presents an access token to the `userInfo` endpoint, the authorization server returns a response body that contains the user attributes that are within the boundaries set by the access token scopes. Your application can retrieve information about a user from the `userInfo` endpoint as long as it holds a valid access token with at least an `openid` scope claim.

The `userInfo` endpoint is an OpenID Connect (OIDC) [userInfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo). It responds with user attributes when service providers present access tokens that your [token endpoint](token-endpoint.md) issued. The scopes in your user's access token define the user attributes that the userInfo endpoint returns in its response. The `openid` scope must be one of the access token claims.

Amazon Cognito issues access tokens in response to user pools API requests like [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html). Because they don't contain any scopes, the userInfo endpoint doesn't accept these access tokens. Instead, you must present access tokens from your token endpoint.

Your OAuth 2.0 third-party identity provider (IdP) also hosts a userInfo endpoint. When your user authenticates with that IdP, Amazon Cognito silently exchanges an authorization code with the IdP `token` endpoint. Your user pool passes the IdP access token to authorize retrieval of user information from the IdP `userInfo` endpoint.

The scopes in a user's access token are determined by the `scopes` request parameter in authentication requests, or the scopes that the [pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md) adds. You can decode access tokens and examine `scope` claims to see the access-control scopes that they contain. The following are some scope combinations that influence the data returned from the `userInfo` endpoint. The reserved Amazon Cognito scope `aws.cognito.signin.user.admin` has no effect on the data returned from this endpoint.Example scopes in access token and their effect on the `userInfo` response

**`openid`**  
Returns a response with all user attributes that the app client can read.

**`openid profile`**  
Returns the user attributes `name`, `family_name`, `given_name`, `middle_name`, `nickname`, `preferred_username`, `profile`, `picture`, `website`, `gender`, `birthdate`, `zoneinfo`, `locale`, and `updated_at`. Also returns [custom attributes](user-pool-settings-attributes.md#user-pool-settings-custom-attributes). In app clients that don't have read access to each attribute, the response to this scope is all of the attributes within the specification that your app client does have read access to.

**`openid email`**  
Returns basic profile information and the `email` and `email_verified` attributes.

**`openid phone`**  
Returns basic profile information and the `phone_number` and `phone_number_verified` attributes.

## GET /oauth2/userInfo
<a name="get-userinfo"></a>

Your application generates requests to this endpoint directly, not through a browser.

For more information, see [UserInfo Endpoint](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo) in the OpenID Connect (OIDC) specification.

**Topics**
+ [

## GET /oauth2/userInfo
](#get-userinfo)
+ [

## Request parameters in header
](#get-userinfo-request-header-parameters)
+ [

## Example – request
](#get-userinfo-positive-exchanging-authorization-code-for-userinfo-sample-request)
+ [

## Example – positive response
](#get-userinfo-response-sample)
+ [

## Example negative responses
](#get-userinfo-negative)

## Request parameters in header
<a name="get-userinfo-request-header-parameters"></a>

**`Authorization: Bearer <access_token>`**  
Pass the access token in the authorization header field.  
Required.

## Example – request
<a name="get-userinfo-positive-exchanging-authorization-code-for-userinfo-sample-request"></a>

```
GET /oauth2/userInfo HTTP/1.1
Content-Type: application/x-amz-json-1.1
Authorization: Bearer eyJra12345EXAMPLE
User-Agent: [User agent]
Accept: */*
Host: auth.example.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
```

## Example – positive response
<a name="get-userinfo-response-sample"></a>

```
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Content-Length: [Integer]
Date: [Timestamp]
x-amz-cognito-request-id: [UUID]
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Server: Server
Connection: keep-alive
{
    "sub": "[UUID]",
    "email_verified": "true",
    "custom:mycustom1": "CustomValue",
    "phone_number_verified": "true",
    "phone_number": "+12065551212",
    "email": "bob@example.com",
    "username": "bob"
}
```

For a list of OIDC claims, see [Standard Claims](http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). Currently, Amazon Cognito returns the values for `email_verified` and `phone_number_verified` as strings.

## Example negative responses
<a name="get-userinfo-negative"></a>

### Example – bad request
<a name="get-userinfo-negative-400"></a>

```
HTTP/1.1 400 Bad Request
WWW-Authenticate: error="invalid_request",
error_description="Bad OAuth2 request at UserInfo Endpoint"
```

**`invalid_request`**  
The request is missing a required parameter, it includes an unsupported parameter value, or it is otherwise malformed.

### Example – bad token
<a name="get-userinfo-negative-401"></a>

```
HTTP/1.1 401 Unauthorized
WWW-Authenticate: error="invalid_token",
error_description="Access token is expired, disabled, or deleted, or the user has globally signed out."
```

**`invalid_token`**  
The access token is expired, revoked, malformed, or it's invalid.

# The token revocation endpoint
<a name="revocation-endpoint"></a>

Users who hold a refresh token in their session have something similar to a browser cookie. They can renew their existing session as long as the refresh token is valid. Instead of prompting a user to sign in after their ID or access token expires, your application can use the refresh token to get new, valid tokens. However, you might externally determine that a user's session should be ended, or the user might elect to forget their current session. At that point, you can revoke that refresh token so that they can no longer persist their session.

The `/oauth2/revoke` endpoint revokes a user's access token that Amazon Cognito initially issued with the refresh token that you provide. This endpoint also revokes the refresh token itself and all subsequent access and identity tokens from the same refresh token. After the endpoint revokes the tokens, you can't use the revoked access tokens to access APIs that Amazon Cognito tokens authenticate.

## POST /oauth2/revoke
<a name="post-revoke"></a>

The `/oauth2/revoke` endpoint only supports `HTTPS POST`. The user pool client makes requests to this endpoint directly and not through the system browser.

### Request parameters in header
<a name="revocation-request-parameters"></a>

**`Authorization`**  
If your app client has a client secret, the application must pass its `client_id` and `client_secret` in the authorization header through Basic HTTP authorization. The secret is [Basic](https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side) `Base64Encode(client_id:client_secret)`.

**`Content-Type`**  
Must always be `'application/x-www-form-urlencoded'`.

#### Request parameters in body
<a name="revocation-request-parameters-body"></a>

**`token`**  
(Required) The refresh token that the client wants to revoke. The request also revokes all access tokens that Amazon Cognito issued with this refresh token.  
Required.

**`client_id`**  
(Optional) The app client ID for the token that you want to revoke.  
Required if the client is public and doesn't have a secret.

## Revocation request examples
<a name="revoke-sample-request"></a>

This revocation request revokes a refresh token for an app client that has no client secret. Note the `client_id` parameter in the request body.

```
POST /oauth2/revoke HTTP/1.1
Host: mydomain.auth.us-east-1.amazoncognito.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
token=2YotnFZFEjr1zCsicMWpAA&
client_id=1example23456789
```

This revocation request revokes a refresh token for an app client that *has* a client secret. Note the `Authorization` header that contains an encoded client ID and client secret, but no `client_id` in the request body.

```
POST /oauth2/revoke HTTP/1.1
Host: mydomain.auth.us-east-1.amazoncognito.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
token=2YotnFZFEjr1zCsicMWpAA
```

## Revocation error response
<a name="revoke-sample-response"></a>

A successful response contains an empty body. The error response is a JSON object with an `error` field and, in some cases, an `error_description` field.

**Endpoint errors**
+ If the token isn't present in the request or if the feature is disabled for the app client, you receive an HTTP 400 and error `invalid_request`.
+ If the token that Amazon Cognito sent in the revocation request isn't a refresh token, you receive an HTTP 400 and error `unsupported_token_type`.
+ If the client credentials aren't valid, you receive an HTTP 401 and error `invalid_client`.
+ If the token has been revoked or if the client submitted a token that isn't valid, you receive an HTTP 200 OK. 

# The IdP SAML assertion endpoint
<a name="saml2-idpresponse-endpoint"></a>

The `/saml2/idpresponse` receives SAML assertions. In service-provider-initiated (SP-initiated) sign-in, your application doesn't interact directly with this endpoint—your SAML 2.0 identity provider (IdP) redirects your user here with their SAML response. For SP-initiated sign-in, configure your IdP with the path to your `saml2/idpresponse` as the assertion consumer service (ACS) URL. For more information about session initiation, see [SAML session initiation in Amazon Cognito user pools](cognito-user-pools-SAML-session-initiation.md).

In IdP-initiated sign-in, invoke requests to this endpoint in your application after you sign in user with your SAML 2.0 provider. Your users sign in with your IdP in their browser, then your application collects the SAML assertion and submits it to this endpoint. You must submit SAML assertions in the body of a `HTTP POST` request over HTTPS. The body of your `POST` request must be a `SAMLResponse` parameter and a `Relaystate` parameter. For more information, see [Implement IdP-initiated SAML sign-in](cognito-user-pools-SAML-session-initiation.md#cognito-user-pools-SAML-session-initiation-idp-initiation).

The `saml2/idpresponse` endpoint can accept SAML assertions of up to 100,000 characters in length.

## POST `/saml2/idpresponse`
<a name="saml2-idpresponse-endpoint-post"></a>

To use the `/saml2/idpresponse` endpoint in an IdP-initiated sign-in, generate a POST request with parameters that provide your user pool with information about your user's session.
+ The app client that they want to sign in to.
+ The callback URL that they want to end up at.
+ The OAuth 2.0 scopes that they want to request in your user's access token.
+ The IdP that initiated the sign-in request.

### IdP-initiated request body parameters
<a name="saml2-idpresponse-endpoint-post-request"></a>

*SAMLResponse*  
A Base64-encoded SAML assertion from an IdP associated with a valid app client and IdP configuration in your user pool.

*RelayState*  
A `RelayState` parameter contains the request parameters that you would otherwise pass to the `oauth2/authorize` endpoint. For detailed information about these parameters, see [Authorize endpoint](authorization-endpoint.md).    
*response\$1type*  
The OAuth 2.0 grant type.  
*client\$1id*  
The app client ID.  
*redirect\$1uri*  
The URL where the authentication server redirects the browser after Amazon Cognito authorizes the user.  
*identity\$1provider*  
The name of the identity provider where you want to redirect your user.  
*idp\$1identifier*  
The identifier of the identity provider where you want to redirect your user.  
*scope*  
The OAuth 2.0 scopes that you want your user to request from the authorization server.

### Example requests with positive responses
<a name="saml2-idpresponse-endpoint-post-example"></a>

**Example – POST request**  
The following request is for an authorization code grant for a user from IdP `MySAMLIdP` in app client `1example23456789`. The user redirects to `https://www.example.com` with their authorization code, which can be exchanged for tokens that include an access token with the OAuth 2.0 scopes `openid`, `email`, and `phone`.

```
POST /saml2/idpresponse HTTP/1.1
User-Agent: USER_AGENT
Accept: */*
Host: example.auth.us-east-1.amazoncognito.com
Content-Type: application/x-www-form-urlencoded

SAMLResponse=[Base64-encoded SAML assertion]&RelayState=identity_provider%3DMySAMLIdP%26client_id%3D1example23456789%26redirect_uri%3Dhttps%3A%2F%2Fwww.example.com%26response_type%3Dcode%26scope%3Demail%2Bopenid%2Bphone
```

**Example – response**  
The following is the response to the previous request.

```
HTTP/1.1 302 Found
Date: Wed, 06 Dec 2023 00:15:29 GMT
Content-Length: 0
x-amz-cognito-request-id: 8aba6eb5-fb54-4bc6-9368-c3878434f0fb
Location: https://www.example.com?code=[Authorization code]
```

# OAuth 2.0 grants
<a name="federation-endpoints-oauth-grants"></a>

The Amazon Cognito user pool OAuth 2.0 authorization server issues tokens in response to three types of OAuth 2.0 [authorization grants](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3). You can set the supported grant types for each app client in your user pool. You can't enable *client credentials* grants in the same app client as either *implicit* or *authorization code* grants. Requests for implicit and authorization code grants begin at your [Authorize endpoint](authorization-endpoint.md) and requests for client credentials grants start at your [Token endpoint](token-endpoint.md).

**Authorization code grant**  
In response to your successful authentication request, the authorization server appends an authorization code in a `code` parameter to your callback URL. You must then exchange the code for ID, access, and refresh tokens with the [Token endpoint](token-endpoint.md). To request an authorization code grant, set `response_type` to `code` in your request. For an example request, see [Example: authorization code grant](authorization-endpoint.md#sample-authorization-code-grant). Amazon Cognito supports [Proof Key for Code Exchange (PKCE)](using-pkce-in-authorization-code.md) in authorization code grants.  
The authorization code grant is the most secure form of authorization grant. It doesn't show token contents directly to your users. Instead, your app is responsible for retrieving and securely storing your user's tokens. In Amazon Cognito, an authorization code grant is the only way to get all three token types—ID, access, and refresh—from the authorization server. You can also get all three token types from authentication through the Amazon Cognito user pools API, but the API doesn't issue access tokens with scopes other than `aws.cognito.signin.user.admin`.

**Implicit grant**  
In response to your successful authentication request, the authorization server appends an access token in an `access_token` parameter, and an ID token in an `id_token` parameter, to your callback URL. An implicit grant requires no additional interaction with the [Token endpoint](token-endpoint.md). To request an implicit grant, set `response_type` to `token` in your request. The implicit grant only generates an ID and access token. For an example request, see [Example: Token (implicit) grant without `openid` scope](authorization-endpoint.md#sample-token-grant-without-openid-scope).  
The implicit grant is a legacy authorization grant. Unlike with the authorization code grant, users can intercept and inspect your tokens. To prevent token delivery through implicit grant, configure your app client to support authorization code grant only.

**Client credentials**  
Client credentials is an authorization-only grant for machine-to-machine access. To receive a client credentials grant, bypass the [Authorize endpoint](authorization-endpoint.md) and generate a request directly to the [Token endpoint](token-endpoint.md). Your app client must have a client secret and support client credentials grants only. In response to your successful request, the authorization server returns an access token.  
The access token from a client credentials grant is an authorization mechanism that contains OAuth 2.0 scopes. Typically, the token contains custom scope claims that authorize HTTP operations to access-protected APIs. For more information, see [Scopes, M2M, and resource servers](cognito-user-pools-define-resource-servers.md).  
Client credentials grants add costs to your AWS bill. For more information, see [Amazon Cognito Pricing](https://aws.amazon.com/cognito/pricing).

**Refresh token**  
You can request a refresh token grant directly from the [Token endpoint](token-endpoint.md). This grant returns new ID and access tokens in exchange for a valid refresh token.

For more perspective on these grants and their implementation, see How to use [OAuth 2.0 in Amazon Cognito: Learn about the different OAuth 2.0 grants](https://aws.amazon.com/blogs/security/how-to-use-oauth-2-0-in-amazon-cognito-learn-about-the-different-oauth-2-0-grants/) in the *AWS Security Blog*.

# Using PKCE in authorization code grants
<a name="using-pkce-in-authorization-code"></a>

Amazon Cognito supports Proof Key for Code Exchange (PKCE) authentication in authorization code grants. PKCE is an extension to the OAuth 2.0 authorization code grant for public clients. PKCE guards against the redemption of intercepted authorization codes.

## How Amazon Cognito uses PKCE
<a name="how-pkce-works"></a>

To start authentication with PKCE, your application must generate a unique string value. This string is the code verifier, a secret value that Amazon Cognito uses to compare the client requesting the initial authorization grant to the client exchanging the authorization code for tokens. 

Your app must apply an SHA256 hash to the code verifier string and encode the result to base64. Pass the hashed string to the [Authorize endpoint](authorization-endpoint.md) as a `code_challenge` parameter in the request body. When your app exchanges the authorization code for tokens, it must include the code verifier string in plaintext as a `code_verifier` parameter in the request body to the [Token endpoint](token-endpoint.md). Amazon Cognito performs the same hash-and-encode operation on the code verifier. Amazon Cognito only returns ID, access, and refresh tokens if it determines that the code verifier results in the same code challenge that it received in the authorization request.

**To implement Authorization Grant Flow with PKCE**

1. Open the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or create a user pool. If you create a user pool, you will be prompted to set up an app client and configure managed login during the wizard.

   1. If you create a new user pool, set up an app client and configure managed login during the guided setup.

   1. If you configure an existing user pool, add a [domain](cognito-user-pools-assign-domain.md) and a [public app client](user-pool-settings-client-apps.md), if you haven’t already.

1. Generate a random alphanumeric string, typically a universally unique identifier ([UUID](cognito-terms.md#terms-uuid)), to create a code challenge for the PKCE. This string is the value of the `code_verifier` parameter that you will submit in your request to the [Token endpoint](token-endpoint.md). 

1. Hash the `code_verifier` string with the SHA256 algorithm. Encode the result of the hashing operation to base64. This string is the value of the `code_challenge` parameter that you will submit in your request to the [Authorize endpoint](authorization-endpoint.md). 

   The following Python example generates a `code_verifier` and calculates the `code_challenge`:

   ```
   #!/usr/bin/env python3
   
   import secrets
   from base64 import urlsafe_b64encode
   from hashlib import sha256
   from string import ascii_letters
   from string import digits
   
   # use the secrets module for cryptographically strong random values
   alphabet = ascii_letters + digits
   code_verifier = ''.join(secrets.choice(alphabet) for _ in range(128))
   code_verifier_hash = sha256(code_verifier.encode()).digest()
   code_challenge = urlsafe_b64encode(code_verifier_hash).decode().rstrip('=')
   
   print(f"code challenge: {code_challenge}")
   print(f"code verifier: {code_verifier}")
   ```

   The following is an example output from the Python script:

   ```
   code challenge: Eh0mg-OZv7BAyo-tdv_vYamx1boOYDulDklyXoMDtLg
   code verifier: 9D-aW_iygXrgQcWJd0y0tNVMPSXSChIc2xceDhvYVdGLCBk-JWFTmBNjvKSdOrjTTYazOFbUmrFERrjWx6oKtK2b6z_x4_gHBDlr4K1mRFGyE8yA-05-_v7Dxf3EIYJH
   ```

1. Complete managed login sign-in with an authorization code grant request with PKCE. The following is an example URL:

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com&code_challenge=Eh0mg-OZv7BAyo-tdv_vYamx1boOYDulDklyXoMDtLg&code_challenge_method=S256
   ```

1. Collect the authorization `code` and redeem it for tokens with the token endpoint. The following is an example request:

   ```
   POST /oauth2/token HTTP/1.1
   Host: mydomain.auth.us-east-1.amazoncognito.com
   Content-Type: application/x-www-form-urlencoded
   Content-Length: 296
   
   redirect_uri=https%3A%2F%2Fwww.example.com&
   client_id=1example23456789&
   code=7378f445-c87f-400c-855e-0297d072ff03&
   grant_type=authorization_code&
   code_verifier=9D-aW_iygXrgQcWJd0y0tNVMPSXSChIc2xceDhvYVdGLCBk-JWFTmBNjvKSdOrjTTYazOFbUmrFERrjWx6oKtK2b6z_x4_gHBDlr4K1mRFGyE8yA-05-_v7Dxf3EIYJH
   ```

1. Review the response. It will contain ID, access, and refresh tokens. For more information about using Amazon Cognito user pool tokens, see [Understanding user pool JSON web tokens (JWTs)](amazon-cognito-user-pools-using-tokens-with-identity-providers.md).

# Managed login and federation error responses
<a name="federation-endpoint-idp-responses"></a>

A sign-in process in managed login or federated sign-in might return an error. The following are some conditions that can cause authentication to end with an error.
+ A user performs an operation that your user pool can't fulfill.
+ A Lambda trigger doesn't respond with expected syntax.
+ Your identity provider (IdP) returns an error.
+ Amazon Cognito couldn't validate attribute information that your user provided.
+ Your IdP didn't send claims that map to required attributes.

When Amazon Cognito encounters an error, it communicates it in one of the following ways.

1. Amazon Cognito sends a redirect URL with the error in the request parameters.

1. Amazon Cognito displays an error in managed login.

Errors that Amazon Cognito appends to request parameters have the following format.

```
https://<Callback URL>/?error_description=error+description&error=error+name
```

When you help your users submit error information when they can't perform an operation, request that they capture the URL *and* the text or a screenshot of the page.

**Note**  
Amazon Cognito error descriptions are not fixed strings and you shouldn't use logic that relies on a fixed pattern or format.

**OIDC and social identity provider error messages**  
Your identity provider might return an error. When an OIDC or OAuth 2.0 IdP returns an error that conforms to standards, Amazon Cognito redirects your user to the callback URL and adds the provider error response to error request parameters. Amazon Cognito adds the provider name and HTTP error code to the existing error strings.

The following URL is an example redirect from an IdP that returned an error to Amazon Cognito.

```
https://www.amazon.com/?error_description=LoginWithAmazon+Error+-+400+invalid_request+The+request+is+missing+a+required+parameter+%3A+client_secret&error=invalid_request
```

Because Amazon Cognito only returns what it receives from a provider, your user might see a subset of this information. 

When your user encounters an issue with initial sign-in through your IdP, the IdP delivers any error messages directly to your user. Amazon Cognito relays an error message to your user when it generates a request to your IdP to validate your user's session. Amazon Cognito relays OAuth and OIDC IdP error messages from the following endpoints.

`/token`  
Amazon Cognito exchanges an IdP authorization code for an access token.

`/.well-known/openid-configuration`  
Amazon Cognito discovers the path to your issuer endpoints.

`/.well-known/jwks.json`  
To verify your user's JSON Web Tokens (JWTs), Amazon Cognito discovers the JSON Web Keys (JWKs) that your IdP uses to sign tokens.

Because Amazon Cognito doesn't initiate outbound sessions to SAML 2.0 providers that might return HTTP errors, your users' errors during a session with a SAML 2.0 IdP don't include this form of provider error message.