Cognito DG
Cognito DG
Cognito DG
Developer Guide
Amazon Cognito Developer Guide
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
Amazon Cognito Developer Guide
Table of Contents
What Is Amazon Cognito? ................................................................................................................... 1
Features of Amazon Cognito ....................................................................................................... 2
Getting Started with Amazon Cognito .......................................................................................... 2
Regional Availability ................................................................................................................... 3
Pricing for Amazon Cognito ........................................................................................................ 3
Using the Amazon Cognito Console .............................................................................................. 3
Getting Started with Amazon Cognito .................................................................................................. 5
Common Amazon Cognito Scenarios .................................................................................................... 6
Authenticate with a User Pool ..................................................................................................... 6
Access Your Server-side Resources ................................................................................................ 6
Access Resources with API Gateway and Lambda ............................................................................ 7
Access AWS Services with a User Pool and an Identity Pool ............................................................. 8
Authenticate with a Third Party and Access AWS Services with an Identity Pool .................................. 8
Access AWS AppSync Resources with Amazon Cognito .................................................................... 9
Tutorials .......................................................................................................................................... 10
Creating a User Pool ................................................................................................................. 10
Related Resources ............................................................................................................ 10
Creating an Identity Pool .......................................................................................................... 10
Related Resources ............................................................................................................ 11
Cleaning Up Your AWS Resources ............................................................................................... 11
Integrating With Apps ....................................................................................................................... 12
Amazon Cognito Authentication With the AWS Amplify Framework ................................................ 12
Multi-tenant Application Best Practices ............................................................................................... 13
User pool-based multi-tenancy .................................................................................................. 13
Application client-based multi-tenancy ....................................................................................... 14
Group-based multi-tenancy ....................................................................................................... 14
Custom attribute-based multi-tenancy ........................................................................................ 14
Multi-tenancy security recommendations ..................................................................................... 15
Amazon Cognito user pools ............................................................................................................... 16
Getting Started with User Pools ................................................................................................. 17
Prerequisite: Sign Up for an AWS Account ........................................................................... 17
Step 1. Create a User Pool ................................................................................................ 17
Step 2. Add an App to Enable the Hosted Web UI ................................................................ 18
Step 3. Add Social Sign-in to a User Pool (Optional) ............................................................. 19
Step 4. Add Sign-in with a SAML Identity Provider to a User Pool (Optional) ............................. 24
Next Steps ....................................................................................................................... 26
Using the Hosted UI ................................................................................................................. 26
Setting Up the Hosted UI with AWS Amplify ........................................................................ 27
Setting Up the Hosted UI with the Amazon Cognito Console .................................................. 27
Configuring an App Client ................................................................................................. 29
Configuring a Domain ....................................................................................................... 32
Customizing the Built-in Webpages .................................................................................... 37
Defining Resource Servers ................................................................................................. 41
Adding Sign-in Through a Third Party ......................................................................................... 43
Adding Social Identity Providers ......................................................................................... 43
Adding SAML Providers ..................................................................................................... 49
Adding OIDC Providers ...................................................................................................... 56
Specifying Attribute Mappings ........................................................................................... 61
Using Lambda Triggers ............................................................................................................. 64
Important Considerations .................................................................................................. 66
Using Lambda Triggers ..................................................................................................... 66
User Pool Lambda Trigger Event ........................................................................................ 66
User Pool Lambda Trigger Common Parameters ................................................................... 67
Lambda Trigger Sources .................................................................................................... 67
iii
Amazon Cognito Developer Guide
iv
Amazon Cognito Developer Guide
v
Amazon Cognito Developer Guide
Updating the Logins Map (Android and iOS only) ............................................................... 241
Getting a Token (Server Side) ........................................................................................... 241
Connect to an Existing Social Identity ............................................................................... 242
Supporting Transition Between Providers .......................................................................... 243
Switching Identities ................................................................................................................ 245
Android ......................................................................................................................... 245
iOS - Objective-C ............................................................................................................ 246
iOS - Swift .................................................................................................................... 246
JavaScript ...................................................................................................................... 246
Unity ............................................................................................................................. 247
Xamarin ......................................................................................................................... 247
Amazon Cognito Sync ..................................................................................................................... 248
Getting Started with Amazon Cognito Sync ............................................................................... 248
Sign Up for an AWS Account ........................................................................................... 248
Set Up an Identity Pool in Amazon Cognito ....................................................................... 249
Store and Sync Data ....................................................................................................... 249
Synchronizing Data ................................................................................................................. 249
Initializing the Amazon Cognito Sync Client ....................................................................... 249
Understanding Datasets .................................................................................................. 251
Reading and Writing Data in Datasets ............................................................................... 252
Synchronizing Local Data with the Sync Store .................................................................... 254
Handling Callbacks ................................................................................................................. 256
Android ......................................................................................................................... 256
iOS - Objective-C ............................................................................................................ 258
iOS - Swift .................................................................................................................... 260
JavaScript ...................................................................................................................... 262
Unity ............................................................................................................................. 264
Xamarin ......................................................................................................................... 266
Push Sync .............................................................................................................................. 268
Create an Amazon Simple Notification Service (Amazon SNS) App ........................................ 268
Enable Push Sync in the Amazon Cognito console .............................................................. 268
Use Push Sync in Your App: Android ................................................................................. 269
Use Push Sync in Your App: iOS - Objective-C .................................................................... 270
Use Push Sync in Your App: iOS - Swift ............................................................................. 272
Amazon Cognito Streams ........................................................................................................ 274
Amazon Cognito Events .......................................................................................................... 275
Security ......................................................................................................................................... 279
Data Protection ...................................................................................................................... 279
Data Encryption ............................................................................................................. 280
Identity and Access Management .............................................................................................. 280
Amazon Resource Names (ARNs) ...................................................................................... 280
Example Policies ............................................................................................................. 281
Managed Policies ............................................................................................................ 282
Signed versus Unsigned APIs ............................................................................................ 282
Using Service-Linked Roles .............................................................................................. 283
Authentication ............................................................................................................... 286
Logging and Monitoring .......................................................................................................... 292
Tracking quotas and usage in CloudWatch and Service Quotas ............................................. 292
Metrics for Amazon Cognito user pools ............................................................................. 293
Dimensions for Amazon Cognito user pools ....................................................................... 297
Use the Service Quotas console to track metrics ................................................................. 298
Use the CloudWatch console to track metrics ..................................................................... 298
Create a CloudWatch alarm for a quota ............................................................................. 299
Logging Amazon Cognito API Calls with AWS CloudTrail ...................................................... 299
Compliance Validation ............................................................................................................. 301
Resilience .............................................................................................................................. 302
Regional Data Considerations ........................................................................................... 302
vi
Amazon Cognito Developer Guide
vii
Amazon Cognito Developer Guide
The two main components of Amazon Cognito are user pools and identity pools. User pools are user
directories that provide sign-up and sign-in options for your app users. Identity pools enable you to
grant your users access to other AWS services. You can use identity pools and user pools separately or
together.
See the diagram for a common Amazon Cognito scenario. Here the goal is to authenticate your user, and
then grant your user access to another AWS service.
1. In the first step your app user signs in through a user pool and receives user pool tokens after a
successful authentication.
2. Next, your app exchanges the user pool tokens for AWS credentials through an identity pool.
3. Finally, your app user can then use those AWS credentials to access other AWS services such as
Amazon S3 or DynamoDB.
For more examples using identity pools and user pools, see Common Amazon Cognito
Scenarios (p. 6).
Amazon Cognito is compliant with SOC 1-3, PCI DSS, ISO 27001, and is HIPAA-BAA eligible. For more
information, see AWS Services in Scope. See also Regional Data Considerations (p. 302).
Topics
• Features of Amazon Cognito (p. 2)
1
Amazon Cognito Developer Guide
Features of Amazon Cognito
A user pool is a user directory in Amazon Cognito. With a user pool, your users can sign in to your web or
mobile app through Amazon Cognito, or federate through a third-party identity provider (IdP). Whether
your users sign in directly or through a third party, all members of the user pool have a directory profile
that you can access through an SDK.
For more information about user pools, see Getting Started with User Pools (p. 17) and the Amazon
Cognito user pools API Reference.
Identity pools
With an identity pool, your users can obtain temporary AWS credentials to access AWS services, such
as Amazon S3 and DynamoDB. Identity pools support anonymous guest users, as well as the following
identity providers that you can use to authenticate users for identity pools:
To save user profile information, your identity pool needs to be integrated with a user pool.
For more information about identity pools, see Getting Started with Amazon Cognito Identity Pools
(Federated Identities) (p. 180) and the Amazon Cognito Identity Pools API Reference.
2
Amazon Cognito Developer Guide
Regional Availability
For videos, articles, documentation, and sample apps, see Amazon Cognito Developer Resources.
To use Amazon Cognito, you need an AWS account. For more information, see Using the Amazon Cognito
Console (p. 3).
Regional Availability
Amazon Cognito is available in multiple AWS Regions worldwide. In each Region, Amazon Cognito is
distributed across multiple Availability Zones. These Availability Zones are physically isolated from
each other, but are united by private, low-latency, high-throughput, and highly redundant network
connections. These Availability Zones enable AWS to provide services, including Amazon Cognito, with
very high levels of availability and redundancy, while also minimizing latency.
For a list of all the Regions where Amazon Cognito is currently available, see AWS Regions and Endpoints
in the Amazon Web Services General Reference. To learn more about the number of Availability Zones that
are available in each Region, see AWS Global Infrastructure.
For more information, see Getting Started with User Pools (p. 17).
4. To create or edit an identity pool, choose Manage Identity Pools.
For more information, see Getting Started with Amazon Cognito Identity Pools (Federated
Identities) (p. 180).
The Amazon Cognito console is a part of the AWS Management Console, which provides information
about your account and billing. For more information, see Working with the AWS Management Console.
3
Amazon Cognito Developer Guide
Using the Amazon Cognito Console
4
Amazon Cognito Developer Guide
The two main components of Amazon Cognito are user pools and identity pools. User pools are user
directories that provide sign-up and sign-in options for your web and mobile app users. Identity pools
provide AWS credentials to grant your users access to other AWS services. You can use user pools and
identity pools separately or together.
Access Resources
5
Amazon Cognito Developer Guide
Authenticate with a User Pool
The two main components of Amazon Cognito are user pools and identity pools. User pools are user
directories that provide sign-up and sign-in options for your web and mobile app users. Identity pools
provide AWS credentials to grant your users access to other AWS services.
A user pool is a user directory in Amazon Cognito. Your app users can sign in either directly through a
user pool, or 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. Whether your users sign in directly or through a
third party, all members of the user pool have a directory profile that you can access through an SDK.
With an identity pool, your users can obtain temporary AWS credentials to access AWS services, such
as Amazon S3 and DynamoDB. Identity pools support anonymous guest users, as well as federation
through third-party IdPs.
Topics
• Authenticate with a User Pool (p. 6)
• Access Your Server-side Resources with a User Pool (p. 6)
• Access Resources with API Gateway and Lambda with a User Pool (p. 7)
• Access AWS Services with a User Pool and an Identity Pool (p. 8)
• Authenticate with a Third Party and Access AWS Services with an Identity Pool (p. 8)
• Access AWS AppSync Resources with Amazon Cognito (p. 9)
After a successful authentication, your web or mobile app will receive user pool tokens from Amazon
Cognito. You can use those tokens to retrieve AWS credentials that allow your app to access other AWS
services, or you might choose to use them to control access to your server-side resources, or to the
Amazon API Gateway.
For more information, see User Pool Authentication Flow (p. 287) and Using Tokens with User
Pools (p. 144).
6
Amazon Cognito Developer Guide
Access Resources with API Gateway and Lambda
user pool groups to manage permissions, and to represent different types of users. For more information
on using groups to control access your resources see Adding Groups to a User Pool (p. 124).
Once you configure a domain for your user pool, Amazon Cognito provisions a hosted web UI that allows
you to add sign-up and sign-in pages to your app. Using this OAuth 2.0 foundation you can create
your own resource server to enable your users to access protected resources. For more information see
Defining Resource Servers for Your User Pool (p. 41).
For more information about user pool authentication see User Pool Authentication Flow (p. 287) and
Using Tokens with User Pools (p. 144).
You can use groups in a user pool to control permissions with API Gateway by mapping group
membership to IAM roles. The groups that a user is a member of are included in the ID token provided by
a user pool when your app user signs in. For more information on user pool groups See Adding Groups to
a User Pool (p. 124).
You can submit your user pool tokens with a request to API Gateway for verification by an Amazon
Cognito authorizer Lambda function. For more information on API Gateway, see Using API Gateway with
Amazon Cognito user pools.
7
Amazon Cognito Developer Guide
Access AWS Services with a User Pool and an Identity Pool
8
Amazon Cognito Developer Guide
Access AWS AppSync Resources with Amazon Cognito
9
Amazon Cognito Developer Guide
Creating a User Pool
Topics
• Tutorial: Creating a User Pool (p. 10)
• Tutorial: Creating an Identity Pool (p. 10)
• Tutorial: Cleaning Up Your AWS Resources (p. 11)
1. Go to the Amazon Cognito console. You may be prompted for your AWS credentials.
2. Choose Manage User Pools.
3. Choose Create a user pool.
4. Provide a name for your user pool and choose Review defaults to save the name.
5. On the Review page, choose Create pool.
Related Resources
For more information on user pools, see Amazon Cognito user pools (p. 16).
See also User Pool Authentication Flow (p. 287) and Using Tokens with User Pools (p. 144).
1. Go to the Amazon Cognito console. You may be prompted for your AWS credentials.
2. Choose Manage Identity Pools
3. Choose Create new identity pool.
4. Enter a name for your identity pool.
5. To enable unauthenticated identities select Enable access to unauthenticated identities from the
Unauthenticated identities collapsible section.
6. Choose Create Pool.
7. You will be prompted for access to your AWS resources.
10
Amazon Cognito Developer Guide
Related Resources
Choose Allow to create the two default roles associated with your identity pool–one for
unauthenticated users and one for authenticated users. These default roles provide your identity
pool access to Amazon Cognito Sync. You can modify the roles associated with your identity pool in
the IAM console.
8. Make a note of your identity pool Id number. You will use it to set up policies allowing your app
users to access other AWS services such as Amazon Simple Storage Service or DynamoDB
Related Resources
For more information on identity pools, see Amazon Cognito Identity Pools (Federated
Identities) (p. 180).
For an S3 example using an identity pool see Uploading Photos to Amazon S3 from a Browser.
1. Go to the Amazon Cognito console. You may be prompted for your AWS credentials.
2. Choose Manage Identity Pools.
3. Choose the name of the identity pool that you want to delete. The Dashboard page for your identity
pool appears.
4. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool
page appears.
5. Scroll down and choose Delete identity pool to expand it.
6. Choose Delete identity pool.
7. Choose Delete pool.
1. Go to the Amazon Cognito console. You may be prompted for your AWS credentials.
2. Manage User Pools.
3. Choose the user pool you created in the previous step.
4. On the Domain name page under App integration select Delete domain.
5. Choose Delete domain when prompted to confirm.
6. Go to the General Settings page.
7. Select Delete pool in the upper right corner of the page.
8. Enter delete and choose Delete pool when prompted to confirm.
11
Amazon Cognito Developer Guide
Amazon Cognito Authentication
With the AWS Amplify Framework
To use the AWS Amplify framework to add authentication to your app, see the AWS Amplify
authorization documentation for your platform:
12
Amazon Cognito Developer Guide
User pool-based multi-tenancy
You have four ways to secure multi-tenant applications: user pools, application clients, groups, or custom
attributes.
Topics
• User pool-based multi-tenancy (p. 13)
• Application client-based multi-tenancy (p. 14)
• Group-based multi-tenancy (p. 14)
• Custom attribute-based multi-tenancy (p. 14)
• Multi-tenancy security recommendations (p. 15)
• Your application has different configurations for each tenant. For example, data residency
requirements, password policy, and MFA configurations can be different for each tenant.
• Your application has complex user-to-tenant role mapping. For example, a single user could be a
“Student” in tenant A and the same user could also be a “Teacher” in tenant B.
• Your application uses the default Amazon Cognito hosted UI as the primary authentication method
for native users. (Native users are those that have been created in the user pool with user name and
password).
• Your application has a silo multi-tenant application where each tenant gets a full instance of your
application infrastructure for their usage.
Effort level
13
Amazon Cognito Developer Guide
Application client-based multi-tenancy
The development and operation effort to use this approach is high. You need to build tenant onboarding
and administration components into your application that uses Amazon Cognito API operations and
automation tools. These components are necessary to create the required resources for each tenant.
You also need to implement a tenant-matching user interface. In addition, you must add logic to your
application that allows users to sign up and sign in to their corresponding tenant’s user pool.
Note
The SaaS identity and isolation with Amazon Cognito quick start provides reference architecture
and sample implementation for the user-pool-per-tenant approach.
Application client-based multi-tenancy requires additional considerations for user name, password,
and more when you use hosted UI to authenticate users with native accounts. When the hosted UI is in
use, a session cookie is created to maintain the session for the authenticated user. The session cookie
also provides SSO between application clients in the same user pool. This approach can be used in the
following scenarios:
• Your application has the same configurations across all tenants. For example, data residency and
password policy are the same across all tenants.
• Your application has a one-to-many mapping between user and tenants. For example, a single user
could have access to multiple tenants using the same profile.
• You have a federation-only multi-tenant application where tenants will always use an external IdP to
sign in to your application.
• You have a B2B multi-tenant application and tenants backend services will use client-credentials grant
to access your services. In this case, you can create application client for each tenant and share the
client-id and secret with tenant backend service for machine-to-machine authentication.
Effort level
The development effort to use this approach is high. You need to implement tenant-matching logic and
a user interface to match a user to the application client for their tenant.
Group-based multi-tenancy
With group-based multi-tenancy, you can associate an Amazon Cognito user pool group with a tenant.
That way you can use additional functionality through role-based access control (RBAC). For more
information see, Role-based access control.
14
Amazon Cognito Developer Guide
Multi-tenancy security recommendations
• Avoid using an unverified email address to authorize user access to a tenant based on domain match.
Email addresses and phone numbers shouldn’t be trusted unless they are verified by your application
or a proof of verification is given by the external IdP. For more details on setting these permissions, see
Attribute Permissions and Scopes.
• Make sure that user profile attributes used to identify tenants are immutable or mutable attributes
that can be changed by administrators. Application clients should have read-only access to these
attributes.
• Ensure you have 1:1 mapping between external IdP and application client to prevent unauthorized
cross-tenant access. This could happen if a user has a valid Amazon Cognito session cookie and their
external IdP is allowed on multiple application clients.
• When implementing tenant-matching and authorization logic in your application, ensure that the
criteria used to authorize user access to the tenant3s6can't be modified by users themselves. You
should also ensure that user access can't be modified by the tenant identity provider administrators (if
an external IdP is being used for federation).
15
Amazon Cognito Developer Guide
After successfully authenticating a user, Amazon Cognito issues JSON web tokens (JWT) that you can use
to secure and authorize access to your own APIs, or exchange for AWS credentials.
Amazon Cognito provides token handling through the Amazon Cognito user pools Identity SDKs for
JavaScript, Android, and iOS. See Getting Started with User Pools (p. 17) and Using Tokens with User
Pools (p. 144).
The two main components of Amazon Cognito are user pools and identity pools. Identity pools provide
AWS credentials to grant your users access to other AWS services. To enable users in your user pool
to access AWS resources, you can configure an identity pool to exchange user pool tokens for AWS
credentials. For more information see Accessing AWS Services Using an Identity Pool After Sign-
in (p. 153) and Getting Started with Amazon Cognito Identity Pools (Federated Identities) (p. 180).
Topics
• Getting Started with User Pools (p. 17)
• Using the Amazon Cognito Hosted UI for Sign-Up and Sign-In (p. 26)
• Adding User Pool Sign-in Through a Third Party (p. 43)
• Customizing User Pool Workflows with Lambda Triggers (p. 64)
• Using Amazon Pinpoint Analytics with Amazon Cognito User Pools (p. 111)
• Managing Users in User Pools (p. 113)
• Email Settings for Amazon Cognito User Pools (p. 140)
• Using Tokens with User Pools (p. 144)
• Accessing Resources After a Successful User Pool Authentication (p. 152)
• User Pools Reference (AWS Management Console) (p. 156)
• Managing error responses (p. 178)
16
Amazon Cognito Developer Guide
Getting Started with User Pools
Topics
• Prerequisite: Sign Up for an AWS Account (p. 17)
• Step 1. Create a User Pool (p. 17)
• Step 2. Add an App to Enable the Hosted Web UI (p. 18)
• Step 3. Add Social Sign-in to a User Pool (Optional) (p. 19)
• Step 4. Add Sign-in with a SAML Identity Provider to a User Pool (Optional) (p. 24)
• Next Steps (p. 26)
1. Open https://portal.aws.amazon.com/billing/signup.
2. Follow the online instructions.
Part of the sign-up procedure involves receiving a phone call and entering a verification code on the
phone keypad.
Next Step
Step 1. Create a User Pool (p. 17)
1. Go to the Amazon Cognito console. You might be prompted for your AWS credentials.
2. Choose Manage User Pools.
3. In the top-right corner of the page, choose Create a user pool.
4. Provide a name for your user pool, and choose Review defaults to save the name.
5. In the top-left corner of the page, choose Attributes, choose Email address or phone number and
Allow email addresses, and then choose Next step to save.
Note
We recommend that you enable case insensitivity on the username attribute before you
create your user pool. For example, when this option is selected, users will be able to
sign in using either "username" or "Username". Enabling this option also enables both
preferred_username and email alias to be case insensitive, in addition to the username
attribute. For more information, see CreateUserPool in the Amazon Cognito user pools API
Reference.
6. In the left navigation menu, choose Review.
17
Amazon Cognito Developer Guide
Step 2. Add an App to Enable the Hosted Web UI
7. Review the user pool information and make any necessary changes. When the information is correct,
choose Create pool.
Next Step
Step 2. Add an App to Enable the Hosted Web UI (p. 18)
1. Go to the Amazon Cognito console. You might be prompted for your AWS credentials.
2. Choose Manage User Pools.
3. Choose an existing user pool from the list, or create a user pool.
4. On the navigation bar on the left-side of the page, choose App clients under General settings.
5. Choose Add an app client.
6. Give your app a name.
7. Clear the option Generate client secret for the purposes of this getting started exercise, as it
would not be secure to send it on the URL using client-side JavaScript. The client secret is used by
applications that have a server-side component that can secure the client secret.
8. Choose Create app client.
9. Note the App client ID.
10. Choose Return to pool details.
11. Choose App client settings from the navigation bar on the left-side of the console page.
12. Select Cognito User Pool as one of the Enabled Identity Providers.
Note
To sign in with external identity providers (IdPs) such as Facebook, Amazon, Google, and
Apple, as well as through OpenID Connect (OIDC) or SAML IdPs, first configure them as
described next, and then return to the App client settings page to enable them.
13. Enter a callback URL for the Amazon Cognito authorization server to call after users are
authenticated. For a web app, the URL should start with https://, such as https://
www.example.com.
For an iOS or Android app, you can use a callback URL such as myapp://.
14. Enter a Sign out URL.
15. Select Authorization code grant to return an authorization code that is then exchanged for user
pool tokens. Because the tokens are never exposed directly to an end user, they are less likely to
become compromised. However, a custom application is required on the backend to exchange the
authorization code for user pool tokens. For security reasons, we recommend that you use the
authorization code grant flow, together with Proof Key for Code Exchange (PKCE), for mobile apps.
16. Under Allowed OAuth Flows, select Implicit grant to have user pool JSON web tokens (JWT)
returned to you from Amazon Cognito. You can use this flow when there's no backend available to
exchange an authorization code for tokens. It's also helpful for debugging tokens.
Note
You can enable both the Authorization code grant and the Implicit code grant, and then
use each grant as needed.
17. Unless you specifically want to exclude one, select the check boxes for all of the Allowed OAuth
scopes.
18
Amazon Cognito Developer Guide
Step 3. Add Social Sign-in to a User Pool (Optional)
Note
Select Client credentials only if your app needs to request access tokens on its own behalf,
not on behalf of a user.
18. Choose Save changes.
19. On the Domain name page, type a domain prefix that's available.
20. Make a note of the complete domain address.
21. Choose Save changes.
You can view the hosted UI sign-in webpage with the following URL. Note the response_type. In this
case, response_type=code for the authorization code grant.
https://your_domain/login?
response_type=code&client_id=your_app_client_id&redirect_uri=your_callback_url
You can view the hosted UI 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://your_domain/login?
response_type=token&client_id=your_app_client_id&redirect_uri=your_callback_url
You can find the JSON web token (JWT) identity token after the #idtoken= parameter in the response.
Here's a sample response from an implicit grant request. Your identity token string will be much longer.
https://www.example.com/
#id_token=123456789tokens123456789&expires_in=3600&token_type=Bearer
You can decode and verify user pool tokens using AWS Lambda, see Decode and verify Amazon Cognito
JWT tokens on the AWS GitHub website.
Amazon Cognito user pools tokens are signed using an RS256 algorithm.
You might have to wait a minute to refresh your browser before changes you made in the console
appear.
Your domain is shown on the Domain name page. Your app client ID and callback URL are shown on the
General settings page.
Next Step
Step 3. Add Social Sign-in to a User Pool (Optional) (p. 19)
19
Amazon Cognito Developer Guide
Step 3. Add Social Sign-in to a User Pool (Optional)
https://<your-user-pool-domain>/oauth2/idpresponse
https://<your-user-pool-domain>
Type your redirect URL into Valid OAuth Redirect URIs. It will consist of your user pool domain with
the /oauth2/idpresponse endpoint.
https://<your-user-pool-domain>/oauth2/idpresponse
Choose Apps and Services from navigation bar at the top of the page and then choose Login with
Amazon.
4. Choose Create a Security Profile.
5. Type in a Security Profile Name, a Security Profile Description, and a Consent Privacy Notice URL.
6. Choose Save.
7. Choose Client ID and Client Secret to show the client ID and secret. You will use them in the next
section.
20
Amazon Cognito Developer Guide
Step 3. Add Social Sign-in to a User Pool (Optional)
8. Hover over the gear and choose Web Settings, and then choose Edit.
9. Type your user pool domain into Allowed Origins.
https://<your-user-pool-domain>
10. Type your user pool domain with the /oauth2/idpresponse endpoint into Allowed Return URLs.
https://<your-user-pool-domain>/oauth2/idpresponse
https://<your-user-pool-domain>
8. Choose CREATE. You will not use the Client ID and Client Secret from this step.
9. Choose DONE.
10. Sign in to the Google Console.
11. On the left navigation bar, choose Credentials.
12. Create your OAuth 2.0 credentials by choosing OAuth client ID from the Create credentials drop-
down list.
13. Choose Web application.
14. Type your user pool domain into Authorized JavaScript origins.
https://<your-user-pool-domain>
15. Type your user pool domain with the /oauth2/idpresponse endpoint into Authorized Redirect
URIs.
https://<your-user-pool-domain>/oauth2/idpresponse
21
Amazon Cognito Developer Guide
Step 3. Add Social Sign-in to a User Pool (Optional)
https://<your-user-pool-domain>/oauth2/idpresponse
5. Choose Add, and then Save. You do not need to verify the domain.
6. Choose Continue, and then choose Register.
12. On the left navigation bar, choose Keys.
13. On the Keys page, choose the + icon.
14. On the Register a New Key page, do the following:
22
Amazon Cognito Developer Guide
Step 3. Add Social Sign-in to a User Pool (Optional)
To configure a user pool social identity provider with the AWS Management Console
1. Go to the Amazon Cognito console. You might be prompted for your AWS credentials.
2. Choose Manage your User Pools.
3. Choose an existing user pool from the list, or create a user pool.
4. On the left navigation bar, choose Identity providers.
5. Choose a social identity provider: Facebook, Google, Login with Amazon, or Apple.
6. For Google and Login with Amazon, type the app client ID and app client secret that you received
from the social identity provider in the previous section. For Facebook, type the app client ID, app
client secret that you received from the social identity provider in the previous section, and choose
an API version. We recommend choosing the highest available possible version as each Facebook
API version has a lifecycle and a deprecation date for example, version 2.12. You can change the API
version post creation if you encounter any issues. The Facebook scopes and attributes may vary with
each API version, so we recommend testing your integration.” For Sign in with Apple, provide the
Services ID, Team ID, Key ID, and private key that you received in the previous section.
7. Type the names of the scopes that you want to authorize. 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.
Your app user is asked to consent to providing these attributes to your app. For more information
about their scopes, see the documentation from Google, Facebook, Login with Amazon, or Sign in
with Apple.
In the case of 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 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
8. Choose Enable for the social identity provider that you are configuring.
9. Choose App client settings from the navigation bar.
10. Select your social identity provider as one of the Enabled Identity Providers for your user pool app.
11. Type your callback URL into Callback URL(s) for your user pool app. This is the URL of the page
where your user will be redirected after a successful authentication.
https://www.example.com
23
Amazon Cognito Developer Guide
Step 4. Add Sign-in with a SAML Identity
Provider to a User Pool (Optional)
a. Select the check box to choose the Facebook, Google, or Amazon attribute name. You can also
type the names of additional attributes that are not listed in the Amazon Cognito console.
b. Choose the destination user pool attribute from the drop-down list.
c. Choose Save changes.
d. Choose Go to summary.
https://<your_user_pool_domain>/login?
response_type=code&client_id=<your_client_id>&redirect_uri=https://www.example.com
You can find your domain on the user pool Domain name console page. The client_id is on the App
client settings page. Use your callback URL for the redirect_uri parameter. This is the URL of the page
where your user will be redirected after a successful authentication.
Note
Requests that are not completed within 5 minutes will be cancelled, redirected to the login
page, and then display a Something went wrong error message.
Next Step
Step 4. Add Sign-in with a SAML Identity Provider to a User Pool (Optional) (p. 24)
You need to update your SAML identity provider and configure your user pool. See the documentation
for your SAML identity provider for information about how to add your user pool as a relying party or
application for your SAML 2.0 identity provider.
You also need to provide an assertion consumer endpoint to your SAML identity provider. Configure this
endpoint for SAML 2.0 POST binding in your SAML identity provider:
https://<yourDomainPrefix>.auth.<region>.amazoncognito.com/saml2/idpresponse
You can find your domain prefix and the region value for your user pool on the Domain name tab of the
Amazon Cognito console.
For some SAML identity providers, you also need to provide the SP urn / Audience URI / SP Entity ID, in
the form:
24
Amazon Cognito Developer Guide
Step 4. Add Sign-in with a SAML Identity
Provider to a User Pool (Optional)
urn:amazon:cognito:sp:<yourUserPoolID>
You can find your user pool ID on the General settings tab in the Amazon Cognito console.
You should also configure your SAML identity provider to provide attribute values for any attributes that
are required in your user pool. Typically, email is a required attribute for user pools. In that case, the
SAML identity provider should provide an email value (claim) in the SAML assertion.
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 identity provider via a user agent.
1. Go to the Amazon Cognito console. You might be prompted for your AWS credentials.
2. Manage User Pools.
3. Choose an existing user pool from the list, or create a user pool.
4. On the left navigation bar, choose Identity providers.
5. Choose SAML to open the SAML dialog.
6. Under Metadata document upload a metadata document from your SAML IdP. You can also enter a
URL that points to the metadata document. For more information, see Integrating Third-Party SAML
Identity Providers with Amazon Cognito User Pools (p. 55).
Note
We recommend that you provide the endpoint URL if it is a public endpoint, rather
than uploading a file, because this allows Amazon Cognito to refresh the metadata
automatically. Typically metadata refresh happens every 6 hours or before the metadata
expires, whichever is earlier.
7. Enter your SAML Provider name. For more information on SAML naming see Choosing SAML
Identity Provider Names (p. 51).
8. Enter any optional SAML Identifiers you want to use.
9. Select Enable IdP sign out flow if you want your user to be logged out from the SAML IdP when
logging out from Amazon Cognito.
Enabling this flow sends a signed logout request to the SAML IdP when the LOGOUT
Endpoint (p. 342) is called.
Configure this endpoint for consuming logout responses from your IdP. This endpoint uses post
binding.
https://<yourDomainPrefix>.auth.<region>.amazoncognito.com/saml2/logout
Note
If this option is selected and your SAML identity provider expects a signed logout request,
you will also need to 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.
10. Choose Create provider.
11. On the Attribute mapping tab, add mappings for at least the required attributes, typically email,
as follows:
a. Type the SAML attribute name as it appears in the SAML assertion from your identity provider.
If your identity provider offers sample SAML assertions, that might help you to find the name.
25
Amazon Cognito Developer Guide
Next Steps
Some identity providers use simple names, such as email, while others use names similar to
this:
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
b. Choose the destination user pool attribute from the drop-down list.
12. Choose Save changes.
13. Choose Go to summary.
For more information, see Adding SAML Identity Providers to a User Pool (p. 49).
Next Steps
Now that you've created a user pool, here are some places to go next.
For an overview of Amazon Cognito authentication and authorization cases, see Common Amazon
Cognito Scenarios (p. 6).
To access other AWS services after a successful user pool authentication, see Accessing AWS Services
Using an Identity Pool After Sign-in (p. 153).
In addition to the AWS Management Console and the user pool SDKs mentioned previously in this
section, you can also interact with your user pool profiles by using the AWS Command Line Interface.
Topics
• Setting Up the Hosted UI with AWS Amplify (p. 27)
• Setting Up the Hosted UI with the Amazon Cognito Console (p. 27)
• Configuring a User Pool App Client (p. 29)
• Configuring a User Pool Domain (p. 32)
• Customizing the Built-in Sign-in and Sign-up Webpages (p. 37)
26
Amazon Cognito Developer Guide
Setting Up the Hosted UI with AWS Amplify
You can display a pre-built hosted UI, or you can federate users through an OAuth 2.0 endpoint
that redirects to a social sign-in provider, such as Facebook, Google, Amazon, or Apple. After a user
successfully authenticates with the social provider, AWS Amplify creates a new user in your user pool if
needed, and it provides the user's OIDC token to you app.
For more information, see the AWS Amplify framework documentation for your app platform:
1. Choose App client settings from the navigation bar on the left-side of the console page.
2. Select Cognito User Pool as one of the Enabled Identity Providers.
Note
To sign in with external identity providers (IdPs), such as Facebook, Amazon, Google, or
Apple as well as through OpenID Connect (OIDC) or SAML IdPs, first configure them as
described next, and then return to the App client settings page to enable them.
27
Amazon Cognito Developer Guide
Setting Up the Hosted UI with
the Amazon Cognito Console
3. Enter Callback URL(s). A callback URL indicates where the user is to be redirected after a successful
sign-in.
4. Enter Sign out URL(s). A sign-out URL indicates where your user is to be redirected after signing out.
5. Select Authorization code grant to return an authorization code that is then exchanged for user
pool tokens. Because the tokens are never exposed directly to an end user, they are less likely to
become compromised. However, a custom application is required on the backend to exchange the
authorization code for user pool tokens. For security reasons, we recommend that you use the
authorization code grant flow, together with Proof Key for Code Exchange (PKCE), for mobile apps.
6. Select Implicit grant to have user pool JSON web tokens (JWT) returned to you from Amazon
Cognito. You can use this flow when there's no backend available to exchange an authorization code
for tokens. It's also helpful for debugging tokens.
7. You can enable both the Authorization code grant and the Implicit code grant, and then use each
grant as needed.
8. Unless you specifically want to exclude one, select the check boxes for all of the Allowed OAuth
scopes.
9. Select Client credentials only if your app needs to request access tokens on its own behalf, not on
behalf of a user.
10. Choose Save changes.
Configure a domain
You can view the hosted UI sign-in webpage with the following URL. Note the response_type. In this
case, response_type=code for the authorization code grant.
https://<your_domain>/login?
response_type=code&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>
You can view the hosted UI 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://<your_domain>/login?
response_type=token&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>
You can find the JSON web token (JWT) identity token after the #idtoken= parameter in the response.
Here's a sample response from an implicit grant request. Your identity token string will be much longer.
https://www.example.com/
#id_token=123456789tokens123456789&expires_in=3600&token_type=Bearer
You can decode and verify user pool tokens using AWS Lambda, see Decode and verify Amazon Cognito
JWT tokens on the AWS GitHub website.
28
Amazon Cognito Developer Guide
Configuring an App Client
Amazon Cognito user pools tokens are signed using an RS256 algorithm.
You might have to wait a minute to refresh your browser before changes you made in the console
appear.
Your domain is shown on the Domain name page. Your app client ID and callback URL are shown on the
App client settings page.
Note
The Amazon Cognito hosted sign-in web page does not support the custom authentication flow.
Replace "MyUserPoolID" and "MyAppClientID" with your user pool and app client ID values in these
examples. Likewise, your parameter values might be different than those used in these examples.
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"]"
Updating a User Pool App Client (AWS CLI and AWS API)
29
Amazon Cognito Developer Guide
Configuring an App Client
{
"UserPoolClient": {
"ClientId": "MyClientID",
"SupportedIdentityProviders": [
"LoginWithAmazon",
"MySAMLIdP"
],
"CallbackURLs": [
"https://example.com"
],
"AllowedOAuthScopes": [
"openid"
],
"ClientName": "Example",
"AllowedOAuthFlows": [
"implicit",
"code"
],
"RefreshTokenValidity": 30,
"CreationDate": 1524628110.29,
"AllowedOAuthFlowsUserPoolClient": true,
"UserPoolId": "MyUserPoolID",
"LastModifiedDate": 1530055177.553
}
}
See the AWS CLI command reference for more information: update-user-pool-client.
Creating a User Pool App Client (AWS CLI and AWS API)
See the AWS CLI command reference for more information: create-user-pool-client
Getting Information about a User Pool App Client (AWS CLI and AWS API)
See the AWS CLI command reference for more information: describe-user-pool-client.
Listing All App Client Information in a User Pool (AWS CLI and AWS API)
See the AWS CLI command reference for more information: list-user-pool-clients.
Deleting a User Pool App Client (AWS CLI and AWS API)
30
Amazon Cognito Developer Guide
Configuring an App Client
See the AWS CLI command reference for more information: delete-user-pool-client
You can choose your identity provider (IDP) to authenticate your users. This service can be
performed by your user pool, or by a third party such as Facebook. Before you can use an IdP,
you need to enable it. You can enable multiple IdPs, but you must enable at least one. For more
information on using external IdPs see Adding User Pool Sign-in Through a Third Party (p. 43).
Callback URL(s)
A callback URL indicates where the user is to be redirected after a successful sign-in. Choose at least
one callback URL, and it should:
• Be an absolute URI.
• Be pre-registered with a client.
• Not include a fragment component.
Amazon Cognito requires HTTPS over HTTP except for http://localhost for testing purposes
only.
A sign-out URL indicates where your user is to be redirected after signing out.
Allowed OAuth Flows
The Authorization code grant flow initiates a code grant flow, which provides an authorization code
as the response. This code can be exchanged for access tokens with the TOKEN Endpoint (p. 336).
Because the tokens are never exposed directly to an end user, they are less likely to become
compromised. However, a custom application is required on the backend to exchange the
authorization code for user pool tokens.
Note
For security reasons, we highly recommend that you use only the Authorization code grant
flow, together with PKCE, for mobile apps.
The Implicit grant flow allows the client to get the access token (and, optionally, ID token, based on
scopes) directly from the AUTHORIZATION Endpoint (p. 331). Choose this flow if your app cannot
initiate the Authorization code grant flow. For more information, see the OAuth 2.0 specification.
You can enable both the Authorization code grant and the Implicit code grant, and then use each
grant as needed.
The Client credentials flow is used in machine-to-machine communications. With it you can request
an access token to access your own resources. Use this flow when your app is requesting the token
on its own behalf, not on behalf of a user.
Note
Since the client credentials flow is not used on behalf of a user, only custom scopes can be
used with this flow. A custom scope is one that you define for your own resource server. See
Defining Resource Servers for Your User Pool (p. 41).
31
Amazon Cognito Developer Guide
Configuring a Domain
Choose one or more of the following OAuth scopes to specify the access privileges that can be
requested for access tokens.
• 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 openid scope returns all user attributes in the ID token that are readable by the client. The ID
token is not returned if the openid scope is not requested by the client.
• The aws.cognito.signin.user.admin scope grants access to Amazon Cognito User Pool API
operations that require access tokens, such as UpdateUserAttributes and VerifyUserAttribute.
• 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.
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 Defining Resource Servers for Your User
Pool (p. 41).
For more information about OAuth scopes, see the list of standard OIDC scopes.
To add an app client and an Amazon Cognito hosted domain with the AWS Management Console, see
Adding an App to Enable the Hosted Web UI.
Note
You can't use the text aws, amazon, or cognito, in the domain prefix.
Topics
• Using the Amazon Cognito Domain for the Hosted UI (p. 32)
• Using Your Own Domain for the Hosted UI (p. 34)
To add an app client and an Amazon Cognito hosted domain with the AWS Management Console, see
Adding an App to Enable the Hosted Web UI.
Topics
• Prerequisites (p. 33)
• Step 1: Configure a Hosted User Pool Domain (p. 33)
• Step 2: Verify Your Sign-in Page (p. 33)
32
Amazon Cognito Developer Guide
Configuring a Domain
Prerequisites
Before you begin, you need:
• A user pool with an app client. For more information, see Getting Started with User Pools (p. 17).
You can use the AWS Management Console to configure a user pool domain.
To configure a hosted user pool domain (AWS CLI and AWS API)
Use the following commands to create a domain prefix and assign it to your user pool.
To delete a domain
33
Amazon Cognito Developer Guide
Configuring a 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.
Topics
• Adding a Custom Domain to a User Pool (p. 34)
• Changing the SSL Certificate for Your Custom Domain (p. 36)
Prerequisites
Before you begin, you need:
• A user pool with an app client. For more information, see Getting Started with User Pools (p. 17).
• A web domain that you own. Its root must have a valid A record in DNS. For more information see
Domain Names.
• The ability to create a subdomain for your custom domain. We recommend using auth as the
subdomain. 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.
• A Secure Sockets Layer (SSL) certificate managed by ACM.
Note
You must change the AWS region to US East (N. Virginia) in the ACM console before you
request or import a certificate.
• To set up a custom domain name or to update its certificate, you must have permission to update
Amazon CloudFront distributions. You can do so by attaching the following IAM policy statement to an
IAM user, group, or role in your AWS account:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCloudFrontUpdateDistribution",
"Effect": "Allow",
"Action": [
"cloudfront:updateDistribution"
],
"Resource": [
"*"
]
}
34
Amazon Cognito Developer Guide
Configuring a Domain
]
}
You can add your domain to your user pool by using the Amazon Cognito console or API.
1. Sign in to the Amazon Cognito console. You might be prompted for your AWS credentials.
2. Sign in to the AWS Management Console and open the Amazon Cognito console at https://
console.aws.amazon.com/cognito/home.
3. Choose Manage User Pools.
4. On the Your User Pools page, choose the user pool that you want to add your domain to.
5. On the navigation menu on the left, choose Domain name.
6. Under Your own domain, choose Use your domain.
7. For Domain name, enter your custom domain name. 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.
8. For AWS managed certificate, choose the SSL certificate that you want to use for your domain. You
can choose one of the certificates that you manage with ACM.
If you don't have a certificate that is available to choose, you can use ACM to provision one. For more
information, see Getting Started in the AWS Certificate Manager User Guide.
9. Choose Save changes.
10. Note the Alias target. Instead of an IP address or a domain name, the Alias target is an alias
resource record set that points to an Amazon CloudFront distribution.
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.
• If you aren't using Route 53 for DNS address resolution, then you need to have your DNS service
provider add the alias target from the previous step as an alias for your user pool custom domain.
Your DNS provider will also need to set up the subdomain for your custom domain.
1. Sign in to the Route 53 console. You might be prompted for your AWS credentials.
2. If you don't have a hosted zone in Route 53, set one up. Otherwise, skip this step.
35
Amazon Cognito Developer Guide
Configuring a Domain
a. On the Hosted Zones page, choose the name of your hosted zone.
b. Choose Create Record Set and enter the following values:
i. For Name, type your preferred subdomain name. For example, if the subdomain you’re
attempting to create is auth.example.com, type auth.
ii. For Type, choose A - IPv4 address.
iii. Select Yes for the Alias option.
iv. Type the alias target name that you noted in a previous step in Alias Target.
c. Choose Create.
Note
Alternatively, you can create a new hosted zone to hold the records that are associated
with your subdomain. You can also createa delegation set in the parent hosted zone
that refers clients to the subdomain hosted zone. This method offers more flexibility
when you're managing the hosted zones (for example, restricting who can edit the
zones). You can only use this method for public hosted zones, because adding NS
records to private hosted zones isn't currently supported. For more information, see
Creating a subdomain for a domain hosted through Amazon Route 53.
• 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://auth.example.com/login?
response_type=code&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>
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.
36
Amazon Cognito Developer Guide
Customizing the Built-in Webpages
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 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.
1. Sign in to the AWS Management Console and open the Amazon Cognito console at https://
console.aws.amazon.com/cognito/home.
2. Choose Manage User Pools.
3. On the Your User Pools page, choose the user pool that you want to add your domain to.
4. On the navigation menu on the left, choose Domain name.
5. Under Your own domain, for AWS managed certificate, choose your new certificate.
6. Choose Save changes.
You can specify app UI customization settings for a single client (with a specific clientId) or for all
clients (by setting the clientId to ALL). If you specify ALL, the default configuration will be used for
every client that has no UI customization set previously. If you specify UI customization settings for a
particular client, it will no longer fall back to the ALL configuration.
Note
To use this feature, your user pool must have a domain associated with it.
• The CSS class names can only be from the following list:
• background-customizable
37
Amazon Cognito Developer Guide
Customizing the Built-in Webpages
• banner-customizable
• errorMessage-customizable
• idpButton-customizable
• idpButton-customizable:hover
• inputField-customizable
• inputField-customizable:focus
• label-customizable
• legalText-customizable
• logo-customizable
• submitButton-customizable
• submitButton-customizable:hover
• textDescription-customizable
• Property values cannot contain HTML, @import, @supports, @page, or @media statements or
Javascript.
Labels
• font-weight is a multiple of 100 from 100 to 900.
Input fields
• width is the width as a percentage of the containing block.
• 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 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.
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 4 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 4 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.
38
Amazon Cognito Developer Guide
Customizing the Built-in Webpages
39
Amazon Cognito Developer Guide
Customizing the Built-in Webpages
40
Amazon Cognito Developer Guide
Defining Resource Servers
A resource server is a server for access-protected resources. It handles authenticated requests from an
app that has an access token. Typically the resource server provides a CRUD API for making these access
requests. This API can be hosted in Amazon API Gateway or outside of AWS. The app passes the access
token in the API call to the resource server. The app should treat the access token as opaque when it
passes the token in the access request. The resource server inspects the access token to determine if
access should be granted.
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 and using user
pool tokens, see this blog post. Amazon API Gateway is a good option for inspecting access
tokens and protecting your resources. For more about API Gateway custom authorizers, see Use
API Gateway Custom Authorizers.
A scope is a level of access that an app can request to a resource. For example, if you have a resource
server for photos, it might define two scopes: one for read access to the photos and one for write/delete
access. When the app makes an API call to request access and passes an access token, the token will have
one or more scopes embedded in inside it.
Overview
Amazon Cognito allows app developers to create their own OAuth2.0 resource servers and define
custom scopes in them. Custom scopes can then be associated with a client, and the client can request
them in OAuth2.0 authorization code grant flow, implicit flow, and client credentials flow. Custom
scopes are added in the scope claim in the access token. A client can use the access token against its
resource server, which makes the authorization decision based on scopes present in the token. For more
information about access token scope, see Using Tokens with User Pools (p. 144).
Note
Your resource server must verify the access token signature and expiration date before
processing any claims inside the token.
Note
An app client can only use the client credentials flow if the app client has a client secret.
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.
Example:
• Name: a friendly name for the resource server, such as Weather API or Photo API.
41
Amazon Cognito Developer Guide
Defining Resource Servers
• Identifier: Unique identifier for the resource server. This could be an HTTPS endpoint where your
resource server is located. For example, https://my-weather-api.example.com
• Scope Name: The scope name. For example, weather.read
• Scope Description: A brief description the scope. For example, Retrieve weather
information.
When a client app requests a custom scope in any of the OAuth2.0 flows, it must request the full
identifier for the scope, which is resourceServerIdentifier/scopeName. For example, if
the resource server identifier is https://myphotosapi.example.com and the scope name is
photos.read, the client app must request https://myphotosapi.example.com/photos.read at
runtime.
Deleting a scope from a resource server does not delete its association with all clients; deleting the scope
makes it inactive. So if a client app requests the deleted scope at runtime, the scope is ignored and is not
included in the access token. If the scope is re-added later, then it is again included in the access token.
If a scope is removed from a client, the association between client and scope is deleted. If a client
requests a disallowed scope at runtime, this results in an error, and an access token is not issued.
You can use the AWS Management Console, API, and CLI to define resource servers and scopes for your
user pool.
Each of the custom scopes that you define appears on the App client settings tab, under OAuth2.0
Allowed Custom Scopes; for example com.example.photos/read.
Defining a Resource Server for Your User Pool (AWS CLI and
AWS API)
Use the following commands to specify resource server settings for your user pool.
42
Amazon Cognito Developer Guide
Adding Sign-in Through a Third Party
To list information about all resource servers for your user pool
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
• Adding Social Identity Providers to a User Pool (p. 43)
• Adding SAML Identity Providers to a User Pool (p. 49)
• Adding OIDC Identity Providers to a User Pool (p. 56)
• Specifying Identity Provider Attribute Mappings for Your User Pool (p. 61)
43
Amazon Cognito Developer Guide
Adding Social Identity Providers
You can add a social identity provider in the AWS Management Console, with the AWS CLI, or using
Amazon Cognito API calls.
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
• Prerequisites (p. 44)
• Step 1: Register with a Social IdP (p. 44)
• Step 2: Add a Social IdP to Your User Pool (p. 47)
• Step 3: Test Your Social IdP Configuration (p. 48)
Prerequisites
Before you begin, you need:
• A user pool with an application client and a user pool domain. For more information, see Create a user
pool.
• A social identity provider.
https://<your_user_pool_domain>/login?
response_type=code&client_id=<your_client_id>&redirect_uri=https://www.example.com
44
Amazon Cognito Developer Guide
Adding Social Identity Providers
https://<your-user-pool-domain>
Type your redirect URL into Valid OAuth Redirect URIs. It will consist of your user pool domain with
the /oauth2/idpresponse endpoint.
https://<your-user-pool-domain>/oauth2/idpresponse
Choose Apps and Services from navigation bar at the top of the page and then choose Login with
Amazon.
4. Choose Create a Security Profile.
5. Type in a Security Profile Name, a Security Profile Description, and a Consent Privacy Notice URL.
6. Choose Save.
7. Choose Client ID and Client Secret to show the client ID and secret. You will use them in the next
section.
8. Hover over the gear and choose Web Settings, and then choose Edit.
9. Type your user pool domain into Allowed Origins.
https://<your-user-pool-domain>
10. Type your user pool domain with the /oauth2/idpresponse endpoint into Allowed Return URLs.
https://<your-user-pool-domain>/oauth2/idpresponse
https://<your-user-pool-domain>
45
Amazon Cognito Developer Guide
Adding Social Identity Providers
8. Choose CREATE. You will not use the Client ID and Client Secret from this step.
9. Choose DONE.
10. Sign in to the Google Console.
11. On the left navigation bar, choose Credentials.
12. Create your OAuth 2.0 credentials by choosing OAuth client ID from the Create credentials drop-
down list.
13. Choose Web application.
14. Type your user pool domain into Authorized JavaScript origins.
https://<your-user-pool-domain>
15. Type your user pool domain with the /oauth2/idpresponse endpoint into Authorized Redirect
URIs.
https://<your-user-pool-domain>/oauth2/idpresponse
46
Amazon Cognito Developer Guide
Adding Social Identity Providers
https://<your-user-pool-domain>/oauth2/idpresponse
5. Choose Add, and then Save. You do not need to verify the domain.
6. Choose Continue, and then choose Register.
12. On the left navigation bar, choose Keys.
13. On the Keys page, choose the + icon.
14. On the Register a New Key page, do the following:
To configure a user pool social identity provider with the AWS Management Console
1. Go to the Amazon Cognito console. You might be prompted for your AWS credentials.
2. Choose Manage your User Pools.
3. Choose an existing user pool from the list, or create a user pool.
4. On the left navigation bar, choose Identity providers.
5. Choose a social identity provider: Facebook, Google, Login with Amazon, or Apple.
6. For Google and Login with Amazon, type the app client ID and app client secret that you received
from the social identity provider in the previous section. For Facebook, type the app client ID, app
client secret that you received from the social identity provider in the previous section, and choose
an API version. We recommend choosing the highest available possible version as each Facebook
API version has a lifecycle and a deprecation date for example, version 2.12. You can change the API
version post creation if you encounter any issues. The Facebook scopes and attributes may vary with
each API version, so we recommend testing your integration.” For Sign in with Apple, provide the
Services ID, Team ID, Key ID, and private key that you received in the previous section.
7. Type the names of the scopes that you want to authorize. 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.
47
Amazon Cognito Developer Guide
Adding Social Identity Providers
Your app user is asked to consent to providing these attributes to your app. For more information
about their scopes, see the documentation from Google, Facebook, Login with Amazon, or Sign in
with Apple.
In the case of 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 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
8. Choose Enable for the social identity provider that you are configuring.
9. Choose App client settings from the navigation bar.
10. Select your social identity provider as one of the Enabled Identity Providers for your user pool app.
11. Type your callback URL into Callback URL(s) for your user pool app. This is the URL of the page
where your user will be redirected after a successful authentication.
https://www.example.com
a. Select the check box to choose the Facebook, Google, or Amazon attribute name. You can also
type the names of additional attributes that are not listed in the Amazon Cognito console.
b. Choose the destination user pool attribute from the drop-down list.
c. Choose Save changes.
d. Choose Go to summary.
https://<your_user_pool_domain>/login?
response_type=code&client_id=<your_client_id>&redirect_uri=https://www.example.com
You can find your domain on the user pool Domain name console page. The client_id is on the App
client settings page. Use your callback URL for the redirect_uri parameter. This is the URL of the page
where your user will be redirected after a successful authentication.
48
Amazon Cognito Developer Guide
Adding SAML Providers
Note
Requests that are not completed within 5 minutes will be cancelled, redirected to the login
page, and then display a Something went wrong error message.
With the built-in hosted web UI, Amazon Cognito provides token handling and management for all
authenticated users, so your backend systems can standardize on one set of user pool tokens. You can
create and manage a SAML IdP in the AWS Management Console, with the AWS CLI, or using Amazon
Cognito API calls. To get started with the console see Adding sign-in through SAML-based identity
providers to a user pool with the AWS Management Console.
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).
You need to update your SAML identity provider and configure your user pool to support it. See the
documentation for your SAML identity provider for information about how to add your user pool as a
relying party or application for your SAML 2.0 identity provider.
Note
Cognito supports relayState values larger than 80 bytes. Whilst 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 more than 80 bytes
will break many standard SAML provider integrations.
You also need to provide an assertion consumer endpoint to your SAML identity provider. Configure this
endpoint for SAML 2.0 POST binding in your SAML identity provider:
https://<yourDomainPrefix>.auth.<region>.amazoncognito.com/saml2/idpresponse
You can find your domain prefix and the region value for your user pool on the Domain name tab of the
Amazon Cognito console.
For some SAML identity providers, you also need to provide the SP urn / Audience URI / SP Entity ID, in
the form:
urn:amazon:cognito:sp:<yourUserPoolID>
You can find your user pool ID on the General settings tab in the Amazon Cognito console.
You should also configure your SAML identity provider to provide attribute values for any attributes that
are required in your user pool. Typically, email is a required attribute for user pools. In that case, the
SAML identity provider should provide an email value (claim) in the SAML assertion.
49
Amazon Cognito Developer Guide
Adding SAML Providers
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 identity provider via a user agent. Your user pool acts as a service
provider (SP) on behalf of your application. Amazon Cognito supports SP-initiated single sign-on (SSO)
as described in section 5.1.2 of the SAML V2.0 Technical Overview.
Topics
• SAML User Pool IdP Authentication Flow (p. 50)
• Choosing SAML Identity Provider Names (p. 51)
• Creating and Managing a SAML Identity Provider for a User Pool (AWS Management
Console) (p. 51)
• Creating and Managing a SAML Identity Provider for a User Pool (AWS CLI and AWS API) (p. 53)
• Integrating Third-Party SAML Identity Providers with Amazon Cognito User Pools (p. 55)
1. The app starts the sign-up and sign-in process by directing your user to the UI hosted by AWS. A
mobile app can use web view to show the pages hosted by AWS.
2. Typically your user pool determines the identity provider for your user from that user's email
address.
Alternatively, if your app gathered information before directing the user to your user pool, it can
provide that information to Amazon Cognito through a query parameter.
3. Your user is redirected to the identity provider.
4. The IdP authenticates the user if necessary. If the IdP recognizes that the user has an active session,
the IdP skips the authentication to provide a single sign-in (SSO) experience.
5. The IdP POSTs the SAML assertion to the Amazon Cognito service.
6. After verifying the SAML assertion and collecting the user attributes (claims) from the assertion,
Amazon Cognito internally creates or updates the user's profile in the userpool. Amazon Cognito
returns OIDC tokens to the app for the now signed-in user.
The following diagram shows the authentication flow for this process:
Note
Requests that are not completed within 5 minutes will be cancelled, redirected to the login
page, and then display a Something went wrong error message.
50
Amazon Cognito Developer Guide
Adding SAML Providers
When a user authenticates, the user pool returns ID, access, and refresh tokens. The ID token is a
standard OIDC token for identity management, and the access token is a standard OAuth 2.0 token. The
ID and access tokens expire after one hour, but your app can use the refresh token to get new tokens
without having the user re-authenticate. As a developer, you can choose the expiration time of refresh
tokens, and therefore how frequently users need to reauthenticate. If the user has authenticated through
an external IdP (i.e., they are a federated user), your app still uses the Amazon Cognito tokens with the
refresh token to determine how long until the user reauthenticates, regardless of when the external
IdP's token expires. The user pool automatically uses the refresh token to get new ID and access tokens
when they expire. If the refresh token has also expired, the server automatically initiates authentication
through the pages in your app that are hosted by AWS.
You can also optionally choose identifiers for your SAML providers. An identifier uniquely resolves to
an identity provider associated with your user pool. Typically each identifier corresponds to a domain
that belongs to the company that the SAML IdP represents. For a multitenant app that can be used
by different companies, identifiers can be used to redirect users to the correct IdP. Since there can be
multiple domains owned by the same company, you can provide multiple identifiers.
You can associate up to 50 identifiers with each SAML provider. Identifiers must be unique across the
identity provider.
For example, suppose that you built an app that can be used by employees of two different companies, A
and B. Company A owns domainA.com and domainA.co.uk; Company B owns domainB.com. Suppose
further that you set up two IdPs, one for each company:
In your application, you can prompt users to enter their email addresses. By deriving the domain
from the email address, you can redirect the user to the correct IdP by providing the domain
in the IdPIdentifier in the call to the /authorize endpoint. For example, if a user enters
[email protected], the user is redirected to IdP A.
The sign-in page hosted by Amazon Cognito parses the email address automatically to derive the
information. It parses the email domain from email and uses it as IdPIdentifier when calls the /
authorize endpoint.
• If you have multiple SAML IdPs and you specify an IdPIdentifier value for all of them, you will see
a box to enter an email address on the hosted page.
• If you have multiple IdPs, and you do not specify an IdPIdentifier value for any of them, the
hosted page will show a list of IdPs.
If you're building your own UI, you should parse the domain name so that it matches the
IdPIdentifiers that are provided during the IdP setup. For more information about IdP setup, see
Configuring Identity Providers for Your User Pool (p. 174).
51
Amazon Cognito Developer Guide
Adding SAML Providers
Before you create a SAML identity provider, you need the SAML metadata document that you get from
the third-party identity provider (IdP). For instructions on how to get or generate the required SAML
metadata document, see Integrating Third-Party SAML Identity Providers with Amazon Cognito User
Pools (p. 55).
1. Go to the Amazon Cognito console. You might be prompted for your AWS credentials.
2. Manage User Pools.
3. Choose an existing user pool from the list, or create a user pool.
4. On the left navigation bar, choose Identity providers.
5. Choose SAML to open the SAML dialog.
6. Under Metadata document upload a metadata document from your SAML IdP. You can also enter a
URL that points to the metadata document. For more information, see Integrating Third-Party SAML
Identity Providers with Amazon Cognito User Pools (p. 55).
Note
We recommend that you provide the endpoint URL if it is a public endpoint, rather
than uploading a file, because this allows Amazon Cognito to refresh the metadata
automatically. Typically metadata refresh happens every 6 hours or before the metadata
expires, whichever is earlier.
7. Enter your SAML Provider name. For more information on SAML naming see Choosing SAML
Identity Provider Names (p. 51).
8. Enter any optional SAML Identifiers you want to use.
9. Select Enable IdP sign out flow if you want your user to be logged out from the SAML IdP when
logging out from Amazon Cognito.
Enabling this flow sends a signed logout request to the SAML IdP when the LOGOUT
Endpoint (p. 342) is called.
Configure this endpoint for consuming logout responses from your IdP. This endpoint uses post
binding.
https://<yourDomainPrefix>.auth.<region>.amazoncognito.com/saml2/logout
Note
If this option is selected and your SAML identity provider expects a signed logout request,
you will also need to 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.
10. Choose Create provider.
11. On the Attribute mapping tab, add mappings for at least the required attributes, typically email,
as follows:
a. Type the SAML attribute name as it appears in the SAML assertion from your identity provider.
If your identity provider offers sample SAML assertions, that might help you to find the name.
Some identity providers use simple names, such as email, while others use names similar to
this:
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
b. Choose the destination user pool attribute from the drop-down list.
52
Amazon Cognito Developer Guide
Adding SAML Providers
Note
If you see InvalidParameterException while creating a SAML identity provider 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.
• To get the certificate containing the public key which will be used by the identity provider to verify the
signed logout request, choose Show signing certificate under Active SAML Providers on the SAML
dialog under Identity providers on the Federation console page.
{
"MetadataFile": "<SAML metadata XML>"
53
Amazon Cognito Developer Guide
Adding SAML Providers
Note
If the <SAML metadata XML> contains any quotations ("), they must be escaped (\").
{
"MetadataFile": "<SAML metadata XML>"
}
Note
If the <SAML metadata XML> contains any quotations ("), they must be escaped (\").
To delete an IdP
54
Amazon Cognito Developer Guide
Adding SAML Providers
• Replace it with a new one that uses the new redirect URL.
• Update the configuration in your SAML identity provider to accept both the old and new
redirect URLs.
All SAML identity providers in Amazon Cognito will switch to the new URLs, and the old ones
will stop working on October 31, 2017.
For some SAML Identity providers you must provide the urn / Audience URI / SP Entity ID, in the form
urn:amazon:cognito:sp:<yourUserPoolID>. You can find your user pool ID on the General
settings tab in the Amazon Cognito console.
You must also configure your SAML identity provider to provide attributes values for any attributes
required in your user pool. Typically, email is a required attribute for user pools, and in that case the
SAML identity provider will need to provide an email value (claim) in the SAML assertion.
The following links help you configure third-party SAML 2.0 identity provider solutions to work with
federation for Amazon Cognito User Pools.
Note
Identity provider support is built in to Amazon Cognito, so you only need to go to the following
provider sites to get the SAML metadata document. You may see further instructions on the
provider website about integrating with AWS, but you won't need those.
Microsoft Active Directory Federation Services (AD You can download the SAML metadata
FS) document for your ADFS federation
server from the following address:
https://<yourservername>/
FederationMetadata/2007-06/
FederationMetadata.xml.
55
Amazon Cognito Developer Guide
Adding OIDC Providers
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).
You can add an OIDC IdP to your user pool in the AWS Management Console, with the AWS CLI, or by
using the user pool API method CreateIdentityProvider.
Topics
• Prerequisites (p. 56)
• Step 1: Register with an OIDC IdP (p. 57)
• Step 2: Add an OIDC IdP to Your User Pool (p. 58)
• Step 3: Test Your OIDC IdP Configuration (p. 60)
• OIDC User Pool IdP Authentication Flow (p. 61)
Prerequisites
Before you begin, you need:
56
Amazon Cognito Developer Guide
Adding OIDC Providers
• A user pool with an application client and a user pool domain. For more information, see Create a user
pool.
• An OIDC IdP.
or https://Your Okta
subdomain.okta.com
2. 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://<your-user-pool-domain>/oauth2/idpresponse
3. Register your callback URL with your Cognito User Pool. This is the URL of the page where your user
will be redirected after a successful authentication.
57
Amazon Cognito Developer Guide
Adding OIDC Providers
https://www.example.com
4. Select your scopes. The scope openid is required. The email scope is needed to grant access to the
email and email_verified claims.
5. The OIDC IdP provides you with a client ID and a client secret. You'll use them when you set up an
OIDC IdP in your user pool.
You use an OIDC identity provider when you want to establish trust between an OIDC-compatible IdP
such as Salesforce and your user pool.
• 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.
4. On the left navigation bar, choose Company Settings.
5. On the navigation bar, choose Domain, type a domain, and choose Create.
6. On the left navigation bar, go to Platform Tools and choose Apps.
7. Choose App Manager.
8. a. Choose new connected app.
b. Fill out the required fields.
Under Start URL, type your user pool domain URL with the /oauth2/idpresponse endpoint.
https://<your-user-pool-domain>/oauth2/idpresponse
c. Enable OAuth settings and, type your callback URL into Callback URL. This is the URL of the
page where your user will be redirected after a successful sign-in.
https://www.example.com
9. Select your scopes. The scope openid is required. The email scope is needed to grant access to the
email and email_verified claims.
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.
58
Amazon Cognito Developer Guide
Adding OIDC Providers
Your app user is asked to consent to providing these attributes to your application.
11. Type the URL of your IdP and choose Run discovery.
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 Run discovery isn't successful, then you need to provide the Authorization endpoint, Token
endpoint, Userinfo endpoint, and Jwks uri (the location of the JSON Web Key).
Note
If provider uses discovery for federated login, the discovery document must use HTTPS
for the following values: authorization_endpoint, token_endpoint, userinfo_endpoint, and
jwks_uri. Otherwise the login will fail.
12. Choose Create provider.
13. On the left navigation bar, choose App client settings.
14. Select the OIDC provider that you set up in the previous step as one of the Enabled Identity
Providers.
15. Type a callback URL for the Amazon Cognito authorization server to call after users are
authenticated. This is the URL of the page where your user will be redirected after a successful
authentication.
https://www.example.com
16. Under Allowed OAuth Flows, enable both the Authorization code grant and the Implicit code
grant.
Unless you specifically want to exclude one, select the check boxes for all of the Allowed OAuth
scopes.
17. Choose Save changes.
18. On the Attribute mapping tab on the left navigation bar, add mappings of OIDC claims to user pool
attributes.
a. As a default, the OIDC claim sub is mapped to the user pool attribute Username. You can map
other OIDC claims to user pool attributes. Type in the OIDC claim, and choose the corresponding
59
Amazon Cognito Developer Guide
Adding OIDC Providers
user pool attribute from the drop-down list. For example, the claim email is often mapped to
the user pool attribute Email.
b. In the drop-down list, choose the destination user pool attribute.
c. Choose Save changes.
d. Choose Go to summary.
--attribute-mapping string
--idp-identifiers (list)
--cli-input-json string
--generate-cli-skeleton string
{
"client_id": "string",
"client_secret": "string",
"authorize_scopes": "string",
"attributes_request_method": "string",
"oidc_issuer": "string",
"authorize_url": "string",
"token_url": "string",
"attributes_url": "string",
"jwks_uri": "string"
}
https://<your_user_pool_domain>/oauth2/authorize?
response_type=code&client_id=<your_client_id>&redirect_uri=https://www.example.com
You can find your domain on the user pool Domain name console page. The client_id is on the General
settings page. Use your callback URL for the redirect_uri parameter. This is the URL of the page where
your user will be redirected after a successful authentication.
60
Amazon Cognito Developer Guide
Specifying Attribute Mappings
1. Your user lands on the Amazon Cognito built-in sign-in page, and is offered the option to sign in
through an OIDC IdP such as Salesforce.
2. Your user is redirected to the OIDC IdP's authorization endpoint.
3. After your user is authenticated, the OIDC IdP redirects to Amazon Cognito with an authorization
code.
4. Amazon Cognito exchanges the authorization code with the OIDC IdP for an access token.
5. Amazon Cognito creates or updates the user account in your user pool.
6. Amazon Cognito issues your application bearer tokens, which might include identity, access, and
refresh tokens.
Note
Requests that are not completed within 5 minutes will be cancelled, redirected to the login
page, and then display 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, the user pool returns ID, access, and refresh tokens. The ID token is a
standard OIDC token for identity management, and the access token is a standard OAuth 2.0 token.
61
Amazon Cognito Developer Guide
Specifying Attribute Mappings
Requirements
Remember the following requirements when you map user pool attributes to identity provider
attributes:
• A mapping must be present for each user pool attribute that's required when a user signs in to your
application. For example, if your user pool requires an email attribute for sign-in, map this attribute to
its equivalent from the identity provider.
• For each mapped user pool attribute, the maximum value length (2048 characters) must be large
enough for the value that Amazon Cognito obtains from the identity provider. Otherwise, Amazon
Cognito throws an error when users sign in to your application. If you map a custom attribute to an
identity provider token, set the length to 2048 characters.
• The username user pools attribute must be mapped only to specific attributes for the following
identity providers:
Facebook id
Google sub
• 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 identity provider, Amazon Cognito updates the
mapped attributes with the latest information from the identity provider. Amazon Cognito updates
each mapped attribute, even if its current value already matches the latest information. If Amazon
Cognito can't update the attribute, it throws an error. To ensure that Amazon Cognito can update the
attributes, check the following requirements:
• The mapped user pool attributes must be mutable. Mutable attributes can be updated by app
clients that have write permissions for those attributes. You can set user pool attributes as mutable
when you define them in the Amazon Cognito console. Or, if you create your user pool by using the
CreateUserPool API operation, you can set the Mutable parameter for each of these attributes to
true.
• 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 CreateUserPoolClient API operation, you can add these
attributes to the WriteAttributes array.
62
Amazon Cognito Developer Guide
Specifying Attribute Mappings
i. In the Facebook attribute (or Google attribute or Amazon attribute or Apple attribute)
field, enter the name of the attribute to be mapped.
ii. In the User pool attribute field, choose the user pool attribute to map the social identity
provider attribute to from the drop-down list.
d. Choose Save changes.
63
Amazon Cognito Developer Guide
Using Lambda Triggers
{
"MetadataFile": "<SAML metadata XML>"
}
Note
If the <SAML metadata XML> contains any quotations ("), they must be escaped (\").
The following table summarizes some of the customizations that can be made:
Custom Authentication Flow Define Auth Challenge Determines the next challenge
in a custom auth flow
64
Amazon Cognito Developer Guide
Using Lambda Triggers
Email and SMS third-party the section called Use a third-party provider to
providers “Custom Sender Lambda send SMS and email messages
Triggers” (p. 105)
Topics
• Important Considerations (p. 66)
• Adding a User Pool Lambda Trigger (p. 66)
• User Pool Lambda Trigger Event (p. 66)
• User Pool Lambda Trigger Common Parameters (p. 67)
• User Pool Lambda Trigger Sources (p. 67)
• Pre Sign-up Lambda Trigger (p. 69)
• Post Confirmation Lambda Trigger (p. 75)
• Pre Authentication Lambda Trigger (p. 78)
• Post Authentication Lambda Trigger (p. 81)
• Custom Authentication Challenge Lambda Triggers (p. 84)
• Pre Token Generation Lambda Trigger (p. 93)
• Migrate User Lambda Trigger (p. 97)
• Custom Message Lambda Trigger (p. 100)
• Custom sender Lambda Triggers (p. 105)
65
Amazon Cognito Developer Guide
Important Considerations
Important Considerations
The following information is important to consider before you start working with Lambda functions:
• Except for Custom Sender Lambda triggers, Amazon Cognito invokes Lambda functions synchronously.
When called, your Lambda function must respond within 5 seconds. If it does not, Amazon Cognito
retries the call. After 3 unsuccessful attempts, the function times out. This 5-second timeout value
cannot be changed. For more information see the Lambda programming model.
• If you delete an AWS 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.
• Except for Custom Sender Lambda triggers, errors thrown by Lambda triggers will be visible directly to
your end users if they are using Amazon Cognito Hosted UI as query parameters in the Callback URL.
As a recommended best practice, end user facing errors should be thrown from the Lambda triggers
and any sensitive or debugging information should be logged in the Lambda trigger itself.
1. Create a Lambda function using the Lambda console. For more information on Lambda functions,
see the AWS Lambda Developer Guide.
2. Navigate to the Amazon Cognito console, choose Manage User Pools.
3. Choose an existing user pool from the list, or create a user pool.
4. In your user pool, choose the Triggers tab from the navigation bar.
5. Choose a Lambda trigger such as Pre sign-up or Pre authentication and choose your Lambda
function from the Lambda function drop-down list.
6. Choose Save changes.
7. You can log your Lambda function using CloudWatch in the Lambda console. For more information
see Accessing CloudWatch Logs for Lambda.
JSON
{
"version": "string",
"triggerSource": "string",
"region": AWSRegion,
"userPoolId": "string",
"userName": "string",
"callerContext":
{
"awsSdkVersion": "string",
"clientId": "string"
},
"request":
{
"userAttributes": {
66
Amazon Cognito Developer Guide
User Pool Lambda Trigger Common Parameters
"string": "string",
....
}
},
"response": {}
}
The name of the event that triggered the Lambda function. For a description of each triggerSource
see User Pool Lambda Trigger Sources (p. 67).
region
The request from the Amazon Cognito service. This request must include:
userAttributes
One or more pairs of user attribute names and values. Each pair is in the form "name": "value".
response
The response from your Lambda trigger. The return parameters in the response depend on the
triggering event.
67
Amazon Cognito Developer Guide
Lambda Trigger Sources
68
Amazon Cognito Developer Guide
Pre Sign-up Lambda Trigger
Topics
• Pre Sign-up Lambda Flows (p. 70)
• Pre Sign-up Lambda Trigger Parameters (p. 70)
• Sign-up Tutorials (p. 71)
• Pre Sign-up Example: Auto-Confirm Users from a Registered Domain (p. 72)
• Pre Sign-up Example: Auto-Confirm and Auto-Verify all Users (p. 73)
69
Amazon Cognito Developer Guide
Pre Sign-up Lambda Trigger
The request includes validation data from the client which comes from the ValidationData values
passed to the user pool SignUp and AdminCreateUser API methods.
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
},
"validationData": {
"string": "string",
. . .
},
"clientMetadata": {
"string": "string",
. . .
}
},
"response": {
"autoConfirmUser": "boolean",
"autoVerifyPhone": "boolean",
"autoVerifyEmail": "boolean"
}
}
70
Amazon Cognito Developer Guide
Pre Sign-up Lambda Trigger
One or more name-value pairs representing user attributes. The attribute names are the keys.
validationData
One or more name-value pairs containing the validation data in the request to register a user. The
validation data is set and then passed from the client in the request to register a user. You can pass
this data to your Lambda function by using the ClientMetadata parameter in the InitiateAuth and
AdminInitiateAuth API actions.
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,
AdminRespondToAuthChallenge, ForgotPassword, and SignUp.
autoConfirmUser
Set to true to set as verified the email 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 when
autoVerifyEmail is set. If an alias with that email already exists, the alias will be moved to the
new user and the previous user's email will be marked as unverified. For more information, see
Overview of Aliases (p. 159).
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 Overview of Aliases (p. 159).
Sign-up Tutorials
The pre sign-up Lambda function is triggered before user sign-up. See these Amazon Cognito sign-up
tutorials for JavaScript, Android, and iOS.
Platform Tutorial
71
Amazon Cognito Developer Guide
Pre Sign-up Lambda Trigger
Platform Tutorial
JavaScript
var dataEmailDomain = {
Name: "custom:domain",
Value: "example.com"
}
var attributeEmail =
new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
var attributePhoneNumber =
new AmazonCognitoIdentity.CognitoUserAttribute(dataPhoneNumber);
var attributeEmailDomain =
new AmazonCognitoIdentity.CognitoUserAttribute(dataEmailDomain);
attributeList.push(attributeEmail);
attributeList.push(attributePhoneNumber);
attributeList.push(attributeEmailDomain);
var cognitoUser;
userPool.signUp('username', 'password', attributeList, null, function(err, result){
if (err) {
alert(err);
return;
}
cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
});
This is a sample Lambda trigger called just before sign-up with the user pool pre sign-up Lambda trigger.
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.
72
Amazon Cognito Developer Guide
Pre Sign-up Lambda Trigger
Node.js
Python
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s relevant to your Lambda trigger. The following is a test event for this
code sample:
JSON
{
"request": {
"userAttributes": {
"email": "[email protected]",
"custom:domain": "example.com"
}
},
"response": {}
}
73
Amazon Cognito Developer Guide
Pre Sign-up Lambda Trigger
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 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
Python
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s relevant to your Lambda trigger. The following is a test event for this
code sample:
JSON
{
"request": {
"userAttributes": {
"email": "[email protected]",
"phone_number": "+12065550100"
}
},
"response": {}
74
Amazon Cognito Developer Guide
Post Confirmation Lambda Trigger
The request contains the current attributes for the confirmed user.
Topics
• Post Confirmation Lambda Flows (p. 75)
• Post Confirmation Lambda Trigger Parameters (p. 76)
• User Confirmation Tutorials (p. 76)
• Post Confirmation Example (p. 77)
75
Amazon Cognito Developer Guide
Post Confirmation Lambda Trigger
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
},
"clientMetadata": {
"string": "string",
. . .
}
},
"response": {}
}
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,
ConfirmForgotPassword, ConfirmSignUp, and SignUp.
76
Amazon Cognito Developer Guide
Post Confirmation Lambda Trigger
Platform Tutorial
Node.js
if (event.request.userAttributes.email) {
sendEmail(event.request.userAttributes.email, "Congratulations " +
event.userName + ", you have been confirmed: ", function(status) {
77
Amazon Cognito Developer Guide
Pre Authentication Lambda Trigger
completedCallback('Email sent');
});
console.log("EMAIL CODE END");
};
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s relevant to your Lambda trigger. The following is a test event for this
code sample:
JSON
{
"request": {
"userAttributes": {
"email": "[email protected]",
"email_verified": true
}
},
"response": {}
}
Topics
• Pre Authentication Lambda Flows (p. 78)
• Pre Authentication Lambda Trigger Parameters (p. 79)
• Authentication Tutorials (p. 80)
• Pre Authentication Example (p. 80)
78
Amazon Cognito Developer Guide
Pre Authentication Lambda Trigger
The request includes validation data from the client which comes from the ClientMetadata values
passed to the user pool InitiateAuth and AdminInitiateAuth API methods.
For more information, see User Pool Authentication Flow (p. 287).
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
},
"validationData": {
"string": "string",
. . .
},
"userNotFound": boolean
},
"response": {}
}
This boolean is populated when PreventUserExistenceErrors is set to ENABLED for your User
Pool client.
validationData
One or more key-value pairs containing the validation data in the user's sign-in request. You can pass
this data to your Lambda function by using the ClientMetadata parameter in the InitiateAuth and
AdminInitiateAuth API actions.
79
Amazon Cognito Developer Guide
Pre Authentication Lambda Trigger
Authentication Tutorials
The pre authentication Lambda function is triggered just before Amazon Cognito signs in a new user. See
these sign-in tutorials for JavaScript, Android, and iOS.
Platform Tutorial
Node.js
Python
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s 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": {}
}
80
Amazon Cognito Developer Guide
Post Authentication Lambda Trigger
Topics
• Post Authentication Lambda Flows (p. 81)
• Post Authentication Lambda Trigger Parameters (p. 81)
• Authentication Tutorials (p. 82)
• Post Authentication Example (p. 82)
For more information, see User Pool Authentication Flow (p. 287).
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
},
81
Amazon Cognito Developer Guide
Post Authentication Lambda Trigger
"newDeviceUsed": boolean,
"clientMetadata": {
"string": "string",
. . .
}
},
"response": {}
}
This flag indicates if the user has signed in on a new device. It is set only if the remembered devices
value of the user pool is set to Always or User Opt-In.
userAttributes
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. You can pass this data to your Lambda function by using
the ClientMetadata parameter in the AdminRespondToAuthChallenge and RespondToAuthChallenge
API actions.
Authentication Tutorials
The post authentication Lambda function is triggered just after Amazon Cognito signs in a new user. See
these sign-in tutorials for JavaScript, Android, and iOS.
Platform Tutorial
Node.js
82
Amazon Cognito Developer Guide
Post Authentication Lambda Trigger
Python
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s 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": {}
}
83
Amazon Cognito Developer Guide
Challenge Lambda Triggers
These Lambda triggers issue and verify their own challenges as part of a user pool custom authentication
flow.
Amazon Cognito invokes this trigger to initiate the custom authentication flow.
Create auth challenge
Amazon Cognito invokes this trigger after Define Auth Challenge to create a custom challenge.
Verify auth challenge response
Amazon Cognito invokes this trigger to verify if the response from the end user for a custom
challenge is valid or not.
You can incorporate new challenge types with these challenge Lambda triggers. For example, these
challenge types might include CAPTCHAs or dynamic challenge questions.
You can generalize authentication into two common steps with the user pool InitiateAuth and
RespondToAuthChallenge API methods.
In this flow, a user authenticates by answering successive challenges until authentication either fails or
the user is issued tokens. These two API calls can be repeated to include different challenges.
Note
The Amazon Cognito hosted sign-in web page does not support the custom authentication flow.
Topics
84
Amazon Cognito Developer Guide
Challenge Lambda Triggers
Amazon Cognito invokes this trigger to initiate the custom authentication flow.
The request for this Lambda trigger contains session, which 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 challenge details (ChallengeResult) are stored in chronological order in
the session array, with session[0] representing the first challenge that is presented to the user.
You can have Amazon Cognito verify user passwords before it issues your custom challenges. Here is an
overview of the process:
1. To start, have your app initiate sign-in by calling InitiateAuth or AdminInitiateAuth with the
AuthParameters map, including CHALLENGE_NAME: SRP_A, and values for SRP_A and USERNAME.
2. Your define auth challenge Lambda trigger is invoked with an initial session that contains
challengeName: SRP_A and challengeResult: true.
3. After receiving those inputs, your Lambda function responds with challengeName:
PASSWORD_VERIFIER, issueTokens: false, failAuthentication: false.
4. If the password verification succeeds, your Lambda function is invoked again with a new session
containing challengeName: PASSWORD_VERIFIER and challengeResult: true.
85
Amazon Cognito Developer Guide
Challenge Lambda Triggers
5. Your Lambda function initiates your custom challenges by responding 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.
6. The challenge loop repeats until all challenges are answered.
Topics
• Define Auth Challenge Lambda Trigger Parameters (p. 86)
• Define Auth Challenge Example (p. 87)
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
},
"session": [
ChallengeResult,
. . .
],
"clientMetadata": {
"string": "string",
. . .
},
"userNotFound": boolean
},
"response": {
"challengeName": "string",
"issueTokens": boolean,
"failAuthentication": boolean
}
These are the parameters provided to your Lambda function when it is invoked.
userAttributes
86
Amazon Cognito Developer Guide
Challenge Lambda Triggers
challengeName
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. You can pass this data to your Lambda
function by using the ClientMetadata parameter in the AdminRespondToAuthChallenge and
RespondToAuthChallenge API operations.
In the response, you can return the next stage of the authentication process.
challengeName
A string containing the name of the next challenge. If you want to present a new challenge to your
user, specify the challenge name here.
issueTokens
Set to true if you determine that the user has been sufficiently authenticated by completing the
challenges, or false otherwise.
failAuthentication
Set to true if you want to terminate the current authentication process, or false otherwise.
Node.js
87
Amazon Cognito Developer Guide
Challenge Lambda Triggers
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 = true;
event.response.failAuthentication = false;
} else {
event.response.issueTokens = false;
event.response.failAuthentication = true;
}
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.
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.
88
Amazon Cognito Developer Guide
Challenge Lambda Triggers
Topics
• Create Auth Challenge Lambda Trigger Parameters (p. 89)
• Create Auth Challenge Example (p. 90)
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
},
"challengeName": "string",
"session": [
ChallengeResult,
. . .
],
"clientMetadata": {
"string": "string",
. . .
},
"userNotFound": boolean
},
"response": {
"publicChallengeParameters": {
"string": "string",
. . .
},
"privateChallengeParameters": {
"string": "string",
. . .
},
"challengeMetadata": "string"
}
}
userAttributes
This boolean is populated when PreventUserExistenceErrors is set to ENABLED for your User
Pool client.
challengeName
The session element is an array of ChallengeResult elements, each of which contains the
following elements:
89
Amazon Cognito Developer Guide
Challenge Lambda Triggers
challengeName
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 pass this data to your Lambda
function by using the ClientMetadata parameter in the AdminRespondToAuthChallenge and
RespondToAuthChallenge API actions.
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 accurately present the challenge
to the user.
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
Node.js
90
Amazon Cognito Developer Guide
Challenge Lambda Triggers
Amazon Cognito invokes this trigger to verify if the response from the end user for a custom Auth
Challenge is valid or not. It is part of a user pool custom authentication flow.
The request for this trigger contains the privateChallengeParameters and challengeAnswer
parameters. The privateChallengeParameters values are returned by the Create Auth Challenge
Lambda trigger and will contain the expected response from the user. The challengeAnswer
parameter contains the user's response for the challenge.
The response contains the answerCorrect attribute, which is set to true if the user successfully
completed the challenge, or false otherwise.
The challenge loop will repeat until all challenges are answered.
Topics
• Verify Auth Challenge Lambda Trigger Parameters (p. 91)
• Verify Auth Challenge Response Example (p. 93)
91
Amazon Cognito Developer Guide
Challenge Lambda Triggers
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
},
"privateChallengeParameters": {
"string": "string",
. . .
},
"challengeAnswer": {
"string": "string",
. . .
},
"clientMetadata": {
"string": "string",
. . .
},
"userNotFound": boolean
},
"response": {
"answerCorrect": boolean
}
}
userAttributes
This boolean is populated when PreventUserExistenceErrors is set to ENABLED for your User
Pool client.
privateChallengeParameters
This parameter comes from the Create Auth Challenge trigger, and is compared against a user’s
challengeAnswer to determine whether the user passed the challenge.
This parameter is only used by the Verify Auth Challenge Response Lambda trigger. It should contain
all of the information that is required to validate the user's response to the challenge. That includes
the publicChallengeParameters parameter which contains the question that is presented to the
user, and privateChallengeParameters which contains the valid answers for the question.
challengeAnswer
One or more key-value pairs that you can provide as custom input to the Lambda function
that you specify for the verify auth challenge trigger. You can pass this data to your Lambda
function by using the ClientMetadata parameter in the AdminRespondToAuthChallenge and
RespondToAuthChallenge API actions.
92
Amazon Cognito Developer Guide
Pre Token Generation Lambda Trigger
answerCorrect
Set to true if the user has successfully completed the challenge, or false otherwise.
Node.js
This Lambda trigger allows you to customize an identity token before it is generated. You can use this
trigger to add new claims, update claims, or suppress claims in the identity token. To use this feature,
you can associate a Lambda function from the Amazon Cognito user pools console or by updating your
user pool through the AWS CLI.
There are some claims which cannot be modified. These include acr, amr, aud, auth_time, azp, exp,
iat, identities, iss, sub, token_use, nonce, at_hash, and cognito:username.
Topics
• Pre Token Generation Lambda Trigger Sources (p. 93)
• Pre Token Generation Lambda Trigger Parameters (p. 94)
• Pre Token Generation Example: Add a New Claim and Suppress an Existing Claim (p. 95)
• Pre Token Generation Example: Modify the User's Group Membership (p. 96)
93
Amazon Cognito Developer Guide
Pre Token Generation Lambda Trigger
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
},
"groupConfiguration": {
"groupsToOverride": ["string", . . .],
"iamRolesToOverride": ["string", . . .],
"preferredRole": "string",
"clientMetadata": {
"string": "string",
. . .
}
},
"response": {
"claimsOverrideDetails": {
"claimsToAddOrOverride": {
"string": "string",
. . .
},
"claimsToSuppress": ["string", . . .],
"groupOverrideDetails": {
"groupsToOverride": ["string", . . .],
"iamRolesToOverride": ["string", . . .],
"preferredRole": "string"
}
}
}
}
The input object containing the current group configuration. It includes groupsToOverride,
iamRolesToOverride, and preferredRole.
groupsToOverride
A list of the group names that are associated with the user that the identity token is issued for.
94
Amazon Cognito Developer Guide
Pre Token Generation Lambda Trigger
iamRolesToOverride
One or more key-value pairs that you can provide as custom input to the Lambda function that you
specify for the pre token generation trigger. You can pass this data to your Lambda function by using
the ClientMetadata parameter in the AdminRespondToAuthChallenge and RespondToAuthChallenge
API actions.
A map of one or more key-value pairs of claims to add or override. For group related claims, use
groupOverrideDetails instead.
claimsToSuppress
The output object containing the current group configuration. It includes groupsToOverride,
iamRolesToOverride, and preferredRole.
The groupOverrideDetails object is replaced with the one you provide. If you provide an
empty or null object in the response, then the groups are suppressed. To leave the existing
group configuration as is, copy the value of the request's groupConfiguration object to the
groupOverrideDetails object in the response, and pass it back to the service.
Node.js
95
Amazon Cognito Developer Guide
Pre Token Generation Lambda Trigger
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s relevant to your Lambda trigger. The following is a test event for this
code sample:
JSON
{
"request": {},
"response": {}
}
Node.js
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s relevant to your Lambda trigger. The following is a test event for this
code sample:
JSON
{
"request": {},
"response": {}
}
96
Amazon Cognito Developer Guide
Migrate User Lambda Trigger
You can migrate users from your existing user directory into Amazon Cognito user pools at the time of
sign-in, or during the forgot-password flow with this Lambda trigger.
Topics
• Migrate User Lambda Trigger Sources (p. 97)
• Migrate User Lambda Trigger Parameters (p. 97)
• Example: Migrate a User with an Existing Password (p. 99)
JSON
{
"userName": "string",
"request": {
"password": "string",
"validationData": {
"string": "string",
. . .
},
"clientMetadata": {
"string": "string",
. . .
}
},
"response": {
"userAttributes": {
"string": "string",
. . .
},
"finalUserStatus": "string",
"messageAction": "string",
"desiredDeliveryMediums": [ "string", . . .],
"forceAliasCreation": boolean
}
}
97
Amazon Cognito Developer Guide
Migrate User Lambda Trigger
The password entered by the user for sign-in. It is not set in the forgot-password flow.
validationData
One or more key-value pairs containing the validation data in the user's sign-in request. You can pass
this data to your Lambda function by using the ClientMetadata parameter in the InitiateAuth and
AdminInitiateAuth API actions.
clientMetadata
One or more key-value pairs that you can provide as custom input to the Lambda function that you
specify for the migrate user trigger. You can pass this data to your Lambda function by using the
ClientMetadata parameter in the AdminRespondToAuthChallenge and ForgotPassword API actions.
It must contain one or more name-value pairs representing user attributes to be stored in the
user profile in your user pool. 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.
Note
In order for users to reset their passwords in the forgot-password flow, they must have
either a verified email or a verified phone number. Amazon Cognito sends a message
containing a reset password code to the email or phone number in the user attributes.
Attributes Requirement
Any attributes marked If any required attributes are missing during the migration, default
as required when you values will be used.
created your user pool
username Required if you have configured your user pool with email and/or
preferred_username aliases in addition to username for sign-in, and
the user has entered an email or phone number to sign-in.
finalUserStatus
During sign-in, this attribute can be set to CONFIRMED, or not set, to auto-confirm your users and
allow them to sign-in with their previous passwords. This is the simplest experience for the user.
98
Amazon Cognito Developer Guide
Migrate User Lambda Trigger
If this attribute is set to RESET_REQUIRED, the user is required to change his or her password
immediately after migration at the time of sign-in, and your client app needs to handle the
PasswordResetRequiredException during the authentication flow.
Note
The password policy for the new user pool should not be stronger than the password policy
from your existing user directory.
messageAction
This attribute can be set to "SUPPRESS" to suppress the welcome message usually sent by Amazon
Cognito to new users. If this attribute is not returned, the welcome message will be sent.
desiredDeliveryMediums
This attribute can be set to "EMAIL" to send the welcome message by email, or "SMS" to send the
welcome message by SMS. If this attribute is not returned, the welcome message will be sent by
SMS.
forceAliasCreation
If this parameter is set to "true" and the phone number or email address specified in the
UserAttributes parameter already exists as an alias with a different user, the API call will migrate the
alias from the previous user to the newly created user. The previous user will no longer be able to
log in using that alias.
If this attribute is set to "false" and the alias exists, the user will not be migrated, and an error is
returned to the client app.
Node.js
var user;
if ( event.triggerSource == "UserMigration_Authentication" ) {
99
Amazon Cognito Developer Guide
Custom Message Lambda Trigger
The request includes codeParameter, which is a string that acts as a placeholder for the code that's
being delivered to the user. Insert the codeParameter string into the message body, at the position
where you want the verification code to be inserted. On receiving this response, the Amazon Cognito
service replaces the codeParameter string with the actual verification code.
Note
A custom message Lambda function with the CustomMessage_AdminCreateUser
trigger returns a user name and verification code and so the request must include both
request.usernameParameter and request.codeParameter.
Topics
• Custom Message Lambda Trigger Sources (p. 100)
• Custom Message Lambda Trigger Parameters (p. 101)
• Custom Message for Sign Up Example (p. 102)
• Custom Message for Admin Create User Example (p. 103)
100
Amazon Cognito Developer Guide
Custom Message Lambda Trigger
JSON
{
"request": {
"userAttributes": {
"string": "string",
. . .
}
"codeParameter": "####",
"usernameParameter": "string",
"clientMetadata": {
"string": "string",
. . .
}
},
"response": {
"smsMessage": "string",
"emailMessage": "string",
"emailSubject": "string"
}
}
A string for you to use as the placeholder for the verification code in the custom message.
usernameParameter
The username parameter. It is a required request parameter for the admin create user flow.
101
Amazon Cognito Developer Guide
Custom Message 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 custom message trigger. You can pass this data to your Lambda function by using the
ClientMetadata parameter in the following API actions:
• AdminResetUserPassword
• AdminRespondToAuthChallenge
• AdminUpdateUserAttributes
• ForgotPassword
• GetUserAttributeVerificationCode
• ResendConfirmationCode
• SignUp
• UpdateUserAttributes
smsMessage
The custom SMS message to be sent to your users. Must include the codeParameter value received
in the request.
emailMessage
The custom email message to be sent to your users. Must include the
codeParameter value received in the request. If EmailSendingAccount
is not DEVELOPER and EmailMessage is returned, 400 error code
com.amazonaws.cognito.identity.idp.model.InvalidLambdaResponseException will
be thrown. emailMessage is allowed only if UserPool's EmailSendingAccount is DEVELOPER.
emailSubject
A Lambda trigger can be invoked at multiple points: post-registration, resending a verification code,
forgotten password, or verifying a user attribute. The response includes messages for both SMS
and email. The message must include the code parameter, "####", which is the placeholder for the
verification code that is delivered to the user.
For email, the maximum length for the message is 20,000 UTF-8 characters, including the verification
code. HTML tags can be used in these emails.
For SMS, the maximum length is 140 UTF-8 characters, including the verification code.
Node.js
102
Amazon Cognito Developer Guide
Custom Message Lambda Trigger
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s relevant to your Lambda trigger. The following is a test event for this
code sample:
JSON
{
"version": 1,
"triggerSource": "CustomMessage_SignUp/CustomMessage_ResendCode/
CustomMessage_ForgotPassword/CustomMessage_VerifyUserAttribute",
"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": "####"
},
"response": {
"smsMessage": "<custom message to be sent in the message with code parameter>"
"emailMessage": "<custom message to be sent in the message with code parameter>"
"emailSubject": "<custom email subject>"
}
}
The code parameter value "####" is a placeholder for the temporary password and "username" is a
placeholder for the username delivered to your user.
103
Amazon Cognito Developer Guide
Custom Message Lambda Trigger
For email, the maximum length for the message is 20,000 UTF-8 characters, including the verification
code. HTML tags can be used in these emails. For SMS, the maximum length is 140 UTF-8 characters,
including the verification code.
Node.js
Amazon Cognito passes event information to your Lambda function. The function then returns the same
event object back to Amazon Cognito, with any changes in the response. In the Lambda console, you can
set up a test event with data that’s 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>"
104
Amazon Cognito Developer Guide
Custom Sender Lambda Triggers
Resources
The following resources can assist you with using the CustomEmailSender and CustomSMSSender
triggers.
AWS KMS
AWS KMS is a managed service that makes it easy for you to create and control customer master
keys (CMKs), which are the encryption keys that are used to encrypt your data. For more information
see, What is AWS Key Management Service?.
Customer master key
A customer master key (CMK) is a logical representation of a master key. The CMK includes
metadata, such as the key ID, creation date, description, and key state. The CMK also contains the
key material used to encrypt and decrypt data. For more information see, Customer master keys.
Symmetric customer master key
A symmetric customer master key represents a 256-bit encryption key that never leaves AWS
KMS unencrypted. To use a symmetric CMK, you must call AWS KMS. Symmetric keys are used
in symmetric encryption, where the same key is used for encryption and decryption. For more
information see, Symmetric customer master keys.
105
Amazon Cognito Developer Guide
Custom Sender Lambda Triggers
Note
The CustomEmailSender trigger isn't available in the Amazon Cognito console.
• Create a Lambda function for the CustomEmailSender. Amazon Cognito uses the AWS Encryption
SDK to encrypt the secrets (temporary passwords or authorization codes).
• Create an encryption key in AWS KMS. This key will be used to encrypt temporary passwords and
authorization codes that Amazon Cognito generates. You can then decrypt these secrets in the custom
sender Lambda function to send them to the end-user in plain-text.
• Grant Amazon Cognito service principal cognito-idp.amazonaws.com access to invoke the Lambda
function.
• Edit the code in your Lambda function to use customer senders or third-party providers.
• Update the existing user pool to add custom sender Lambda triggers.
Important
For additional security, you must configure a symmetric customer master key in AWS KMS (KMS),
when CustomEmailSender or CustomSMSSender is configured with your user pool. Amazon
Cognito uses your configured KMS key to encrypt codes or temporary passwords. Amazon
Cognito sends the base64 encoded ciphertext to your Lambda functions. For more information
see, Symmetric customer master keys
Create a Lambda function for the CustomEmailSender trigger. Amazon Cognito uses the AWS
Encryption SDK to encrypt the secrets (temporary passwords or authorization codes).
Create an encryption key in AWS KMS. This key will be used to encrypt temporary passwords and
authorization codes that Amazon Cognito generates. You can then decrypt these secrets in the custom
sender Lambda function to be able to send them to the end user in plaintext.
Step 3: Grant Amazon Cognito service principal cognito-idp.amazonaws.com access to invoke the
Lambda function
Amazon Cognito uses AWS Encryption SDK to encrypt secrets (temporary passwords and authorization
codes) before sending them to the custom sender Lambda function. You need to decrypt these secrets
before sending them to end users using the custom provider of your choice. To use the AWS Encryption
SDK with your Lambda function, you need to package the SDK with your function. For information,
see Installing the AWS Encryption SDK for JavaScript. You can also update the Lambda package by
completing the following steps.
106
Amazon Cognito Developer Guide
Custom Sender Lambda Triggers
3. Add the AWS Encryption SDK to the package. For example, if you are using Node.js, then add the
node_modules directory and include the libraries from @aws-crypto/client-node.
4. Recreate the package.
5. Update the Lambda function code from the modified directory.
#Send the parameter to update-user-pool along with any existing user pool
configurations.
The following Node.js example shows how to use the CustomEmailSender Lambda function.
#Configure the encryption SDK client with the KMS key from the environment
variables.
if(event.triggerSource == 'CustomEmailSender_SignUp'){
107
Amazon Cognito Developer Guide
Custom Sender Lambda Triggers
}else if(event.triggerSource ==
'CustomEmailSender_AccountTakeOverNotification'){
return;
};
Important
For additional security you must configure a symmetric customer master key in AWS KMS,
when CustomEmailSender or CustomSMSSender is configured with your user pool. Amazon
Cognito uses your configured KMS key to encrypt codes or temporary passwords. Amazon
108
Amazon Cognito Developer Guide
Custom Sender Lambda Triggers
Cognito sends the base64 encoded ciphertext to your Lambda functions. For more information
see, Symmetric customer master keys
Create a Lambda function for the CustomSMSSender trigger. Amazon Cognito uses the AWS Encryption
SDK to encrypt the secrets (temporary passwords or authorization codes).
Create an encryption key in AWS KMS. This key will be used to encrypt temporary passwords and
authorization codes that Amazon Cognito generates. You can then decrypt these secrets in the custom
sender Lambda function to be able to send them to the end user in plaintext.
Step 3: Grant Amazon Cognito service principal cognito-idp.amazonaws.com access to invoke the
Lambda function
Amazon Cognito uses AWS Encryption SDK to encrypt secrets (temporary passwords and authorization
codes) before sending them to the custom sender Lambda function. You need to decrypt these secrets
before sending them to end users using the custom provider of your choice. To use the AWS Encryption
SDK with your Lambda function, you need to package the SDK with your function. For information,
see Installing the AWS Encryption SDK for JavaScript. You can also update the Lambda package by
completing the following steps.
Code examples
#Send the parameter to update-user-pool along with any existing user pool
configurations.
109
Amazon Cognito Developer Guide
Custom Sender Lambda Triggers
The following Node.js example shows how to use the CustomSMSSender Lambda function.
#Configure the encryption SDK client with the KMS key from the environment
variables.
let plainTextCode;
if(event.request.code){
const { plaintext, messageHeader } = await decrypt(keyring,
b64.toByteArray(event.request.code));
plainTextCode = plaintext
}
if(event.triggerSource == 'CustomSMSSender_SignUp'){
return;
};
Topics
• Custom SMS sender Lambda trigger sources (p. 108)
110
Amazon Cognito Developer Guide
Using Amazon Pinpoint Analytics
You can also set up user attributes that are specific to your app using the AWS Mobile SDK for Android or
AWS Mobile SDK for iOS. 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 tab in the Amazon Cognito console, additional endpoints are created for user email addresses
and phone numbers.
Amazon Cognito regions that support Amazon Amazon Pinpoint project regions
Pinpoint
ap-northeast-1 us-east-1
ap-northeast-2 us-east-1
111
Amazon Cognito Developer Guide
Find Amazon Cognito and Amazon
Pinpoint Region mappings
Amazon Cognito regions that support Amazon Amazon Pinpoint project regions
Pinpoint
ap-south-1 us-east-1, ap-south-1
ap-southeast-1 us-east-1
ca-central-1 us-east-1
eu-west-2 us-east-1
us-east-1 us-east-1
us-east-2 us-east-1
• If you create a user pool in ap-northest-1, you have to create your Amazon Pinpoint project in us-
east-1.
• If you create a user pool in ap-south-1, you have to create your Amazon Pinpoint project in either us-
east-1 or ap-south-1.
Note
Amazon Pinpoint is available in several AWS Regions in North America, Europe, Asia, and
Oceania. Besides the exceptions in the table, Amazon Cognito will only support in-Region
Amazon Pinpoint integrations. If Amazon Pinpoint is available the same Region as Amazon
Cognito, then Amazon Cognito sends events to Amazon Pinpoint projects within the same
Region. If Amazon Pinpoint isn't available in the Region, then Amazon Cognito doesn't support
Amazon Pinpoint integrations in that Region until Amazon Pinpoint becomes available. For
Amazon Pinpoint detailed Region information, see Amazon Pinpoint endpoints and quotas.
112
Amazon Cognito Developer Guide
Managing Users
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.
7. Choose Share user attribute data with Amazon Pinpoint if you want Amazon Cognito to send email
addresses and phone numbers to Amazon Pinpoint in order to create additional endpoints for users.
After the account phone number and email address are verified, they are only shared 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 in the
Amazon Pinpoint Developer Guide.
8. Choose Save changes.
9. To specify additional app mappings, choose Add another app mapping.
10. Choose Save changes.
To specify the analytics settings for your user pool's existing client app at app creation time
To update the analytics settings for your user pool's existing client app
Note
Amazon Cognito supports in-Region integrations when you use ApplicationArn
You can import your users into a user pool with a user migration Lambda trigger. This approach enables
seamless migration of users from your existing user directory to user pools when they sign in to your
user pool for the first time.
Topics
• Signing Up and Confirming User Accounts (p. 114)
• Creating User Accounts as Administrator (p. 121)
113
Amazon Cognito Developer Guide
Signing Up and Confirming User Accounts
• The user signs up in your user pool's client app, which 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 (p. 131).
• 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 (p. 121).
Users who sign themselves up need to be confirmed before they can sign in. Imported and created users
are already confirmed, but they need to create their password the first time they sign in. The following
sections explain the confirmation process and email and phone verification.
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.
The user account is confirmed and the user can sign in. If the user confirmed the user account by
entering a confirmation code that was received via email or phone (SMS)—or, in the case of email, by
114
Amazon Cognito Developer Guide
Signing Up and Confirming User Accounts
clicking a confirmation link—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 his or her password before
he or she 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 his or her password to a new value before doing anything else.
User accounts that are created by an administrator or developer start in this state.
Disabled
• Send a temporary password when a user chooses to reset his or her 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:
By providing the verification code, a user proves that he or she has 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:
To view this information, you can use the Amazon Cognito console. Or, you can use the AdminGetUser
API action, 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.
115
Amazon Cognito Developer Guide
Signing Up and Confirming User Accounts
1. Sign in the AWS Management Console and open the Amazon Cognito console at https://
console.aws.amazon.com/cognito.
2. Choose Manage User Pools.
3. On the Your User Pools page, choose the user pool that you want to configure.
4. In the navigation menu on the left, choose MFA and verifications.
The options for email or phone verification are shown under Which attributes do you want to
verify?
If you choose this option, Amazon Cognito emails a verification code 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.
Phone number
If you choose this option, Amazon Cognito sends a verification code through SMS when the
user signs up. Choose this option if you typically communicate with your users through SMS.
For example, you will want to use verified phone numbers if you send delivery notifications,
appointment confirmations, or alerts.
Email or phone number
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 (p. 117).
None
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
116
Amazon Cognito Developer Guide
Signing Up and Confirming User Accounts
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 might be unable to use your app in
some cases. Remember that users require verified contact information to:
• Reset their passwords. When a user does an action 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 Overview of Aliases (p. 159).
6. Choose Save changes.
1. A user signs up in your app by entering a username, phone number and/or email address, and
possibly other attributes.
2. 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 (via SMS) or email. The code is valid for 24 hours
3. 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.
4. 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.
5. The user enters the confirmation code in the app.
6. The app calls ConfirmSignUp 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 or phone number) as verified. Unless the value of this attribute is changed,
the user will not have to verify it again.
7. 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
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. 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 his or her
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.
117
Amazon Cognito Developer Guide
Signing Up and Confirming User Accounts
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.
2. In the sign-up flow for your app, require users to provide both an email address and a phone
number. Call the SignUp 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.
3. In your app interface, present a confirmation page where the user enters the verification code.
Confirm the user by calling the ConfirmSignUp 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.
4. Present the sign-in page, and authenticate the user by calling the InitiateAuth API action. After
the user is authenticated, Amazon Cognito returns an access token to your app.
5. Call the GetUserAttributeVerificationCode 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.
• 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.
• ConfirmForgotPassword
• ConfirmSignUp
• ForgotPassword
118
Amazon Cognito Developer Guide
Signing Up and Confirming User Accounts
• ResendConfirmationCode
• SignUp
The SecretHash 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.
Alternatively, you can use the following code example in your server-side Java application code:
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
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.
119
Amazon Cognito Developer Guide
Signing Up and Confirming User Accounts
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.
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:
120
Amazon Cognito Developer Guide
Creating Users as Administrator
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, [email protected]. 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
[email protected] or [email protected]. 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.
• Create a new user profile by using the AWS Management Console or by calling the AdminCreateUser
API.
• Specify the temporary password or allow Amazon Cognito to automatically generate one.
• Specify whether provided email addresses and phone numbers are marked as verified for new users.
• Specify custom SMS and email invitation messages for new users via the AWS Management Console or
a Custom Message Lambda trigger. For more information, see Customizing User Pool Workflows with
Lambda Triggers (p. 64).
• 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.
Note
This action cannot currently be performed using the AWS Management Console.
• Suppress the sending of the invitation message when the user is created.
• Specify an expiration time limit for the user account (up to 90 days).
• Allow users to sign themselves up or require that new users only be added by the administrator.
121
Amazon Cognito Developer Guide
Creating Users as Administrator
1. The user starts to sign in for the first time by submitting the username and password provided to
him or her.
2. The SDK calls InitiateAuth(Username, USER_SRP_AUTH).
3. Amazon Cognito returns the PASSWORD_VERIFIER challenge with Salt & Secret block.
4. The SDK performs the SRP calculations and calls RespondToAuthChallenge(Username, <SRP
variables>, PASSWORD_VERIFIER).
5. Amazon Cognito returns the NEW_PASSWORD_REQUIRED challenge along with the current and
required attributes.
6. The user is prompted and enters a new password and any missing values for required attributes.
7. The SDK calls RespondToAuthChallenge(Username, <New password>, <User
attributes>).
8. If the user requires a second factor for MFA, Amazon Cognito returns the SMS_MFA challenge and
the code is submitted.
9. After the user has successfully changed his or her password and optionally provided attributed
values or completed MFA, the user is signed in and tokens are issued.
When the user has satisfied all challenges, the Amazon Cognito service marks the user as confirmed
and issues ID, access, and refresh tokens for the user. For more information, see Using Tokens with User
Pools (p. 144).
Policies Tab
The Policies tab has these related settings:
• Specify whether to allow users to sign themselves up. This option is set by default.
• Specify user account expiration time limit (in days) for new accounts. The default setting is 7 days,
measured from the time when the user account is created. The maximum setting is 90 days. After
the account expires, the user cannot log in to the account until the administrator updates the user's
profile.
122
Amazon Cognito Developer Guide
Creating Users as Administrator
Note
Once the user has logged in, the account never expires.
For email (verification messages or user invitation messages), the maximum length for the message is
2048 UTF-8 characters, including the verification code or temporary password. For SMS, the maximum
length is 140 UTF-8 characters, including the verification code or temporary password.
Users Tab
The Users tab in the Users and groups tab has a Create user button.
123
Amazon Cognito Developer Guide
Adding Groups to a User Pool
When you choose Create user, a Create user form appears, which you can use to enter information
about the new user. Only the Username field is required.
Note
For user accounts that you create by using the Create user form in the AWS Management
Console, only the attributes shown in the form can be set in the AWS Management Console.
Other attributes must be set by using the AWS Command Line Interface or the Amazon Cognito
API, even if you have marked them as required attributes.
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.
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 for more
information.
You can see this feature used in the SpaceFinder reference app.
When you create a group in Amazon Cognito, you specify an IAM role by providing the role’s ARN. 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.
124
Amazon Cognito Developer Guide
Adding Groups to a User Pool
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 CustomRoleARN
parameter. The specified IAM role must match a role that is available to the user.
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 can belong 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, it is the group with the lowest precedence value whose IAM role is 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.
Limitations on Groups
User groups are subject to the following limitations:
• The number of groups you can create is limited by the Amazon Cognito service limits (p. 321).
• Groups cannot be nested.
• You cannot search for users in a group.
• You cannot search for groups by name, but you can list groups.
• Only groups with no members can be deleted.
125
Amazon Cognito Developer Guide
Managing and Searching for Users
When you choose Create group, a Create group form appears. This form is where you enter information
about the new group. Only the Name field is required. 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. If you don't have roles already defined, choose Create new
role. If you have more than one group, and your users can be assigned to more than one group, you can
set a Precedence value for each group. The precedence value can be any non-negative integer. Zero is
the top precedence value.
• You can view the Pool details and edit user pool attributes, password policies, MFA settings, apps, and
triggers. For more information, see User Pools Reference (AWS Management Console) (p. 156).
• You can view the users in your user pool and drill down for more details.
• You can also view the details for an individual user in your user pool.
• You can also search for a user in your user pool.
1. From the Amazon Cognito home page in the AWS Management Console, choose Manage your user
identities.
2. Choose your user pool from the Your User Pools page.
3. Choose User and Groups to view user information.
4. Choose a user name to show more information about an individual user. From this screen, you can
perform any of the following actions:
126
Amazon Cognito Developer Guide
Managing and Searching for Users
The Reset user password action results in a confirmation code being sent to the user immediately
and disables the user’s current password by changing the user state to RESET_REQUIRED. The
Enable MFA action results in a confirmation code being sent to the user when the user tries to log in.
The Reset user password code is valid for 1 hour. The MFA code is valid for 3 minutes.
You can search for any of the following standard attributes. Custom attributes are not searchable.
• username (case-sensitive)
• email
• phone_number
• name
• given_name
• family_name
• preferred_username
• cognito:user_status (called Status in the Console) (case-insensitive)
• status (called Enabled in the Console) (case-sensitive)
• sub
AWS Management Console searches are always prefix ("starts with") searches.
For example, if you want to list all users, leave the search box empty.
If you want to search for all confirmed users, choose Status from the drop-down menu. In the search
box, type the first letter of the word "confirmed."
127
Amazon Cognito Developer Guide
Managing and Searching for Users
Note that some attribute values are case-sensitive, such as User name.
• 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. If the array is empty, all attributes are returned.
• 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.
• 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.
{
"AttributesToGet": [],
128
Amazon Cognito Developer Guide
Recovering User Accounts
"Filter": "",
"Limit": 10,
"UserPoolId": "us-east-1_samplepool"
}
The following example returns all users whose phone numbers start with "+1312" and includes all
attributes.
{
"AttributesToGet": [],
"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"
}
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. Cognito sends a verification to only one of the specified methods.
For example, admin_only is a value used when the administrator does not want the user to recover
their account themselves, and would instead require them to contact the administrator to reset their
account. You cannot use admin_only with any other account recovery mechanism.
129
Amazon Cognito Developer Guide
Importing Users into a User Pool
If you do not specify AccountRecoverySetting, Amazon Cognito uses the legacy mechanism to
determine the password recovery method. In this case, Cognito uses a verified phone first. If the verified
phone is not found for the user, Cognito falls back and will use verified email next.
Topics
• Importing Users into User Pools With a User Migration Lambda Trigger (p. 130)
• Importing Users into User Pools From a CSV File (p. 131)
Before starting the user migration process, create a user migration Lambda function in your AWS
account, and configure your user pool to use this Lambda function ARN for the user migration trigger.
Add an authorization policy to your Lambda function to enable only the Amazon Cognito service account
principal ("cognito-idp.amazonaws.com") and your user pool's SourceARN to invoke it, to prevent any
other AWS customer's user pool from invoking your Lambda function. For more information, see Using
Resource-Based Policies for AWS Lambda (Lambda Function Policies).
1. The user opens your app and signs-in with the native sign-in UI screens from your app using the
Cognito Identity Provider APIs from an AWS Mobile SDK, or using the hosted sign-in UI provided by
Amazon Cognito that you leverage with the Amazon Cognito Auth SDK.
2. Your app sends the username and password to Amazon Cognito. If your app has a native sign-in
UI and uses the Cognito Identity Provider SDK, your app must use the USER_PASSWORD_AUTH
flow, in which the SDK sends the password to the server (your app must not use the
default USER_SRP_AUTH flow since the SDK does not send the password to the server
in the SRP authentication flow). The USER_PASSWORD_AUTH flow is enabled by setting
AuthenticationDetails.authenticationType to "USER_PASSWORD".
3. Amazon Cognito checks if the username exists in the user pool, including as an alias for the user's
email, phone number, or preferred_username. If the user does not exist, Amazon Cognito calls your
130
Amazon Cognito Developer Guide
Importing Users into a User Pool
user migration Lambda function with parameters including the username and password, as detailed
in Migrate User Lambda Trigger Parameters (p. 97).
4. Your user migration Lambda function should authenticate the user with your existing user directory
or user database, by calling your existing sign-in service, and it should return user attributes to be
stored in the user's profile in the user pool. If you would like users to continue to use their existing
passwords, set the attribute finalUserStatus = "CONFIRMED" in the Lambda response. For the
required attributes for the response see Migrate User Lambda Trigger Parameters (p. 97).
Important
Do not log the entire request event object in your user migration Lambda code (since that
would include the password in the log record sent to the CloudWatch logs), and ensure you
sanitize the logs so that passwords are not logged.
5. Amazon Cognito creates the user profile in your user pool, and returns tokens to your app client.
6. Your app client can now proceed with its normal functionality after sign-in.
After the user is migrated, we recommend that your native mobile apps use the USER_SRP_AUTH flow
for sign-in. It authenticates the user using the Secure Remote Password (SRP) protocol without sending
the password across the network, and provides security benefits over the USER_PASSWORD_AUTH flow
used during migration.
In case of errors during migration, including client device or network issues, your app will get error
responses from the Amazon Cognito user pools API, and the user account might or might not have been
created in your user pool. The user should then attempt sign-in again, and if that fails repeatedly, then
attempt to reset his or her password using the forgot-password flow in your app.
The forgot-password flow works in a similar way, except that no password is provided to your user
migration Lambda function, and your function only looks up the user in your existing user directory, and
returns attributes to be stored in your user pool. Then Amazon Cognito sends the user a reset password
code by email or SMS, and the user can then set a new password in your app. If your app has a native UI,
it needs to provide screens for the forgot-password flow. If your app uses the Amazon Cognito hosted UI,
then we provide the UI screens.
1. Create an Amazon CloudWatch Logs role in the AWS Identity and Access Management (IAM) console.
2. Create the user import .csv file.
3. Create and run the user import job.
4. Upload the user import .csv file.
5. Start and run the user import job.
6. Use CloudWatch to check the event log.
7. Require the imported users to reset their passwords.
131
Amazon Cognito Developer Guide
Importing Users into a User Pool
Topics
• Creating the CloudWatch Logs IAM Role (AWS CLI, API) (p. 132)
• Creating the User Import .csv File (p. 133)
• Creating and Running the Amazon Cognito User Pool Import Job (p. 135)
• Viewing the User Pool Import Results in the CloudWatch Console (p. 139)
• Requiring Imported Users to Reset Their Passwords (p. 140)
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/.
2. In the navigation pane of the IAM console, choose Roles.
3. For a new role, choose Create role.
4. For Select type of trusted entity, choose AWS service.
5. In Common use cases, choose EC2.
6. Choose Next: Permissions.
7. In Attach permissions policy, choose Create policy to open a new browser tab and create a new
policy from scratch.
8. On the Create policy page, choose the JSON tab.
9. In the JSON tab, copy and paste the following text as your role access policy, replacing any existing
text:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:DescribeLogStreams",
"logs:PutLogEvents"
],
"Resource": [
"arn:aws:logs:REGION:ACCOUNT:log-group:/aws/cognito/*"
]
}
]
}
10. Choose Review policy. Add a name and optional description and choose Create policy.
After you create the policy, close that browser tab and return to your original tab.
11. In Attach Policy, choose Next: Tags.
12. (Optional) In Tags, add metadata to the role by entering tags as key–value pairs.
132
Amazon Cognito Developer Guide
Importing Users into a User Pool
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "cognito-idp.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
22. Choose Update Trust Policy. You are now finished creating the role.
23. Note the role ARN. You need this later when you're creating an import job.
1. Navigate to the Amazon Cognito console, choose Manage User Pools, and then choose the user pool
that you are importing the users into.
2. Choose the Users tab.
3. Choose Import users.
4. Choose Download CSV header to get a .csv file containing the header row that you must include in
your .csv file.
Sample response:
133
Amazon Cognito Developer Guide
Importing Users into a User Pool
"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"
}
The downloaded user import .csv header file looks like this:
cognito:username,name,given_name,family_name,middle_name,nickname,preferred_username,profile,picture,we
You'll need to 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
Configuring User Pool Attributes (p. 157).
• The first line in the file is the downloaded header row that contains the user attribute names.
• The order of columns in the .csv file doesn't matter.
• Each line after the first line 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
• cognito:mfa_enabled
• email_verified or phone_number_verified
• email (if email_verified is true)
• phone_number (if phone_number_verified is true)
• Any attributes that you marked as required when you created the user pool
• The user pool must have at least one auto-verified attribute, either email_verified or
phone_number_verified. At least one of the auto-verified attributes must be true for each user. 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_number as an auto-verified attribute, the phone_number_verified value must be true
for each user.
134
Amazon Cognito Developer Guide
Importing Users into a User Pool
Note
In order 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 via
SMS.
• Attribute values that are strings should not be in quotation marks.
• If an attribute value contains a comma, you must put a backslash (\) 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_enabled field is required. If you've set multi-factor authentication (MFA) to be
required in your user pool, this field must be true for all users. If you've set MFA to be off, this field
must be false for all users. If you've set MFA to be optional, this field can be either true or false,
but it cannot be empty.
• The maximum line length is 16,000 characters.
• The maximum .csv file size is 100 MB.
• The maximum number of lines (users) in the file is 500,000, not including the header.
• The updated_at 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.
cognito:username,name,given_name,family_name,middle_name,nickname,preferred_username,profile,picture,we
John,,John,Doe,,,,,,,[email protected],TRUE,,02/01/1985,,,+12345550100,TRUE,123 Any
Street,,FALSE
Jane,,Jane,Roe,,,,,,,[email protected],TRUE,,01/01/1985,,,+12345550199,TRUE,100 Main
Street,,FALSE
Creating and Running the Amazon Cognito User Pool Import Job
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.
Topics
• Importing Users from a .csv File (Console) (p. 135)
• Importing Users (AWS CLI) (p. 136)
The following procedure describes how to import the users from the .csv file.
135
Amazon Cognito Developer Guide
Importing Users into a User Pool
4. Choose Upload CSV and select the .csv file to import users from.
5. Choose Create job.
6. To start the job, choose Start.
• 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:
The PRE_SIGNED_URL 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.
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
}
}
136
Amazon Cognito Developer Guide
Importing Users into a User Pool
• "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 cannot be started.
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.
To get a description of your user import job, use the following command, where USER_POOL_ID is your
user pool ID, and JOB_ID is the job ID that was returned when you created the user import job.
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_SIGNED_URL is the URL that you uploaded the .csv file to. The
ROLE_ARN is the CloudWatch Logs role ARN that you received when you created the role.
Sample response:
{
"UserImportJobs": [
137
Amazon Cognito Developer Guide
Importing Users into a User Pool
{
"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_TOKEN
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:
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
138
Amazon Cognito Developer Guide
Importing Users into a User Pool
}
}
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
}
}
Topics
• Viewing the Results (p. 139)
• Interpreting the Results (p. 140)
1. Sign in to the AWS Management Console and open the CloudWatch console at https://
console.aws.amazon.com/cloudwatch/.
2. Choose Logs.
3. 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.
4. Choose the log for the user import job you just ran. The log name is in the form JOB_ID/JOB_NAME.
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:
139
Amazon Cognito Developer Guide
Email Settings
In the following cases, the user will not be imported, but the import job will continue:
• 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.
1. The user attempts to sign in, providing user name and password (via InitiateAuth).
2. Amazon Cognito returns NotAuthorizedException when PreventUserExistenceErrors is
enabled. Otherwise, it returns PasswordResetRequiredException.
3. The app should direct the user into the ForgotPassword flow as outlined in the following
procedure:
To handle email delivery, you can use either of the following options:
140
Amazon Cognito Developer Guide
Default Email Functionality
• The default email functionality (p. 141) that is built into the Amazon Cognito service.
• Your Amazon SES configuration (p. 141).
These settings are reversible. When needed, you can update your user pool to switch between them.
With the default option, you can use either of the following email addresses as the FROM address:
Before you can use your Amazon SES configuration, you must verify one or more email addresses with
Amazon SES. You use a verified email addresses as the FROM email address that you assign to your user
pool. Then, when Amazon Cognito sends an email, it uses your email address by calling Amazon SES on
your behalf.
When you use your Amazon SES configuration, 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.
Note
Available regions for Amazon Cognito are us-east-1, us-east-2, us-west-2, eu-west-1, eu-west-2,
eu-central-1, ap-northeast-1, ap-northeast-2, ap-south-1, ap-southeast-1, ap-southeast-2, and
ca-central-1. Available Amazon SES regions are: us-east-1, us-west-2, eu-west-1.
141
Amazon Cognito Developer Guide
Configuring the Email Account
By verifying your email address, you confirm that you own it, which helps prevent unauthorized use.
For the steps to this procedure, see Verifying an Email Address in the Amazon Simple Email Service
Developer Guide.
You can skip this step if you are using the default Amazon Cognito email functionality.
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, do not use your Amazon SES configuration for applications that are in production. In this
situation, Amazon Cognito would be unable to send messages to your users' email addresses.
For the steps to move out of the sandbox, see Moving Out of the Amazon SES Sandbox in the Amazon
Simple Email Service Developer Guide.
If you configure your user pool to use the default email functionality, you use either of the following
addresses as the FROM address from which Amazon Cognito emails your users:
If you are using the default email address, Amazon Cognito does not need additional permissions, and
you can skip this step.
If you are using a custom address, Amazon Cognito needs additional permissions so that it can use this
address to email your users. These permissions are granted by a sending authorization policy, which gets
attached to the address in Amazon SES. If you use the Amazon Cognito console to add your custom
address to your user pool, it automatically attaches the policy for you. But, if you configure your user
pool outside of the console, for example by using the AWS CLI or Amazon Cognito API, you must attach
the policy yourself.
For more information, see Using Sending Authorization with Amazon SES in the Amazon Simple Email
Service Developer Guide.
The following example is a sending authorization policy that allows Amazon Cognito to send email by
using an Amazon SES verified email address.
142
Amazon Cognito Developer Guide
Configuring the Email Account
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "stmnt1234567891234",
"Effect": "Allow",
"Principal": {
"Service": "cognito-idp.amazonaws.com"
},
"Action": [
"ses:SendEmail",
"ses:SendRawEmail"
],
"Resource": "<your SES identity ARN>"
}
]
}
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 in the Amazon
Simple Email Service Developer Guide.
For more examples, see Amazon SES Sending Authorization Policy Examples in the Amazon Simple Email
Service Developer Guide.
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.
Before Amazon Cognito can create this role, the IAM permissions that you use to set up your user pool
must include the iam:CreateServiceLinkedRole action. For more information about updating
permissions in IAM, see Changing Permissions for an IAM User 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 (p. 283).
You don't need to complete this procedure if you want to use the default Amazon Cognito email
functionality and address.
1. Sign in the AWS Management Console and open the Amazon Cognito console at https://
console.aws.amazon.com/cognito.
2. Choose Manage User Pools.
143
Amazon Cognito Developer Guide
Using Tokens
3. On the Your User Pools page, choose the user pool that you want to configure.
4. In the navigation menu on the left, choose Message customizations.
5. If you want to use a custom FROM address, choose Add custom FROM address and do the
following:
a. For SES region, choose the region that contains your verified email address.
b. For Source ARN, choose your email address. The Amazon Cognito console allows you to choose
only those email addresses that you have verified with Amazon SES in the selected region.
c. For FROM email address, choose your email address. You can provide your email address or
your email address with your name.
6. Under Do you want to send emails through your Amazon SES Configuration?, choose Yes - Use
Amazon SES or No - Use Cognito (Default).
If you choose to use a Amazon SES, Amazon Cognito will create a service-linked role after you save
your changes.
7. If you want to use a custom REPLY-TO address, choose Add custom REPLY-TO address. Then,
specify the email address where you want to receive that messages that your users send to your
FROM address.
8. When you finish setting your email account options, choose Save changes.
The Message customizations page also provides the options to customize your verification
messages (p. 166) and customize your invitation messages (p. 167).
User pool token handling and management for your web or mobile app is provided on the client side
through Amazon Cognito SDKs. For information on the SDKs, and sample code for JavaScript, Android,
and iOS see Amazon Cognito User Pool SDKs. Many good libraries are available for decoding and
verifying a JSON Web Token (JWT). Such libraries can help if you need to manually process tokens for
server-side API processing, or if you are using other programming languages. See the OpenID Foundation
list of libraries for working with JWT tokens.
Amazon Cognito user pools implements ID, access, and refresh tokens as defined by the OpenID Connect
(OIDC) open standard:
• The ID token contains claims about the identity of the authenticated user such as name, email, and
phone_number.
• The access token contains scopes and groups and is used to grant access to authorized resources.
• The refresh token contains the information necessary to obtain a new ID or access token.
Important
We strongly recommended that you secure all tokens in transit and storage in the context of
your application.
144
Amazon Cognito Developer Guide
Using the ID Token
For more information on OIDC see the OpenID Connect (OIDC) specification.
Topics
• Using the ID Token (p. 145)
• Using the Access Token (p. 146)
• Using the Refresh Token (p. 148)
• Revoking All Tokens for a User (p. 149)
• Verifying a JSON Web Token (p. 149)
ID Token Header
The header contains two pieces of information: the key ID (kid), and the algorithm (alg).
{
"kid" : "1234example="
"alg" : "RS256",
}
Key ID (kid)
The kid parameter is a hint that indicates which key was used to secure the JSON Web Signature
(JWS) of the token.
For more information about the kid parameter, see the Key Identifier (kid) Header Parameter.
Algorithm (alg)
The alg 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 about the alg parameter, see Algorithm (alg) Header Parameter.
ID Token Payload
This is a sample payload from an ID token. It contains claims about the authenticated user. For more
information about OIDC standard claims, see the OIDC Standard Claims.
{
"sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"aud": "xxxxxxxxxxxxexample",
"email_verified": true,
145
Amazon Cognito Developer Guide
Using the Access Token
"token_use": "id",
"auth_time": 1500009400,
"iss": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example",
"cognito:username": "janedoe",
"exp": 1500013000,
"given_name": "Jane",
"iat": 1500009400,
"email": "[email protected]"
}
Subject (sub)
The sub claim is a unique identifier (UUID) for the authenticated user. It is not the same as the user
name which may not be unique.
Issuer (iss)
https://cognito-idp.{region}.amazonaws.com/{userPoolId}.
For example, suppose you created a user pool in the us-east-1 Region and its user pool ID is
u123456. In that case, the ID token that is issued for users of your user pool have the following iss
claim value:
https://cognito-idp.us-east-1.amazonaws.com/u123456.
Audience (aud)
The aud claim contains the client_id that is used in the user authenticated.
Token use (token_use)
The token_use claim describes the intended purpose of this token. Its value is always id in the
case of the ID token.
Authentication time (auth_time)
The auth_time claim contains the time when the authentication occurred. Its value is a JSON
number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC format.
On refreshes, it represents the time when the original authentication occurred, not the time when
the token was issued.
The ID token can contain OpenID Connect (OIDC) standard claims that are defined in OIDC Standard
Claims. It can also contain custom attributes that you define in your user pool.
Note
User pool custom attributes are always prefixed with a custom: prefix.
ID Token Signature
The signature of the ID token is calculated based on the header and payload of the JWT token. When
used outside of an application in your web APIs, you must always verify this signature before accepting
the token. See Verifying a JSON Web Token (p. 149).
146
Amazon Cognito Developer Guide
Using the Access Token
You can also use the access token to make access control decisions and authorize operations for your
users based on scopes or groups.
The access token is represented as a JSON Web Token (JWT). The header for the access token has the
same structure as the ID token. However, the key ID (kid) is different because different keys are used to
sign ID tokens and access tokens. As with the ID token, you must first verify the signature of the access
token in your web APIs before you can trust any of its claims. See Verifying a JSON Web Token (p. 149)
You can set the access token expiration to any value between 5 minutes and 1 day. This value can be set
per app client.
Important
For access and ID tokens, don't specify a minimum less than an hour. Amazon Cognito HostedUI
uses cookies that are valid for an hour, if you enter a minimum less than an hour, you won't get
a lower expiry time.
{
"kid" : "1234example="
"alg" : "RS256",
}
Key ID (kid)
The kid parameter is a hint indicating which key was used to secure the JSON Web Signature (JWS)
of the token.
For more information about the kid parameter, see the Key Identifier (kid) Header Parameter.
Algorithm (alg)
The alg parameter represents the cryptographic algorithm that was 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.
{
"sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"device_key": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"cognito:groups": [
"admin"
],
"token_use": "access",
"scope": "aws.cognito.signin.user.admin",
"auth_time": 1562190524,
"iss": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_example",
"exp": 1562194124,
"iat": 1562190524,
"jti": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"client_id": "57cbishk4j24pabc1234567890",
"username": "[email protected]"
}
147
Amazon Cognito Developer Guide
Using the Refresh Token
Subject (sub)
The sub claim is a unique identifier (UUID) for the authenticated user. It is not the same as the user
name, which may not be unique.
Amazon Cognito groups (cognito:groups)
The token_use claim describes the intended purpose of this token. Its value is always access in
the case of the access token.
Scope (scope)
The scope claim is a list of Oauth 2.0 scopes that define what access the token provides.
Authentication time (auth_time)
The auth_time claim contains the time when the authentication occurred. Its value is a JSON
number that represents the number of seconds from 1970-01-01T0:0:0Z as measured in UTC
format. On refreshes, it represents the time when the original authentication occurred, not the time
when the token was issued.
Issuer (iss)
https://cognito-idp.{region}.amazonaws.com/{userPoolId}.
By default, the refresh token expires 30 days after your app user signs in to your user pool. When you
create an app for your user pool, you can set the app's refresh token expiration to any value between 60
minutes and 10 years.
The Mobile SDK for iOS and the Mobile SDK for Android automatically refresh your ID and access tokens
if there is a valid (unexpired) refresh token present. The ID and access tokens have a minimum remaining
validity of 5 minutes. If the refresh token is expired, your app user must reauthenticate by signing in
again to your user pool. If the minimum for the access token and ID token is set to 5 minutes, and
you are using the SDK, the refresh token will continually refresh. To see the expected behavior, set a
minimum of 7 minutes instead of 5 minutes.
Note
The Mobile SDK for Android offers the option to change the minimum validity period of the ID
and access tokens to a value between 0 and 30 minutes. See the setRefreshThreshold()
method of CognitoIdentityProviderClientConfig in the AWS Mobile SDK for Android API
Reference.
Your user's account itself never expires, as long as the user has logged in at least once before the
UnusedAccountValidityDays time limit for new accounts.
To use the refresh token to get new ID and access tokens with the user pool API, use the
AdminInitiateAuth or InitiateAuth methods. Pass REFRESH_TOKEN_AUTH for the AuthFlow
148
Amazon Cognito Developer Guide
Revoking All Tokens for a User
parameter. The authorization parameters, AuthParameters, are a key-value map where the key is
"REFRESH_TOKEN" and the value is the actual refresh token. Amazon Cognito responds with new ID and
access tokens.
• The user's refresh token cannot be used to get new tokens for the user.
• The user's access token cannot be used for the user pools service.
• The user must reauthenticate to get new tokens.
An app can use the GlobalSignOut API to allow individual users to sign themselves out from all
devices. Typically an app would present this option as a choice, such as Sign out from all devices. The
app must call this method with the user's valid, nonexpired, nonrevoked access token. This method
cannot be used to allow a user to sign out another user.
An administrator app can use the AdminUserGlobalSignOut API to allow administrators to sign out a
user from all devices. The administrator app must call this method with AWS developer credentials and
pass the user pool ID and the user's user name as parameters. The AdminUserGlobalSignOut API can
sign out any user in the user pool.
Topics
• Prerequisites (p. 149)
• Step 1: Confirm the Structure of the JWT (p. 149)
• Step 2: Validate the JWT Signature (p. 150)
• Step 3: Verify the Claims (p. 151)
Prerequisites
The tasks in this section might be already handled by your library, SDK, or software framework. For
example, user pool token handling and management are provided on the client side through the Amazon
Cognito SDKs. Likewise, the Mobile SDK for iOS and the Mobile SDK for Android automatically refresh
your ID and access tokens if two conditions are met: A valid (unexpired) refresh token must present, and
the ID and access tokens must have a minimum remaining validity of 5 minutes. For information on the
SDKs, and sample code for JavaScript, Android, and iOS see Amazon Cognito User Pool SDKs.
Many good libraries are available for decoding and verifying a JSON Web Token (JWT). Such libraries
can help if you need to manually process tokens for server-side API processing or if you are using other
programming languages. See the OpenID Foundation list of libraries for working with JWT tokens.
1. Header
2. Payload
149
Amazon Cognito Developer Guide
Verifying a JSON Web Token
3. Signature
11111111111.22222222222.33333333333
These sections are encoded as base64url strings and are separated by dot (.) characters. If your JWT does
not conform to this structure, consider it invalid and do not accept it.
You can use AWS Lambda to decode user pool JWTs. For more information see Decode and verify
Amazon Cognito JWT tokens using Lambda.
The OpenID Foundation also maintains a list of libraries for working with JWT tokens.
2. Compare the local key ID (kid) to the public kid.
a. 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 at https://cognito-idp.
{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json.
For more information on JWK and JWK sets, see JSON Web Key (JWK).
Note
This is a one-time step before your web APIs can process tokens. Now you can perform
the following steps each time the ID token or the access token are used with your web
APIs.
{
"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.
150
Amazon Cognito Developer Guide
Verifying a JSON Web Token
Algorithm (alg)
The alg header parameter represents the cryptographic algorithm 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.
Key type (kty)
The kty parameter identifies the cryptographic algorithm family 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.
b. Search the public JSON web key for a kid that matches the kid of your JWT.
3. Use the public key to verify the signature using your JWT library. You might need to convert
the JWK to PEM format first. This example takes the JWT and JWK and uses the Node.js library,
jsonwebtoken, to verify the JWT signature:
Node.js
https://cognito-idp.us-east-1.amazonaws.com/<userpoolID>.
4. Check the token_use claim.
• If you are only accepting the access token in your web APIs, 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.
After a successful authentication, your app will receive user pool tokens from Amazon Cognito. You can
use those tokens to retrieve AWS credentials that allow your app to access other AWS services, or you
might choose to use them to control access to your own server-side resources, or to the Amazon API
Gateway.
For more information, see User Pool Authentication Flow (p. 287) and Using Tokens with User
Pools (p. 144).
Topics
• Accessing Server-side Resources after Sign-in (p. 6)
• Accessing Resources with API Gateway and Lambda After Sign-in (p. 153)
• Accessing AWS Services Using an Identity Pool After Sign-in (p. 153)
Once you configure a domain for your user pool, Amazon Cognito provisions a hosted web UI that allows
you to add sign-up and sign-in pages to your app. Using this OAuth 2.0 foundation you can create
your own resource server to enable your users to access protected resources. For more information see
Defining Resource Servers for Your User Pool (p. 41).
152
Amazon Cognito Developer Guide
Accessing Resources with API Gateway and Lambda
For more information about user pool authentication see User Pool Authentication Flow (p. 287) and
Using Tokens with User Pools (p. 144).
You can use groups in a user pool to control permissions with API Gateway by mapping group
membership to IAM roles. The groups that a user is a member of are included in the ID token provided
by a user pool when your web or mobile app user signs in. For more information on user pool groups See
Adding Groups to a User Pool (p. 124).
You can submit your user pool tokens with a request to API Gateway for verification by an Amazon
Cognito authorizer Lambda function. For more information on API Gateway, see Using API Gateway with
Amazon Cognito user pools.
After a successful authentication, your web or mobile app will receive user pool tokens from Amazon
Cognito. You can use those tokens to retrieve AWS credentials that allow your app to access other AWS
services. For more information, see Getting Started with Amazon Cognito Identity Pools (Federated
Identities) (p. 180).
153
Amazon Cognito Developer Guide
Accessing AWS Resources Using an Identity Pool
For more information about using identity pools together with user pool groups to control access your
AWS resources see Adding Groups to a User Pool (p. 124) and Role-Based Access Control (p. 201). See
also Identity Pools Concepts (Federated Identities) (p. 186) for more information about identity pools
and AWS Identity and Access Management.
154
Amazon Cognito Developer Guide
Accessing AWS Resources Using an Identity Pool
If successful, you will see Changes saved successfully. on the Dashboard page.
cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>
The value for <region> will be the same as the region in the User Pool ID. For example, cognito-
idp.us-east-1.amazonaws.com/us-east-1_123456789.
JavaScript
if (cognitoUser != null) {
cognitoUser.getSession(function(err, result) {
if (result) {
console.log('You are now logged in.');
Android
cognitoUser.getSessionInBackground(new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession session) {
String idToken = session.getIdToken().getJWTToken();
});
iOS - Objective-C
155
Amazon Cognito Developer Guide
User Pools Console Reference
iOS - Swift
Topics
• Adding a User Pool Name (p. 156)
• Importing and Creating Users and Groups (p. 157)
• Configuring User Pool Attributes (p. 157)
• Adding User Pool Password Requirements (p. 163)
• Configuring an Admin Create User Policy (p. 163)
• Configuring Email or Phone Verification (p. 163)
• Configuring SMS and Email Verification Messages and User Invitation Messages (p. 165)
• Adding Cost Allocation Tags to Your User Pool (p. 168)
• Specifying User Pool Device Tracking Settings (p. 168)
• Configuring a User Pool App Client (p. 169)
• Configuring User Pool Lambda Triggers (p. 170)
• Reviewing Your User Pool Creation Settings (p. 171)
• Configuring User Pool Analytics (p. 171)
• Configuring App Client Settings (p. 172)
• Adding a Domain Name for Your User Pool (p. 172)
• Customizing the Built-in App UI to Sign Up and Sign In Users (p. 173)
• Adding Resource Servers for Your User Pool (p. 173)
• Configuring Identity Providers for Your User Pool (p. 174)
• Configuring Attribute Mapping for Your User Pool (p. 177)
156
Amazon Cognito Developer Guide
Users and groups
Pool names must be between one and 128 characters long. They can contain uppercase and lowercase
letters (a-z, A-Z), numbers (0-9), and the following special characters: + = , . @ and -.
• Importing Users into User Pools From a CSV File (p. 131)
• Adding Groups to a User Pool (p. 124)
• Creating User Accounts as Administrator (p. 121)
Attributes are pieces of information that help you identify individual users, such as name, email, and
phone number.
Not all information about your users should be stored in attributes. For example, user data that changes
frequently, such as usage statistics or game scores, should be kept in a separate data store, such as
Amazon Cognito Sync or Amazon DynamoDB.
Standard Attributes
The following are the standard attributes for all users in a user pool. These are implemented following
the OpenID Connect specification.
• address
• birthdate
• email
• family_name
• gender
• given_name
• locale
• middle_name
• name
• nickname
• phone_number
• picture
• preferred_username
• profile
• updated_at
• website
• zoneinfo
157
Amazon Cognito Developer Guide
Attributes
These attributes are available as optional attributes for all users. To make an attribute required, select
the check box next to the attribute.
Note
When a standard attribute is marked as required, a user cannot register unless a value for
the attribute is provided. Administrators can create users without giving values for required
attributes by using the AdminCreateUser API. An attribute cannot be switched between required
and not required after a user pool has been created.
Standard and custom attribute values can be any string up to 2048 characters by default, but some
attribute values, such as updated_at, have formatting restrictions. Only email and phone can be
verified.
Note
In the specification, attributes are called members.
Here are some additional notes regarding some of the above fields.
An administrator with proper AWS account permissions can change the user's email and also mark
it as verified. This can be done by using the AdminUpdateUserAttributes API or the admin-update-
user-attributes CLI command to change the email_verified attribute to true.
phone
A phone number is required if SMS multi-factor authentication (MFA) is enabled. For more
information, see Adding Multi-Factor Authentication (MFA) to a User Pool (p. 303).
An administrator with proper AWS account permissions can change the user's phone number and
also mark it as verified. This can be done by using the AdminUpdateUserAttributes API or the admin-
update-user-attributes CLI command to change the phone_number_verified attribute to true.
Important
Phone numbers must follow these formatting rules: A phone number must start with a plus
(+) sign, followed immediately by the country code. A phone number can only contain the
+ sign and digits. You must remove any other characters from a phone number, such as
parentheses, spaces, or dashes (-) before submitting the value to the service. For example, a
United States-based phone number must follow this format: +14325551212.
preferred_username
158
Amazon Cognito Developer Guide
Attributes
Developers can use the preferred_username attribute to give users a username that they can change.
For more information, see Overview of Aliases (p. 159).
If your application does not require a username, you do not need to ask users to provide one. Your app
can create a unique username for users in the background. This is useful if, for example, you want users
to register and sign in with an email address and password. For more information, see Overview of
Aliases (p. 159).
The username must be unique within a user pool. A username can be reused, but only after it has been
deleted and is no longer in use.
Overview of Aliases
You can allow your end users to sign in with multiple identifiers by using aliases.
By default, users sign in with their username and password. The username is a fixed value that users
cannot change. If you mark an attribute as an alias, users can sign in using that attribute in place of
the username. The email address, phone number, and preferred username attributes can be marked as
aliases.
For example, if email and phone are selected as aliases for a user pool, users in that user pool can sign in
using their username, email address, or phone number, along with their password.
Note
You can choose to sign in or sign up using either lowercase or uppercase letters in an alias
when you configure your user pool for username case insensitivity. For more information, see
CreateUserPool in the Amazon Cognito user pools API Reference.
If email is selected as an alias, a username cannot match a valid email format. Similarly, if phone number
is selected as an alias, a username that matches a valid phone number pattern is not accepted by the
service for that user pool.
Note
Alias values must be unique in a user pool. If an alias is configured for an email address or phone
number, the value provided can be in a verified state in only one account. During sign-up, if an
email address or phone number is supplied as an alias from a different account that has already
been used, registration succeeds. Nevertheless, when a user tries to confirm the account with
this email (or phone number) and enters the valid code, an AliasExistsException error
is thrown. The error indicates to the user that an account with this email (or phone number)
already exists. At this point, the user can abandon the new account creation and can try to reset
the password for the old account. If the user continues creating the new account, your app
should call the ConfirmSignUp API with the forceAliasCreation option. This moves the
alias from the previous account to the newly created account, and it also marks the attribute
unverified in the previous account.
Phone numbers and email addresses only become active aliases for a user after the phone numbers and
email addresses are verified. We therefore recommend that you choose automatic verification of email
addresses and phone numbers if you use them as aliases. The preferred_username attribute provides
159
Amazon Cognito Developer Guide
Attributes
users the experience of changing their username, when in fact the actual username value for a user is not
changeable.
If you want to enable 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 they entered.
If preferred_username is selected as an alias, the value can be provided only when an account is
confirmed. The value cannot be provided during registration.
Topics
• Option 1: User Signs Up with Username and Signs In with Username or Alias (p. 160)
• Option 2: User Signs Up and Signs In with Email or Phone Number Instead of Username (p. 160)
Option 1: User Signs Up with Username and Signs In with Username or Alias
In this case, the user signs up with a username. In addition, you can optionally allow users to sign in with
one or more of the following aliases:
Use the following steps to configure your user pool in the console to allow sign-in with an alias.
1. In the Attributes tab, under How do you want your end users to sign-up and sign-in?, select
Username.
2. Choose one of the following options:
• Also allow sign in with verified email address: This allows users to sign in with their email
address.
• Also allow sign in with verified phone number: This allows users to sign in with their phone
number.
• Also allow sign in with preferred username: This allows users to sign in with a preferred
username. This is a username that the user can change.
Option 2: User Signs Up and Signs In with Email or Phone Number Instead of
Username
In this case, the user signs up with an email address or phone number as their username. You can choose
whether to allow sign-up with only email addresses, only phone numbers, or either one.
The email or phone number must be unique, and it must not already be in use by another user. It does
not have to be verified. After the user has signed up using an email or phone number, the user cannot
160
Amazon Cognito Developer Guide
Attributes
create a new account with the same email or phone number; the user can only reuse the existing account
(and reset the password if needed). However, the user can change the email or phone number to a new
email or phone number; if it is not already in use, it becomes the new username.
Note
If users sign up with an email address as their username, they can change the username to
another email address; they cannot change it to a phone number. If they sign up with a phone
number, they can change the username to another phone number; they cannot change it to an
email address.
Use the following steps to configure your user pool in the console to allow sign-up and sign-in with
email or phone number.
To configure a user pool for sign-up and sign-in with email or phone number
1. In the Attributes tab, under How do you want your end users to sign-up and sign-in?, select Email
address or phone number.
2. Choose one of the following options:
• Allow email addresses: This allows your user to sign up with email as the username.
• Allow phone numbers: This allows your user to sign up with phone number as the username.
• Allow both email addresses and phone number (users can choose one): This allows your user to
use either an email address or a phone number as the username during sign-up.
Note
You do not need to mark email or phone number as required attributes for your user pool.
1. Call the CreateUserPool API to create your user pool. Set the UserNameAttributes parameter
to phone_number, email, or phone_number | email.
2. Call the SignUp API and pass an email address or phone number in the username parameter of the
API. This API does the following:
• If the username string is in valid email format, 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, the user pool automatically populates
the phone_number attribute of the user with the username value.
• If the username string format is not in email or phone number format, the SignUp API throws an
exception.
• The SignUp API generates a persistent UUID for your user, and uses it as the immutable username
attribute internally. This UUID has the same value as the sub claim in the user identity token.
• If the username string contains an email address or phone number that is already in use, the
SignUp API throws an exception.
You can use an email address or phone number as an alias in place of the username in all APIs except the
ListUsers API. When you call ListUsers, you can search by the email or phone_number attribute; if
you search by username, you must supply the actual username, not an alias.
Custom Attributes
You can add up to 25 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.
161
Amazon Cognito Developer Guide
Attributes
Note
In your code and in rules settings for Role-Based Access Control (p. 201), custom attributes
require the custom: prefix to distinguish them from standard attributes.
a. Choose Add another attribute under Do you want to add custom attributes?.
b. Choose the properties for each custom attribute, such as the data Type (string or number), the
Name, Min length, and Max length.
c. If you want to allow the user to change the value of a custom attribute after the value has been
provided by the user, select Mutable.
Repeat these steps for each app client using the custom attribute.
Attributes can be marked as readable or writable for each app. This is true for both standard and
custom attributes. An app can read an attribute that is marked as readable and can write an attribute
that is marked as writable. If an app tries to update an attribute that is not writable, the app gets a
NotAuthorizedException exception. An app calling GetUser only receives the attributes that are
readable for that app. The ID token issued post-authentication only contains claims corresponding
to the readable attributes. Required attributes on a user pool are always writable. If you, using
CLI or the admin API, set a writable attribute and do not provide required attributes, then an
InvalidParameterException exception is thrown.
You can change attribute permissions and scopes after you have created your user pool.
162
Amazon Cognito Developer Guide
Password Requirements
• Minimum length, which must be at least 6 characters but fewer than 99 characters
• Require numbers
• Require a special character from this set:
• Specify whether to allow users to sign themselves up. This option is set by default. If it is
not set, only administrators can create users in this pool and calls to the SignUp API fail with
NotAuthorizedException.
• Specify the user account expiration time limit (in days) for new accounts. The default setting is 7 days,
measured from the time when the user account is created. The maximum setting is 90 days. After the
account expires, the user cannot log in to the account until the administrator updates the user's profile
by updating an attribute or by resending the password to the user.
Note
Once the user has logged in, the account never expires.
Amazon Cognito can automatically verify email addresses or mobile phone numbers by sending a
verification code—or, for email, a verification link. For email addresses, the code or link is sent in an email
message. For phone numbers, the code is sent in an SMS text message.
Verification of a phone or email is necessary to automatically confirm users and enable recovery from
forgotten passwords. Alternatively, you can automatically confirm users with the pre-sign up Lambda
trigger or by using the AdminConfirmSignUp API. For more information, see Signing Up and Confirming
User Accounts (p. 114).
163
Amazon Cognito Developer Guide
Email or Phone Verification
If verification is selected as required for email or phone, the verification code or link is automatically sent
when a user signs up.
Notes
• Use of SMS text messaging for verifying phone numbers is charged separately by Amazon
SNS. (There is no charge for sending verification codes to email addresses.) For information
about Amazon SNS pricing, see Worldwide SMS Pricing. For the current list of countries where
SMS messaging is available, see Supported Regions and Countries.
• When you test actions in your app that initiate emails from Amazon Cognito, use a real
email address that Amazon Cognito can send to without incurring hard bounces. For more
information, see the section called “Sending Emails While Testing Your App” (p. 120).
• The forgotten password flow requires either the user's email or the user's phone number to be
verified.
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, a verification code is sent via SMS to the phone. The email
address is not verified, so your app needs to call GetUser to see if an email address is awaiting
verification. If it is, the app should call GetUserAttributeVerificationCode to initiate the email
verification flow and then submit the verification code by calling VerifyUserAttribute.
Spend limits can be specified for an AWS account and for individual messages, and the limits apply only
to the cost of sending SMS messages. For more information, see Amazon SNS FAQs.
SMS messages from Amazon Cognito user pools are routed through Amazon SNS in the same region
unless noted in the following table.
Example: If your Cognito user pool is in us-east-1 region, you can update the Amazon SNS limit in us-
east-1 region.
Example: If your Cognito user pool is in ap-south-1 region, you can update the Amazon SNS limit in ap-
southeast-1 region.
164
Amazon Cognito Developer Guide
Message Customizations
Note
The SMS and email verification message templates only appear if you have chosen to require
phone number and email verification in the Verifications tab. Similarly, the SMS MFA message
template only appears if the MFA setting is REQUIRED or OPTIONAL.
Topics
• Message Templates (p. 165)
• Customizing the SMS Message (p. 166)
• Customizing Email Verification Messages (p. 166)
• Customizing User Invitation Messages (p. 167)
• Customizing Your Email Address (p. 167)
• Authorizing Amazon Cognito to Send Amazon SES Email on Your Behalf (from a Custom FROM Email
Address) (p. 167)
Message Templates
Message templates allow you to insert a field into your message using a placeholder that will be replaced
with the corresponding value.
Template placeholders
Description Token
Note
{username} can't be used in verification emails. {username} is available for invitation emails
sent after AdminCreateUser call. These invitation emails provide two place holders: username
{username} and temporary password {####}
• Include specific details about an event such as IP address, city, country, login time, and device name,
for analysis by Amazon Cognito advanced security features.
• Verify whether a one-click link is valid.
165
Amazon Cognito Developer Guide
Message Customizations
• Build your own one-click link using event ID, feedback token, and username.
Description Token
IP address {ip-address}
City {city}
Country {country}
Event ID {event-id}
The maximum length for the message is 140 UTF-8 characters, including the authentication code.
The maximum length for the message is 140 UTF-8 characters, including the verification code.
You can customize the email subject and message for email address verifications by editing the template
under the Do you want to customize your email verification messages? heading.
Important
If you have chosen code as the verification type, your custom message must contain the {####}
placeholder, which is replaced with the verification code before the message is sent.
The maximum length for the message is 20,000 UTF-8 characters, including the verification code (if
present). HTML tags can be used in these emails.
166
Amazon Cognito Developer Guide
Message Customizations
For SMS, the maximum length is 140 UTF-8 characters, including the verification code. For email, the
maximum length for the message is 20,000 UTF-8 characters, including the verification code. HTML tags
can be used in these emails.
To customize the FROM email address, in the console, choose a userpool. Next, choose Message
customizations. In Message customizations, choose a SES Region . In the FROM email address ARN
field enter your email address. Verify the Amazon Simple Email Service identity by choosing the link
after the FROM email address ARN field. For more information, see Verifying Email Addresses and
Domains in Amazon SES in the Amazon Simple Email Service Developer Guide.
To customize the REPLY-TO email address, enter a valid email address in the REPLY-TO email address
field.
The following is an example of an Amazon SES sending authorization policy for Amazon Cognito user
pools. For more examples, see Amazon SES Sending Authorization Policy Examples 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 in the
Amazon Simple Email Service Developer Guide.
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "stmnt1234567891234",
"Effect": "Allow",
"Principal": {
"Service": "cognito-idp.amazonaws.com"
},
"Action": [
"ses:SendEmail",
"ses:SendRawEmail"
],
167
Amazon Cognito Developer Guide
Tags
The Amazon Cognito console adds this 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 this policy to your
Amazon SES Identity.
To add a tag, choose Add tag. Specify a Tag key and Tag value, following the restrictions listed in Tag
Restrictions. Choose Save changes to save your tag.
Important
In order for tags to appear on your billing reports, you must activate your applied tags in the
billing console. For more information, see Activating User-Defined Cost Allocation Tags in the
AWS Billing and Cost Management User Guide.
When setting up the remembered devices functionality through the Amazon Cognito console, you have
three options: Always, User Opt-In, and No.
If either Always or User Opt-In is selected, a device identifier (key and secret) will be assigned to each
device the first time a user signs in with that device. This key will not be used for anything other than
identifying the device, but it will be tracked by the service.
If you select Always, Amazon Cognito will use the device identifier (key and secret) to authenticate the
device on every user sign-in with that device as part of the user authentication flow.
If you select User Opt-In, you can remember devices only when your application's users opt to do so.
When a user signs in with a new device, the response from the request to initiate tracking indicates
whether the user should be prompted about remembering their device. You must create the user
168
Amazon Cognito Developer Guide
App Clients
interface to prompt users. If the user opts to have the device remembered, the device status is updated
with a 'remembered' state.
The AWS Mobile SDKs have additional APIs to see remembered devices (ListDevices, GetDevice),
mark a device as remembered or not remembered (UpdateDeviceStatus), and stop tracking a device
(ForgetDevice). In the REST API, there are additional administrator versions of these APIs that
have elevated privileges and work on any user. They have API names such as AdminListDevices,
AdminGetDevice, and so on. They are not exposed through the SDKs.
You can create multiple apps for a user pool. Generally an app corresponds to the platform of an app.
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.
When you create an app, you can optionally choose to create a secret for that app. If a secret is created
for the app, the secret must be provided to use the app. Browser-based applications written in JavaScript
might not need an app with a secret.
Secrets cannot be changed after an app is created. You can create a new app with a new secret if you
want to rotate the secret that you are using. You can also delete an app to block access from apps that
use that app client ID.
169
Amazon Cognito Developer Guide
Triggers
Important
If you use Hosted UI and setup tokens less than an hour, the end user will be able to get
new tokens based on their session cookie which is currently fixed at one hour.
10. By default, user pools generate a client secret for your app. If you don't want that to happen, clear
Generate client secret.
11. If your server app requires developer credentials (using Signature Version 4) and doesn't use Secure
Remote Password (SRP) authentication select Enable username password auth for admin APIs for
authentication (ALLOW_ADMIN_USER_PASSWORD_AUTH) to enable server-side authentication.
For more information, see Admin authentication flow (p. 291).
12. Under Prevent User Existence Errors, choose Legacy or Enabled. For more information, see
Managing error response.
13. By default, user pools allow your app to read and write all attributes. If you want to set different
permissions for your app, perform the following steps or choose Create app client to finish.
• Choose one or more scopes. Each scope is a set of standard attributes. For more information,
see the list of standard OIDC scopes.
• Choose individual standard or custom attributes.
Note
You cannot remove required attributes from write permissions in any app.
14. Choose Create app client.
15. If you want to create another app, choose Add an app.
16. Once you've created all the apps you want, choose Return to pool details, update any other fields,
and then choose Create pool.
To create and update app clients in a user pool (API, AWS CLI)
A user migration Lambda trigger allows easy migration of users from your existing user management
system into your user pool.
For examples of each Lambda trigger, see Customizing User Pool Workflows with Lambda
Triggers (p. 64).
Note
The Custom message AWS Lambda trigger is an advanced way to customize messages for
email and SMS. For more information, see Customizing User Pool Workflows with Lambda
Triggers (p. 64).
170
Amazon Cognito Developer Guide
Review Settings
If you see a message, follow the instructions to fix them before choosing Create pool.
Using Amazon Pinpoint Analytics, you can track Amazon Cognito user pools sign-ups, sign-ins, failed
authentications, daily active users (DAUs), and monthly active users (MAUs). You can also set up user
attributes specific to your app using the AWS Mobile SDK for Android or AWS Mobile SDK for iOS. Those
can then be used to segment your users in Amazon Pinpoint and send them targeted push notifications.
In the Analytics tab, you can specify an Amazon Pinpoint project for your Amazon Cognito app client.
For more information, see Using Amazon Pinpoint Analytics with Amazon Cognito user pools (p. 111).
Note
Amazon Pinpoint is available in several AWS Regions in North America, Europe, Asia, and
Oceania. Amazon Pinpoint regions include the Amazon Pinpoint API. If a Amazon Pinpoint
region is supported by Amazon Cognito, then Amazon Cognito will send events to Amazon
Pinpoint projects within the same Amazon Pinpoint region. If a region isn't supported by
Amazon Pinpoint, then Amazon Cognito will only support sending events in us-east-1. For
Amazon Pinpoint detailed region information, see Amazon Pinpoint endpoints and quotas and
Using Amazon Pinpoint Analytics with Amazon Cognito User Pools.
171
Amazon Cognito Developer Guide
App Client Settings
5. Enter an IAM role that you already created or choose Create new role to create a new role in the
IAM console.
6. Choose Save changes.
7. To specify additional app mappings, choose Add app mapping.
8. Choose Save changes.
On the General settings tab, you must configure at least one identity provider (IdP) for your apps if you
want to use the built-in hosted pages to sign up and sign in users or you want to use OAuth2.0 flows. For
more information, see Configuring a User Pool App Client (p. 29).
1. In Enabled Identity Providers, select the identity providers you want for the apps that you
configured in the App Clients tab.
2. Enter the Callback URLs you want, separated by commas. These URLs apply to all of the selected
identity providers.
Note
You must register the URLs in the console, or by using the CLI or API, before you can use
them in your app.
3. Enter the Sign out URLs you want, separated by commas.
Note
You must register the URLs in the console, or by using the CLI or API, before you can use
them in your app.
4. Under OAuth 2.0, select the from the following options. For more information, see App Client
Settings Terminology (p. 31) and the OAuth 2.0 specification.
• For Allowed OAuth Flows, select Authorized code grant and Implicit grant. Select Client
credentials only if your app needs to request access tokens on its own behalf, not on behalf of a
user.
• For Allowed OAuth Scopes, select the scopes you want. Each scope is a set of one or more
standard attributes.
• For Allowed Custom Scopes, select the scopes you want from any custom scopes that you have
defined. Custom scopes are defined in the Resource Servers tab. For more information, see
Defining Resource Servers for Your User Pool (p. 41).
On the Domain name tab, you can enter your own prefix domain name. The domain for your app is
https://<domain_prefix>.auth.<region>.amazoncognito.com.
The full URL for your app will look like this example: https://example.auth.us-
east-1.amazoncognito.com/login?redirect_uri=https://
www.google.com&response_type=code&client_id=<client_id_value>
For more information, see Configuring a User Pool Domain (p. 32).
172
Amazon Cognito Developer Guide
UI Customization
Important
Before you can access the URL for your app, you must specify app client settings such as
callback and redirect URLs. For more information, see Configuring App Client Settings (p. 172).
1. Enter the domain name you want in the Prefix domain name box.
2. Choose Check availability as needed.
3. Choose Save changes.
On the UI customization tab, you can add your own customizations to the default app UI.
For detailed information about each of the customization fields, see Customizing the Built-in Sign-in and
Sign-up Webpages (p. 37).
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 Domain name tab. Your app client ID and callback URL are shown
on the General settings tab.
1. Under App client to customize, choose the app you want to customize from the dropdown menu of
app clients that you previously created in the App clients tab.
2. To add a logo to the default app UI, choose Choose a file or drag a file onto the Logo box.
3. Under CSS customizations (optional), you can customize the appearance of the app by changing
various properties from their default values.
4. Choose Save changes.
A resource server is a server for access-protected resources. It handles authenticated requests from an
app that has an access token. A scope is a level of access that an app can request to a resource.
In the Resource Servers tab, you can define custom resource servers and scopes for your user pool. For
more information, see Defining Resource Servers for Your User Pool (p. 41).
173
Amazon Cognito Developer Guide
Identity Providers
2. Enter the name of your resource server, for example, Photo Server.
3. Enter the identifier of your resource server, for example, com.example.photos.
4. Enter the names of the custom scopes for your resources, such as read and write.
5. For each of the scope names, enter a description, such as view your photos and update your
photos.
Each of the custom scopes that you define appears on the App client settings tab, under OAuth2.0
Allowed Custom Scopes; for example com.example.photos/read.
In the Identity providers tab, you can specify identity providers (IdPs) for your user pool. For more
information, see Adding User Pool Sign-in Through a Third Party (p. 43).
Topics
• Allowing Users to Sign in Using a Social Identity Provider (p. 174)
• Allowing Users to Sign in Using an OpenID Connect (OIDC) Identity Provider (p. 175)
• Allowing Users to Sign in Using SAML (p. 176)
To add a social identity provider, you first create a developer account with the identity provider. Once
you have your developer account, you 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.
Here are links to help you get started with social identity providers:
1. Choose a social identity provider such as Facebook, Google, Login with Amazon, or
SignInWithApple.
2. For the Facebook, Google or Amazon app ID and app secret, enter the app ID and app secret that
you received when you created your Facebook, Google, or Login with Amazon client app. For the
Sign in with Apple services ID, team ID, key ID, and private key, enter the service ID you provided to
Apple, and the team ID, key ID, and private key that you received when you created your Sign in with
Apple client app.
3. For App secret, enter the app secret that you received when you created your client app.
4. For Authorize 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) you
want to access with your app. For Facebook, these should be separated by commas (for example,
174
Amazon Cognito Developer Guide
Identity Providers
public_profile, email). For Google, Login with Amazon, and Sign in with Apple (CLI), they
should be separated by spaces (Google example: profile email openid. Login with Amazon
example: profile postal_code. Sign in with Apple example: name email). For Sign in with
Apple (console), use the check boxes to select them.
The end-user is asked to consent to providing these attributes to your app. For more information
about their scopes, see the documentation from Google, Facebook, Login with Amazon, or Sign in
with Apple.
5. Choose Enable Facebook, Enable Google, Enable Login with Amazon, or Enable Sign in with
Apple.
For more information on Social IdPs see Adding Social Identity Providers to a User Pool (p. 43).
1. Go to the Amazon Cognito console. You might be prompted for your AWS credentials.
2. Manage User Pools.
3. Choose an existing user pool from the list, or create a user pool.
4. On the left navigation bar, choose Identity providers.
5. Choose OpenId Connect.
6. Type a unique name into Provider name.
7. Type the OIDC IdP's client ID into Client ID.
8. Type the OIDC IdP's client secret into Client secret.
9. In the drop-down list, choose the HTTP method (either GET or POST) that's used to fetch the details
of the user from the userinfo endpoint into Attributes request method.
10. Type the names of the scopes that you want to authorize. Scopes define which user attributes (such
as name and email) that you want to access with your application. Scopes are separated by spaces,
according to the OAuth 2.0 specification.
Your app user is asked to consent to providing these attributes to your application.
11. Type the URL of your IdP and choose Run discovery.
https://login.salesforce.com
Note
The URL should start with https://, and shouldn't end with a slash /.
• If Run discovery isn't successful, then you need to provide the Authorization endpoint, Token
endpoint, Userinfo endpoint, and Jwks uri (the location of the JSON Web Key).
12. Choose Create provider.
13. On the left navigation bar, choose General settings.
14. Select your OIDC provider as one of the Enabled Identity Providers.
15. Type a callback URL for the Amazon Cognito authorization server to call after users are
authenticated. This is the URL of the page where your user will be redirected after a successful sign-
in.
175
Amazon Cognito Developer Guide
Identity Providers
https://www.example.com
16. Under Allowed OAuth Flows, enable both the Authorization code grant and the Implicit code
grant.
Unless you specifically want to exclude one, select the check boxes for all of the Allowed OAuth
scopes.
17. Choose Save changes.
18. On the Attribute mapping tab on the left navigation bar, add mappings of OIDC claims to user pool
attributes.
a. As a default, the OIDC claim sub is mapped to the user pool attribute Username. You can map
other OIDC claims to user pool attributes. Type in the OIDC claim, and choose the corresponding
user pool attribute from the drop-down list. For example, the claim email is often mapped to
the user pool attribute Email.
b. In the drop-down list, choose the destination user pool attribute.
c. Choose Save changes.
d. Choose Go to summary.
For more information on OIDC IdPs see Adding OIDC Identity Providers to a User Pool (p. 56).
Enabling this flow sends a signed logout request to the SAML IdP when the LOGOUT
Endpoint (p. 342) is called.
Note
If this option is selected and your SAML identity provider expects a signed logout request,
you will also need to 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.
5. Choose Create provider.
6. To create additional providers, repeat the previous steps.
Note
If you see InvalidParameterException while creating a SAML identity provider with an
HTTPS metadata endpoint URL, for example, "Error retrieving metadata from <metadata
176
Amazon Cognito Developer Guide
Attribute Mapping
endpoint>," make sure that the metadata endpoint has SSL correctly set up and that there is a
valid SSL certificate associated with it.
• To get the certificate containing the public key which will be used by the identity provider to verify the
signed logout request, choose Show signing certificate under Active SAML Providers on the SAML
dialog under Identity providers on the Federation console page.
For more information on SAML IdPs see Adding SAML Identity Providers to a User Pool (p. 49).
On the Attribute mapping tab, you can map identity provider (IdP) attributes or assertions to user pool
attributes. For more information, see Specifying Identity Provider Attribute Mappings for Your User
Pool (p. 61).
Note
Currently, only the Facebook id, Google sub, Login with Amazon user_id, and Sign in with
Apple sub attributes can be mapped to the Amazon Cognito User Pools username attribute.
Note
The attribute in the user pool must be large enough to fit the values of the mapped identity
provider attributes, or an error occurs when users sign in. Custom attributes should be set to the
maximum 2048 character size if mapped to identity provider tokens.
You must create mappings for any attributes that are required for your user pool.
To specify a social identity provider attribute mapping for your user pool
i. In the Facebook attribute, Google attribute or Amazon attribute field, enter the name of
the attribute to be mapped.
ii. For User pool attribute, choose the user pool attribute you want to map to the social
identity provider attribute to from the drop-down list.
d. Choose Save changes.
177
Amazon Cognito Developer Guide
Managing error responses
b. In the SAML attribute field, enter the name of the SAML attribute to be mapped.
c. For User pool attribute, choose the user pool attribute you want to map to the SAML attribute
from the drop-down list.
d. Choose Save changes.
When you enable custom error responses, Amazon Cognito authentication APIs return a generic
authentication failure response. The error response tells you the user name or password is incorrect.
Amazon Cognito account confirmation and password recovery APIs return a response indicating a
code was sent to a simulated delivery medium. The error response works when the status is ENABLED
and the user doesn't exist. Below are the detailed behaviors for the Amazon Cognito operations when
PreventUserExistenceErrors is set to ENABLED.
You can use either authentication flow method with the following operations.
• AdminInitiateAuth
• AdminRespondToAuthChallenge
• InitiateAuth
• RespondToAuthChallenge
In the USER_SRP_AUTH authentication flow Amazon Cognito receives a user name and SRP
parameter ‘A’ in the first step. In response, Amazon Cognito returns SRP parameter ‘B’ and ‘salt’ for
the user as per SRP protocol. When a user isn't found, Amazon Cognito returns a simulated response
in the first step as described in RFC 5054. Amazon Cognito returns the same ‘salt’ and internal user
id in Universally Unique IDentifier (UUID) format for the same user name and user pool combination.
When the next operation of RespondToAuthChallenge proof of password runs, Amazon Cognito
returns a generic NotAuthorizedException error indicating either user name or password was
incorrect.
Note
You can use UsernamePassword to simulate a generic response if you are using verification
based aliases and the format of immutable user name isn't a UUID.
ForgotPassword
When a user isn't found, is disabled, or doesn't have a 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 user name format and verification settings of
the user pool.
178
Amazon Cognito Developer Guide
Managing error responses
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.
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
The SignUp operation returns UsernameExistsException when a user name is already taken.
To prevent the UsernameExistsException error for email or phone number during SignUp, you
can use verification based aliases. For more information, see AliasAttributes Amazon Cognito API
Reference guide. For more information about aliases see Overview of Aliases.
Imported users
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 Migrate User
Lambda Trigger.
Custom Authentication Challenge Lambda trigger
If you use Custom Authentication Challenge Lambda Trigger and you enable error responses, then
LambdaChallenge returns a boolean parameter named UserNotFound. Then it's passed in the
request of DefineAuthChallenge, VerifyAuthChallenge, and CreateAuthChallenge
Lambda triggers. You can use this trigger to simulate custom authorization challenges for a user that
doesn't exist. If you call the Pre-Authentication Lambda trigger for a user that doesn't exist, then
Amazon Cognito returns UserNotFound.
179
Amazon Cognito Developer Guide
Getting Started with Identity Pools
• Public providers: Login with Amazon (Identity Pools) (p. 217), Facebook (Identity Pools) (p. 212),
Google (Identity Pools) (p. 220), Sign in with Apple (Identity Pools) (p. 227).
• Amazon Cognito user pools (p. 16)
• Open ID Connect Providers (Identity Pools) (p. 231)
• SAML Identity Providers (Identity Pools) (p. 233)
• Developer Authenticated Identities (Identity Pools) (p. 234)
For information about Amazon Cognito identity pools region availability, see AWS Service Region
Availability.
For more information about Amazon Cognito identity pools, see the following topics.
Topics
• Getting Started with Amazon Cognito Identity Pools (Federated Identities) (p. 180)
• Using Identity Pools (Federated Identities) (p. 182)
• Identity Pools Concepts (Federated Identities) (p. 186)
• Using attributes for access control as a form of attribute-based access control (p. 197)
• Role-Based Access Control (p. 201)
• Getting Credentials (p. 204)
• Accessing AWS Services (p. 210)
• Identity Pools (Federated Identities) External Identity Providers (p. 212)
• Developer Authenticated Identities (Identity Pools) (p. 234)
• Switching Unauthenticated Users to Authenticated Users (Identity Pools) (p. 245)
180
Amazon Cognito Developer Guide
Sign Up for an AWS Account
With an identity pool, you can obtain temporary AWS credentials with permissions you define to directly
access other AWS services or to access resources through Amazon API Gateway.
Topics
• Sign Up for an AWS Account (p. 181)
• Create an Identity Pool in Amazon Cognito (p. 181)
• Install the Mobile or JavaScript SDK (p. 181)
• Integrate the Identity Providers (p. 182)
• Get Credentials (p. 182)
1. Open https://portal.aws.amazon.com/billing/signup.
2. Follow the online instructions.
Part of the sign-up procedure involves receiving a phone call and entering a verification code on the
phone keypad.
1. Sign in to the Amazon Cognito console, choose Manage Identity Pools, and then choose Create new
identity pool.
2. Type a name for your identity pool.
3. To enable unauthenticated identities select Enable access to unauthenticated identities from the
Unauthenticated identities collapsible section.
4. If desired, configure an authentication provider in the Authentication providers section.
5. Choose Create Pool.
Note
At least one identity is required for a valid identity pool.
6. You will be prompted for access to your AWS resources.
Choose Allow to create the two default roles associated with your identity pool–one for
unauthenticated users and one for authenticated users. These default roles provide your identity
pool access to Amazon Cognito Sync. You can modify the roles associated with your identity pool in
the IAM console.
181
Amazon Cognito Developer Guide
Integrate the Identity Providers
To learn more about using an Amazon Cognito user pool to create your own user directory, see Amazon
Cognito user pools (p. 16) and Accessing AWS Services Using an Identity Pool After Sign-in (p. 153).
To learn more about using external identity providers, see Identity Pools (Federated Identities) External
Identity Providers (p. 212).
To learn more about integrating your own back-end authentication process, see Developer Authenticated
Identities (Identity Pools) (p. 234).
Get Credentials
Amazon Cognito identity pools provide temporary AWS credentials for users who are guests
(unauthenticated) and for users who have authenticated and received a token. With those AWS
credentials your app can securely access a back end in AWS or outside AWS through Amazon API
Gateway. See Getting Credentials (p. 204).
1. Sign in to the Amazon Cognito console, choose Manage Identity Pools, and then choose Create new
identity pool.
2. Type a name for your identity pool.
3. To enable unauthenticated identities select Enable access to unauthenticated identities from the
Unauthenticated identities collapsible section.
4. If desired, configure an authentication provider in the Authentication providers section.
5. Choose Create Pool.
Note
At least one identity is required for a valid identity pool.
6. You will be prompted for access to your AWS resources.
Choose Allow to create the two default roles associated with your identity pool–one for
unauthenticated users and one for authenticated users. These default roles provide your identity
182
Amazon Cognito Developer Guide
User IAM Roles
pool access to Amazon Cognito Sync. You can modify the roles associated with your identity pool in
the IAM console. For additional instructions on working with the Amazon Cognito console, see Using
the Amazon Cognito Console (p. 3).
• To configure authenticated identities with a public login provider, see Identity Pools (Federated
Identities) External Identity Providers (p. 212).
• To configure your own backend authentication process, see Developer Authenticated Identities
(Identity Pools) (p. 234).
1. Click the name of the identity pool for which you want to enable or disable unauthenticated identities.
The Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, click Edit identity pool. The Edit identity pool page
appears.
3. Scroll down and click Unauthenticated identities to expand it.
4. Select the checkbox to enable or disable access to unauthenticated identities.
5. Click Save Changes.
For each identity type, there is an assigned role. This role has a policy attached to it which dictates which
AWS services that role can access. When Amazon Cognito receives a request, the service will determine
the identity type, determine the role assigned to that identity type, and use the policy attached to that
role to respond. By modifying a policy or assigning a different role to an identity type, you can control
which AWS services an identity type can access. To view or modify the policies associated with the roles
in your identity pool, see the AWS IAM Console.
183
Amazon Cognito Developer Guide
Enable or edit authentication providers
You can change which role is associated with an identity type using the Amazon Cognito identity pool
(federated identities) console. Choose Manage Identity Pools from the Amazon Cognito console:
1. Click the name of the identity pool for which you want to modify roles. The Dashboard page for your
identity pool appears.
2. In the top-right corner of the Dashboard page, click Edit identity pool. The Edit identity pool page
appears.
3. Use the dropdown menus next to Unauthenticated role and Authenticated role to change roles.
Click Create new role to create or modify the roles associated with each identity type in the AWS IAM
console. For more information, see IAM Roles.
You can also configure authentication rules for each provider from this page. Each provider allows up to
25 rules. The rules are applied in the order you save for each provider. For more information, see Role-
Based Access Control (p. 201).
Warning
Changing the application ID to which an identity pool is linked will disable existing users from
authenticating with that identity pool. Learn more about Identity Pools (Federated Identities)
External Identity Providers (p. 212).
1. Click the name of the identity pool for which you want to enable the external provider. The
Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, click Edit identity pool. The Edit identity pool page
appears.
3. Scroll down and click Authentication providers to expand it.
4. Click the tab for the appropriate provider and enter the required information associated with that
authentication provider.
1. Click the name of the identity pool that you want to delete. The Dashboard page for your identity
pool appears.
2. In the top-right corner of the Dashboard page, click Edit identity pool. The Edit identity pool page
appears.
3. Scroll down and click Delete identity pool to expand it.
4. Click Delete identity pool.
5. Click Delete pool.
Warning
When you click the delete button, you will permanently delete your identity pool and all
the user data it contains. Deleting an identity pool will cause applications and other services
utilizing the identity pool to stop working.
184
Amazon Cognito Developer Guide
Delete an Identity from an Identity Pool
1. Click the name of the identity pool that contains the identity that you want to delete. The Dashboard
page for your identity pool appears.
2. In the left-hand navigation on the Dashboard page, click Identity browser. The Identities page
appears.
3. On the Identities page, enter the identity ID that you want to delete and then click Search.
4. On the Identity details page, click the Delete identity button, and then click Delete.
Managing Datasets
If you have implemented Amazon Cognito Sync functionality in your application, the Amazon Cognito
Identity Pools console enables you to manually create and delete datasets and records for individual
identities. Any change you make to an identity's dataset or records in the Amazon Cognito Identity Pools
console will not be saved until you click Synchronize in the console and will not be visible to the end
user until the identity calls synchronize. The data being synchronized from other devices for individual
identities will be visible once you refresh the list datasets page for a particular identity.
1. Click the name of the identity pool that contains the identity for which you want to create a dataset.
The Dashboard page for your identity pool appears.
2. In the left-hand navigation on the Dashboard page, click Identity browser. The Identities page
appears.
3. On the Identities page, enter the identity ID for which you want to create a dataset, and then click
Search.
4. On the Identity details page for that identity, click the Create dataset button, enter a dataset name,
and then click Create and edit dataset.
5. On the Current dataset page, click Create record to create a record to store in that dataset.
6. Enter a key for that dataset, the valid JSON value or values to store, and then click Format as JSON to
prettify the value you entered and to confirm that it is well-formed JSON. When finished, click Save
Changes.
7. Click Synchronize to synchronize the dataset. Your changes will not be saved until you click
Synchronize and will not be visible to the user until the identity calls synchronize. To discard
unsynchronized changes, select the change you wish to discard, and then click Discard changes.
1. Click the name of the identity pool that contains the identity for which you want to delete a dataset.
The Dashboard page for your identity pool appears.
2. In the left-hand navigation on the Dashboard page, click Identity browser. The Identities page
appears.
3. On the Identities page, enter the identity ID containing the dataset which you want to delete, and
then click Search.
185
Amazon Cognito Developer Guide
Bulk Publish Data
4. On the Identity details page, select the checkbox next to the dataset or datasets that you want to
delete, click Delete selected, and then click Delete.
You can enable Push Sync via the Amazon Cognito console. Choose Manage Identity Pools from the
Amazon Cognito console:
1. Click the name of the identity pool for which you want to enable Push Sync. The Dashboard page for
your identity pool appears.
2. In the top-right corner of the Dashboard page, click Edit identity pool. The Edit identity pool page
appears.
3. Scroll down and click Push synchronization to expand it.
4. In the Service role dropdown menu, select the IAM role that grants Amazon Cognito permission to
send an SNS notification. Click Create role to create or modify the roles associated with your identity
pool in the AWS IAM console.
5. Select a platform application, and then click Save Changes.
186
Amazon Cognito Developer Guide
Identity Pools Authentication Flow
credentials to access other AWS services. Amazon Cognito identity pools support public identity
providers—Amazon, Apple, Facebook, and Google—as well as unauthenticated identities. It also supports
developer authenticated identities, which let you register and authenticate users via your own back-end
authentication process.
For information about Amazon Cognito identity pools Region availability, see AWS Service Region
Availability. For more information about Amazon Cognito identity pools concepts, see the following
topics.
Topics
• Identity Pools (Federated Identities) Authentication Flow (p. 187)
• IAM Roles (p. 191)
• Role Trust and Permissions (p. 196)
A user authenticating with Amazon Cognito will go through a multi-step process to bootstrap their
credentials. Amazon Cognito has two different flows for authentication with public providers: enhanced
and basic.
Once you complete one of these flows, you can access other AWS services as defined by your role's access
policies. By default, the Amazon Cognito console will create roles with access to the Amazon Cognito
Sync store and to Amazon Mobile Analytics. For more information on how to grant additional access see
IAM Roles (p. 191).
1. GetId
2. GetCredentialsForIdentity
187
Amazon Cognito Developer Guide
Identity Pools Authentication Flow
1. GetId
2. GetOpenIdToken
3. AssumeRoleWithWebIdentity
When using Developer Authenticated Identities (Identity Pools) (p. 234), the client will use a
different authflow that will include code outside of Amazon Cognito to validate the user in your own
authentication system. Code outside of Amazon Cognito is indicated as such.
Enhanced Authflow
Basic Authflow
188
Amazon Cognito Developer Guide
Identity Pools Authentication Flow
For most customers, the Enhanced Flow is the correct choice, as it offers many benefits over the Basic
Flow:
Since February 2015, the Amazon Cognito console displayed example code that used the Enhanced
Flow. Additionally, the console will display a notification if your identity pool does not have the role
association necessary to use the Enhanced Flow.
The following are the minimum SDK versions where the Enhanced Flow is supported:
You may still wish to use the Basic Flow if you want to use more than the two default roles configured
when you create a new identity pool in the console.
API Summary
GetId
The GetId API call is the first call necessary to establish a new identity in Amazon Cognito.
Unauthenticated Access
189
Amazon Cognito Developer Guide
Identity Pools Authentication Flow
Amazon Cognito has the ability to allow unauthenticated guest access in your applications. If this feature
is enabled in your identity pool, users can request a new identity ID at any time via the GetId API. The
application is expected to cache this identity ID to make subsequent calls to Amazon Cognito. The AWS
Mobile SDKs as well as the AWS SDK for JavaScript in the Browser have credentials providers that handle
this caching for you.
Authenticated Access
When you've configured your application with support for a public login provider (Facebook, Google+,
Login with Amazon, or Sign in with Apple), users will also be able to supply tokens (OAuth or OpenID
Connect) that identify them in those providers. When used in a call to GetId, Amazon Cognito will either
create a new authenticated identity or return the identity already associated with that particular login.
Amazon Cognito does this by validating the token with the provider and ensuring that:
GetCredentialsForIdentity
The GetCredentialsForIdentity API can be called after you establish an identity ID. This API is functionally
equivalent to calling GetOpenIdToken followed by AssumeRoleWithWebIdentity.
In order for Amazon Cognito to call AssumeRoleWithWebIdentity on your behalf, your identity pool must
have IAM roles associated with it. You can do this via the Amazon Cognito Console or manually via the
SetIdentityPoolRoles operation (see the API reference)
GetOpenIdToken
The GetOpenIdToken API call is called after you establish an identity ID. If you have a cached identity ID,
this can be the first call you make during an app session.
Unauthenticated Access
To obtain a token for an unauthenticated identity, you only need the identity ID itself. It is not possible to
get an unauthenticated token for authenticated or disabled identities.
Authenticated Access
If you have an authenticated identity, you must pass at least one valid token for a login already
associated with that identity. All tokens passed in during the GetOpenIdToken call must pass the
same validation mentioned earlier; if any of the tokens fail, the whole call fails. The response from the
GetOpenIdToken call also includes the identity ID. This is because the identity ID you pass in may not be
the one that is returned.
Linking Logins
If you pass in a token for a login that is not already associated with any identity, the login is considered
to be "linked" to the associated identity. You may only link one login per public provider. Attempts to link
more than one login with a public provider will result in a ResourceConflictException. If a login is merely
linked to an existing identity, the identity ID returned from GetOpenIdToken will be the same as what
was passed in.
Merging Identities
If you pass in a token for a login that is not currently linked to the given identity, but is linked to another
identity, the two identities are merged. Once merged, one identity becomes the parent/owner of all
190
Amazon Cognito Developer Guide
IAM Roles
associated logins and the other is disabled. In this case, the identity ID of the parent/owner is returned.
You are expected to update your local cache if this value differs (this is handled for you if you are using
the providers in the AWS Mobile SDKs or AWS SDK for JavaScript in the Browser).
GetOpenIdTokenForDeveloperIdentity
The GetOpenIdTokenForDeveloperIdentity API replaces the use of GetId and GetOpenIdToken from
the device when using developer authenticated identities. Because this API call is signed by your AWS
credentials, Amazon Cognito can trust that the user identifier supplied in the API call is valid. This
replaces the token validation Amazon Cognito performs with external providers.
The payload for this API includes a logins map which must contain the key of your developer provider
and a value as an identifier for the user in your system. If the user identifier isn't already linked to an
existing identity, Amazon Cognito will create a new identity and return the new identity id and an
OpenId Connect token for that identity. If the user identifier is already linked, Amazon Cognito will
return the pre-existing identity id and an OpenId Connect token.
Linking Logins
As with external providers, supplying additional logins that are not already associated with an identity
will implicitly link those logins to that identity. It is important to note that if you link an external provider
login to an identity, the user can use the external provider authflow with that provider, but they cannot
use your developer provider name in the logins map when calling GetId or GetOpenIdToken.
Merging Identities
With developer authenticated identities, Amazon Cognito supports both implicit merging as well as
explicit merging via the MergeDeveloperIdentities API. This explicit merging allows you to mark two
identities with user identifiers in your system as a single identity. You simply supply the source and
destination user identifiers and Amazon Cognito will merge them. The next time you request an OpenId
Connect token for either user identifier, the same identity id will be returned.
AssumeRoleWithWebIdentity
Once you have an OpenID Connect token, you can then trade this for temporary AWS credentials via the
AssumeRoleWithWebIdentity API call in AWS Security Token Service (STS). This call is no different than
if you were using Facebook, Google+, Login with Amazon, or Sign in with Apple directly, except that you
are passing an Amazon Cognito token instead of a token from one of the other public providers.
Because there's no restriction on the number of identities that can be created, it's important to
understand the permissions that are being granted to your users. We recommend having two different
roles for your application: one for unauthenticated users, and one for authenticated users. The Amazon
Cognito console will create these for you by default when you first set up your identity pool. The access
policy for these two roles will be exactly the same: it will grant users access to Amazon Cognito Sync as
well as to submit events to Amazon Mobile Analytics. You are welcome and encouraged to modify these
roles to meet your needs.
IAM Roles
In the process of creating an identity pool, you'll be prompted to update the IAM roles that your users
assume. IAM roles work like this: When a user logs in to your app, Amazon Cognito generates temporary
AWS credentials for the user. These temporary credentials are associated with a specific IAM role. The
IAM role lets you define a set of permissions to access your AWS resources.
You can specify default IAM roles for authenticated and unauthenticated users. In addition, you can
define rules to choose the role for each user based on claims in the user's ID token. For more information,
see Role-Based Access Control (p. 201).
191
Amazon Cognito Developer Guide
IAM Roles
By default, the Amazon Cognito Console creates IAM roles that provide access to Amazon Mobile
Analytics and to Amazon Cognito Sync. Alternatively, you can choose to use existing IAM roles.
To modify IAM roles, thereby allowing or restricting access to other services, log in to the IAM Console.
Then click Roles and select a role. The policies attached to the selected role are listed in the Permissions
tab. You can customize an access policy by clicking the corresponding Manage Policy link. To learn more
about using and defining policies, see Overview of IAM Policies.
Note
As a best practice, define policies that follow the principle of granting least privilege. In other
words, the policies include only the permissions that users require to perform their tasks. For
more information, see Grant Least Privilege in the IAM User Guide.
Remember that unauthenticated identities are assumed by users who do not log in to your
app. Typically, the permissions that you assign for unauthenticated identities should be more
restrictive than those for authenticated identities.
Topics
• Set Up a Trust Policy (p. 192)
• Access Policies (p. 193)
To reuse a role across multiple identity pools, because they share a common permission set, you can
include multiple identity pools, like this:
"StringEquals": {
"cognito-identity.amazonaws.com:aud": [
"us-east-1:12345678-abcd-abcd-abcd-123456790ab",
"us-east-1:98765432-dcba-dcba-dcba-123456790ab"
]
}
To create a policy limited to a specific set of app users, check the value of cognito-
identity.amazonaws.com:sub:
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "us-east-1:12345678-abcd-abcd-abcd-123456790ab",
"cognito-identity.amazonaws.com:sub": [
"us-east-1:12345678-1234-1234-1234-123456790ab",
"us-east-1:98765432-1234-1234-1243-123456790ab"
]
}
To create a policy limited to users who have logged in with a specific provider (perhaps your own login
provider), check the value of cognito-identity.amazonaws.com:amr:
"ForAnyValue:StringLike": {
192
Amazon Cognito Developer Guide
IAM Roles
"cognito-identity.amazonaws.com:amr": "login.myprovider.myapp"
}
For example, an app that trusts only Facebook would have the following amr clause:
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "graph.facebook.com"
}
Access Policies
The permissions attached to a role are effective across all users that assume that role. If you want to
partition your users' access, you can do so via policy variables. Be careful when including your users'
identity IDs in your access policies, particularly for unauthenticated identities as these may change if the
user chooses to login.
For additional security protection, Amazon Cognito applies a scope-down policy to credentials vended by
GetCredentialForIdentity to prevent access to services other than the ones listed below for your
unauthenticated users. In other words, this policy allows an identity using these credentials with access
to only the following services:
If you need access to something other than these services for your unauthenticated users, you must use
the basic authentication flow. If you are getting NotAuthorizedException and you have enabled
access to the service in your unauthenticated role policy, this is likely the reason.
The following access policy grants read permissions to an identity to retrieve a single object from a given
S3 bucket.
193
Amazon Cognito Developer Guide
IAM Roles
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": ["arn:aws:s3:::mybucket/assets/my_picture.jpg"]
}
]
}
Example 2: Allow an Identity to Have Both Read and Write Access to Identity Specific Paths in S3
The following access policy grants read and write permissions to access a specific prefix "folder" in an S3
bucket by mapping the prefix to the ${cognito-identity.amazonaws.com:sub} variable.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": ["s3:ListBucket"],
"Effect": "Allow",
"Resource": ["arn:aws:s3:::mybucket"],
"Condition": {"StringLike": {"s3:prefix": ["${cognito-identity.amazonaws.com:sub}/
*"]}}
},
{
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Effect": "Allow",
"Resource": ["arn:aws:s3:::mybucket/${cognito-identity.amazonaws.com:sub}/*"]
}
]
}
The following access policy provides fine-grained access control to Amazon DynamoDB resources using
Amazon Cognito variables that grant access to items in DynamoDB by identity ID. For more information,
see Using IAM Policy Conditions for Fine-Grained Access Control in the Amazon DynamoDB Developer
Guide.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:BatchGetItem",
"dynamodb:Query",
"dynamodb:PutItem",
194
Amazon Cognito Developer Guide
IAM Roles
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:BatchWriteItem"
],
"Resource": [
"arn:aws:dynamodb:us-west-2:123456789012:table/MyTable"
],
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": ["${cognito-identity.amazonaws.com:sub}"]
}
}
}
]
}
The following access policy grants an identity permissions to execute an AWS Lambda function.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": [
"arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
]
}
]
}
The following access policy allows an identity to use the PutRecord operation with any of the Kinesis
Data Streams. It can be applied to users that need to add data records to all streams in an account. For
more information, see Controlling Access to Amazon Kinesis Data Streams Resources Using IAM in the
Amazon Kinesis Data Streams Developer Guide.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "kinesis:PutRecord",
"Resource": [
"arn:aws:kinesis:us-east-1:111122223333:stream/stream1"
]
}
]
}
Example 6: Allow an Identity Access to Their Data in the Amazon Cognito Sync store
The following access policy grants an identity permissions to only their data in the Amazon Cognito Sync
store.
{
"Version": "2012-10-17",
195
Amazon Cognito Developer Guide
Role Trust and Permissions
"Statement":[{
"Effect":"Allow",
"Action":"cognito-sync:*",
"Resource":["arn:aws:cognito-sync:us-east-1:123456789012:identitypool/${cognito-
identity.amazonaws.com:aud}/identity/${cognito-identity.amazonaws.com:sub}/*"]
}]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "us-east-1:12345678-corner-
cafe-123456790ab"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "unauthenticated"
}
}
}
]
}
This policy defines that we want to allow federated users from cognito-identity.amazonaws.com
(the issuer of the OpenID Connect token) to assume this role. Additionally, we make the restriction that
the aud of the token, in our case the identity pool ID, matches our identity pool. Finally, we specify that
the amr of the token contains the value unauthenticated.
When Amazon Cognito creates a token, it will set the amr of the token to be either "unauthenticated" or
"authenticated" and in the authenticated case will include any providers used during authentication. This
means you can create a role that trusts only users that logged in via Facebook, simply by changing the
amr clause to look like the following:
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "graph.facebook.com"
}
Be careful when changing your trust relationships on your roles, or when trying to use roles across
identity pools. If your role is not configured to correctly trust your identity pool, you will see an exception
from STS like the following:
If you see this, double check that you are using an appropriate role for your identity pool and
authentication type.
196
Amazon Cognito Developer Guide
Using attributes for access control
You can choose default mappings or create your own custom mappings in Amazon Cognito identity
pools. The default mappings allow you to write IAM policies based on a fixed set of user attributes.
Custom mappings allow you to select a custom set of user attributes that are referenced in the IAM
permissions policies. The Attribute names in the Amazon Cognito console are mapped to Tag key for
principal, which are the tags that are referenced in the IAM permissions policy.
For example, let's say that you own a media streaming service with a free and paid membership. You
store the media files in Amazon S3 and tag them with free or premium tags. You can use attributes for
access control to allow access to free and paid content based on user membership level, which is part
of user's profile. You can map the membership attribute to a tag key for principal to be passed on to
the IAM permissions policy. This way you can create a single permissions policy and conditionally allow
access to premium content based on the value of membership level and tag on the content files.
Topics
• Using attributes for access control with Amazon Cognito identity pools (p. 197)
• Using attributes for access control policy example (p. 198)
• Disable attributes for access control (console) (p. 200)
• Default provider mappings (p. 200)
• Permissions management is easier when you use attributes for access control. You can create a basic
permissions policy that uses user attributes instead of creating multiple policies for different job
functions.
• You don't need to update your policies whenever you add or remove resources or users for your
application. The permissions policy will only grant the access to users with the matching user
attributes. For example, you might need to control the access to certain S3 buckets based on the job
title of users. In that case, you can create a permissions policy to allow access to these files only for
users within the defined job title. For more information, see IAM Tutorial: Use SAML session tags for
ABAC.
• Attributes can be passed as principal tags to a policy that allows or denies permissions based on the
values of those attributes.
• An AWS account
• User pool
• Identity pool
• The mobile or JavaScript SDK
197
Amazon Cognito Developer Guide
Using attributes for access control policy example
To use attributes for access control you have to configure Tag Key for Principal and Attribute name. In
Tag Key for Principal the value is used to match the PrincipalTag condition in the permissions policies.
The value in Attribute name is the name of the attribute whose value will be evaluated in the policy.
1. In Tag Key for Principal, enter your custom text. There is a maximum length of 128 characters.
2. In Attribute name, enter the attribute names from your providers tokens or SAML assertions. You
can get your attribute names for your IdPs from your providers developer guide. Attribute names
have a maximum of 256 characters. In addition, the aggregated character limit for all attributes is
460 bytes.
3. (Optional) Add another provider. You can add multiple providers for Amazon Cognito user pools,
OIDC, and SAML providers in the console. For example, you can add two Amazon Cognito user
pools as two separate identity providers. Amazon Cognito treats each tab as different IdPs. You
can configure attributes for access control separately for each IdP.
4. To finish, use the IAM console to create a permissions policy that includes the default mappings or
the custom text mappings that you provided in Tag Key for Principal. For a tutorial on creating a
permissions policy in IAM, see IAM tutorial: Define permissions to access AWS resources based on
tags in the IAM User Guide.
Claims
{ .
.
"sub" : "57e7b692-4f66-480d-98b8-45a6729b4c88",
"department" : "legal",
"clearance" : "confidential",
.
.
}
198
Amazon Cognito Developer Guide
Using attributes for access control policy example
These attributes can be mapped to tags and referenced in IAM permissions policies as principal tags. You
can now manage access by changing the user profile on the identity provider's end. Alternatively, you can
change attributes on the resource side by using names or tags without changing the policy itself.
• Allows list access to all s3 buckets that end with a prefix that matches the user’s department name.
• Allows read access on files in these buckets as long as the clearance tag on the file matches user’s
clearance attribute.
Permissions policy
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:List*",
"Resource": "arn:aws:s3:::*-${aws:PrincipalTag/department}"
},
{
"Effect": "Allow",
"Action": "s3:GetObject*",
"Resource": "arn:aws:s3:::*-${aws:PrincipalTag/department}/*",
"Condition": {
"StringEquals": {
"s3:ExistingObjectTag/clearance": "${aws:PrincipalTag/clearance}"
}
}
}
]
}
The trust policy determines who can assume this role. The trust relationship policy allows the use of
sts:AssumeRoleWithWebIdentity and sts:TagSession to allow access. It adds conditions to
restrict the policy to the identity pool that you created and it ensures that it’s for an authenticated role.
Trust policy
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com"
},
"Action": [
"sts:AssumeRoleWithWebIdentity",
"sts:TagSession"
],
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "IDENTITY-POOL-ID"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "authenticated"
}
199
Amazon Cognito Developer Guide
Disable attributes for access control
}
}
]
}
200
Amazon Cognito Developer Guide
Role-Based Access Control
Standard OIDC ID and access tokens aud (as client_id), sub "620493171733-
providers (as user ID) eebk7c0hcp5lj3e1tlqp1gntt3k0rncv.ap
"109220063452404746097"
Note
The default attribute mappings option is automatically populated for the Tag Key for Principal
and Attribute names. You can't change default mappings.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "us-east-1:12345678-corner-
cafe-123456790ab"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "authenticated"
}
}
}
]
}
This policy allows federated users from cognito-identity.amazonaws.com (the issuer of the OpenID
Connect token) to assume this role. Additionally, the policy restricts the aud of the token, in this case
the identity pool ID, to match the identity pool. Finally, the policy specifies that the amr of the token
contains the value authenticated.
201
Amazon Cognito Developer Guide
Granting Pass Role Permission
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1",
"Effect": "Allow",
"Action": [
"iam:PassRole"
],
"Resource": [
"arn:aws:iam::123456789012:role/myS3WriteAccessRole"
]
}
]
}
In this policy example, the iam:PassRole permission is granted for the myS3WriteAccessRole role.
The role is specified using the role's ARN. You must also attach this policy to your IAM user or role to
which your user belongs. For more information, see Working with Managed Policies.
Note
Lambda functions use resource-based policy, where the policy is attached directly to the
Lambda function itself. When creating a rule that invokes a Lambda function, you do not pass
a role, so the user creating the rule does not need the iam:PassRole permission. For more
information about Lambda function authorization, see Manage Permissions: Using a Lambda
Function Policy.
• The cognito:preferred_role claim is set to the role from the group with the best (lowest)
Precedence value. If there is only one allowed role, cognito:preferred_role is set to that role. If
there are multiple roles and no single role has the best precedence, this claim is not set.
• The cognito:roles claim is set if there is at least one role.
When using tokens to assign roles, if there are multiple roles that can be assigned to the user, Amazon
Cognito identity pools (federated identities) chooses the role as follows:
• Use the GetCredentialsForIdentity CustomRoleArn parameter if it is set and it matches a role in the
cognito:roles claim. If this parameter doesn't match a role in cognito:roles, deny access.
202
Amazon Cognito Developer Guide
Using Rule-Based Mapping to Assign Roles to Users
Each rule specifies a token claim (such as a user attribute in the ID token from an Amazon Cognito user
pool), match type, a value, and an IAM role. The match type can be Equals, NotEqual, StartsWith,
or Contains. If a user has a matching value for the claim, the user can assume that role when the user
gets credentials. For example, you can create a rule that assigns a specific IAM role for users with a
custom:dept custom attribute value of Sales.
Note
In the rule settings, custom attributes require the custom: prefix to distinguish them from
standard attributes.
Rules are evaluated in order, and the IAM role for the first matching rule is used, unless CustomRoleArn
is specified to override the order. For more information about user attributes in Amazon Cognito user
pools, see Configuring User Pool Attributes (p. 157).
You can set multiple rules for an authentication provider in the identity pool (federated identities)
console. Rules are applied in order. You can drag the rules to change their order. The first matching rule
takes precedence. If the match type is NotEqual and the claim doesn't exist, the rule is not evaluated. If
no rules match, the Role resolution setting is applied to either Use default Authenticated role or DENY.
In the API and CLI, you can specify the role to be assigned when no rules match in the
AmbiguousRoleResolution field of the RoleMapping type, which is specified in the RoleMappings
parameter of the SetIdentityPoolRoles API.
For each user pool or other authentication provider configured for an identity pool, you can create up to
25 rules. If you need more than 25 rules for a provider, please open a Service Limit Increase support case.
An Amazon Cognito ID token is represented as a JSON Web Token (JWT). The token contains claims
about the identity of the authenticated user, such as name, family_name, and phone_number. For
more information about standard claims, see the OpenID Connect specification. Apart from standard
claims, the following are the additional claims specific to Amazon Cognito:
• cognito:groups
• cognito:roles
• cognito:preferred_role
Amazon
The following claims, along with possible values for those claims, can be used with Login with Amazon:
• iss: www.amazon.com
• aud: App Id
203
Amazon Cognito Developer Guide
Best Practices for Role-Based Access Control
The following claims, along with possible values for those claims, can be used with Facebook:
• iss: graph.facebook.com
• aud: App Id
• sub: sub from the Facebook token
A Google token contains standard claims from the OpenID Connect specification. All of the claims in the
OpenID token are available for rule-based mapping. See Google's OpenID Connect site to learn about the
claims available from the Google token.
Apple
An Apple token contains standard claims from the OpenID Connect specification. See Authenticating
Users with Sign in with Apple in Apple’s documentation to learn more about the claim available from the
Apple token. Apple's token doesn’t always contain email.
OpenID
All of the claims in the Open Id token are available for rule-based mapping. For more information about
standard claims, see the OpenID Connect specification. Refer to your OpenID provider documentation to
learn about any additional claims that are available.
SAML
Claims are parsed from the received SAML assertion. All the claims that are available in the SAML
assertion can be used in rule-based mapping.
Getting Credentials
You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application,
so that your users can access AWS resources. This section describes how to get credentials and how to
retrieve an Amazon Cognito identity from an identity pool.
204
Amazon Cognito Developer Guide
Android
Amazon Cognito supports both authenticated and unauthenticated identities. Unauthenticated users do
not have their identity verified, making this role appropriate for guest users of your app or in cases when
it doesn't matter if users have their identities verified. Authenticated users log in to your application
through a third-party identity provider, or a user pool, that verifies their identities. Make sure you scope
the permissions of resources appropriately so you don't grant access to them from unauthenticated
users.
Amazon Cognito identities are not credentials. They are exchanged for credentials using web identity
federation support in the AWS Security Token Service (AWS STS). The recommended way to obtain
AWS credentials for your app users is to use AWS.CognitoIdentityCredentials. The identity in the
credentials object is then exchanged for credentials using AWS STS.
Note
If you created your identity pool before February 2015, you will need to reassociate your roles
with your identity pool in order to use the AWS.CognitoIdentityCredentials constructor
without the roles as parameters. To do so, open the Amazon Cognito console, choose Manage
Identity Pools, select your identity pool, choose Edit Identity Pool, specify your authenticated
and unauthenticated roles, and save the changes.
Android
You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application,
so that your users can access AWS resources. Amazon Cognito supports both authenticated and
unauthenticated identities. To provide AWS credentials to your app, follow the steps below.
1. Choose Manage Identity Pools from the Amazon Cognito console, create an identity pool, and copy
the starter code snippets.
2. If you haven't already done so, add the AWS Mobile SDK for Android to your project. For instructions,
see Set Up the Mobile SDK for Android.
3. Include the following import statements:
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.regions.Regions;
4. Initialize the Amazon Cognito credentials provider using the code snippet generated by the Amazon
Cognito console. The value for IDENTITY_POOL_ID will be specific to your account:
5. Pass the initialized Amazon Cognito credentials provider to the constructor of the AWS client to be
used. The code required depends on the service to be initialized. The client will use this provider to get
credentials with which it will access AWS resources.
Note
If you created your identity pool before February 2015, you will need to reassociate your roles
with your identity pool in order to use this constructor without the roles as parameters. To
do so, open the Amazon Cognito console, choose Manage Federated Identies, select your
identity pool, and choose Edit Identity Pool, specify your authenticated and unauthenticated
roles, and save the changes.
205
Amazon Cognito Developer Guide
iOS - Objective-C
If you're allowing unauthenticated users, you can retrieve a unique Amazon Cognito identifier (identity
ID) for your end user immediately. If you're authenticating users, you can retrieve the identity ID after
you've set the login tokens in the credentials provider:
Note
Do not call getIdentityId(), refresh(), or getCredentials() in the main thread
of your application. As of Android 3.0 (API Level 11), your app will automatically fail and
throw a NetworkOnMainThreadException if you perform network I/O on the main application
thread. You will need to move your code to a background thread using AsyncTask. For more
information, consult the Android documentation. You can also call getCachedIdentityId()
to retrieve an ID, but only if one is already cached locally. Otherwise, the method will return null.
iOS - Objective-C
You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application, so
that your users can access AWS resources. Amazon Cognito identity pools support both authenticated
and unauthenticated identities. To provide AWS credentials to your app, follow the steps below.
1. Choose Manage Identity Pools from the Amazon Cognito console, create an identity pool, and copy
the starter code snippets.
2. If you haven't already done so, add the AWS Mobile SDK for iOS to your project. For instructions, see
Set Up the Mobile SDK for iOS.
3. In your source code, include the AWSCore header:
#import <AWSCore/AWSCore.h>
4. Initialize the Amazon Cognito credentials provider using the code snippet generated by the Amazon
Cognito console. The value for IDENTITY_POOL_ID will be specific to your account:
Note
If you created your identity pool before February 2015, you will need to reassociate
your roles with your identity pool in order to use this constructor without the roles as
parameters. To do so, open the Amazon Cognito console, choose Manage Identity Pools,
select your identity pool, choose Edit Identity Pool, specify your authenticated and
unauthenticated roles, and save the changes.
You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately if you're
allowing unauthenticated users or after you've set the login tokens in the credentials provider if you're
authenticating users:
206
Amazon Cognito Developer Guide
iOS - Swift
Note
getIdentityId is an asynchronous call. If an identity ID is already set on your
provider, you can call credentialsProvider.identityId to retrieve that identity,
which is cached locally. However, if an identity ID is not set on your provider, calling
credentialsProvider.identityId will return nil. For more information, consult the
Mobile SDK for iOS API Reference.
iOS - Swift
You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application,
so that your users can access AWS resources. Amazon Cognito supports both authenticated and
unauthenticated identities. To provide AWS credentials to your app, follow the steps below.
1. Choose Manage Identity Pools from the Amazon Cognito console, create an identity pool, and copy
the starter code snippets.
2. If you haven't already done so, add the Mobile SDK for iOS to your project. For instructions, see Set
Up the SDK for iOS.
3. In your source code, include the AWSCore header:
import AWSCore
4. Initialize the Amazon Cognito credentials provider using the code snippet generated by the Amazon
Cognito console. The value for IDENTITY_POOL_ID will be specific to your account:
Note
If you created your identity pool before February 2015, you will need to reassociate
your roles with your identity pool in order to use this constructor without the roles as
parameters. To do so, open the Amazon Cognito console, choose Manage Identity Pools,
select your identity pool, choose Edit Identity Pool, specify your authenticated and
unauthenticated roles, and save the changes.
You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately if you're
allowing unauthenticated users or after you've set the login tokens in the credentials provider if you're
authenticating users:
207
Amazon Cognito Developer Guide
JavaScript
}
else {
// the task result will contain the identity id
let cognitoId = task.result!
print("Cognito id: \(cognitoId)")
}
return task;
})
Note
getIdentityId is an asynchronous call. If an identity ID is already set on your
provider, you can call credentialsProvider.identityId to retrieve that identity,
which is cached locally. However, if an identity ID is not set on your provider, calling
credentialsProvider.identityId will return nil. For more information, consult the
Mobile SDK for iOS API Reference.
JavaScript
If you have not yet created one, create an identity pool in the Amazon Cognito console before using
AWS.CognitoIdentityCredentials.
After you configure an identity pool with your identity providers, you can use
AWS.CognitoIdentityCredentials to authenticate users. To configure your application credentials
to use AWS.CognitoIdentityCredentials, set the credentials property of either AWS.Config or
a per-service configuration. The following example uses AWS.Config:
// Set the region where your identity pool exists (us-east-1, eu-west-1)
AWS.config.region = 'us-east-1';
});
The optional Logins property is a map of identity provider names to the identity tokens for those
providers. How you get the token from your identity provider depends on the provider you use. For
example, if Facebook is one of your identity providers, you might use the FB.login function from the
Facebook SDK to get an identity provider token:
FB.login(function (response) {
if (response.authResponse) { // logged in
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030',
Logins: {
208
Amazon Cognito Developer Guide
Unity
'graph.facebook.com': response.authResponse.accessToken
}
});
You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately if you're
allowing unauthenticated users or after you've set the login tokens in the credentials provider if you're
authenticating users:
Unity
You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application,
so that your users can access AWS resources. Amazon Cognito supports both authenticated and
unauthenticated identities. To provide AWS credentials to your app, follow the steps below.
1. Choose Manage Identity Pools, from the Amazon Cognito console, create an identity pool, and copy
the starter code snippets.
2. If you haven't already done so, download and import the AWS Mobile SDK for Unity package into your
project. You can do so from the menu Assets > Import Package > Custom Package.
3. Paste the starter code snippet from the Console into the script you want to call Amazon Cognito from.
The value for IDENTITY_POOL_ID will be specific to your account:
4. Pass the initialized Amazon Cognito credentials to the constructor of the AWS client to be used.
The code required depends on the service to be initialized. The client will use this provider to get
credentials with which it will access AWS resources.
Note
If you created your identity pool before February 2015, you will need to reassociate your roles
with your identity pool in order to use this constructor without the roles as parameters. To
do so, open the Amazon Cognito console, choose Manage Identity Pools, select your identity
pool, choose Edit Identity Pool, specify your authenticated and unauthenticated roles, and
save the changes.
You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately if you're
allowing unauthenticated users or after you've set the login tokens in the credentials provider if you're
authenticating users:
credentials.GetIdentityIdAsync(delegate(AmazonCognitoIdentityResult<string> result) {
if (result.Exception != null) {
//Exception!
209
Amazon Cognito Developer Guide
Xamarin
}
string identityId = result.Response;
});
Xamarin
You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application,
so that your users can access AWS resources. Amazon Cognito supports both authenticated and
unauthenticated identities. To provide AWS credentials to your app, follow the steps below.
1. Choose Manage Identity Pools, from the Amazon Cognito console, create an identity pool, and copy
the starter code snippets.
2. If you haven't already done so, add the AWS Mobile SDK for Xamarin to your project. For instructions,
see Set Up the SDK for Xamarin.
3. Include the following using statements:
using Amazon.CognitoIdentity;
4. Paste the starter code snippet from the Console into the script you want to call Amazon Cognito from.
The value for IDENTITY_POOL_ID will be specific to your account:
5. Pass the initialized Amazon Cognito credentials to the constructor of the AWS client to be used.
The code required depends on the service to be initialized. The client will use this provider to get
credentials with which it will access AWS resources.
Note
Note: If you created your identity pool before February 2015, you will need to reassociate your
roles with your identity pool in order to use this constructor without the roles as parameters. To
do so, open the Amazon Cognito console, choose Manage Identity Pools, select your identity
pool, choose Edit Identity Pool, specify your authenticated and unauthenticated roles, and save
the changes.
You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately if you're
allowing unauthenticated users or after you've set the login tokens in the credentials provider if you're
authenticating users:
Android
210
Amazon Cognito Developer Guide
iOS - Objective-C
The credentials provider communicates with Amazon Cognito, retrieving both the unique identifier for
authenticated and unauthenticated users as well as temporary, limited privilege AWS credentials for the
AWS Mobile SDK. The retrieved credentials are valid for one hour, and the provider refreshes them when
they expire.
iOS - Objective-C
// create a configuration that uses the provider
AWSServiceConfiguration *configuration = [AWSServiceConfiguration
configurationWithRegion:AWSRegionUSEast1 provider:credentialsProvider];
The credentials provider communicates with Amazon Cognito, retrieving both the unique identifier for
authenticated and unauthenticated users as well as temporary, limited privilege AWS credentials for the
AWS Mobile SDK. The retrieved credentials are valid for one hour, and the provider refreshes them when
they expire.
iOS - Swift
// get a client with the default service configuration
let dynamoDB = AWSDynamoDB.default()
The credentials provider communicates with Amazon Cognito, retrieving both the unique identifier for
authenticated and unauthenticated users as well as temporary, limited privilege AWS credentials for the
AWS Mobile SDK. The retrieved credentials are valid for one hour, and the provider refreshes them when
they expire.
JavaScript
The credentials provider communicates with Amazon Cognito, retrieving both the unique identifier for
authenticated and unauthenticated users as well as temporary, limited privilege AWS credentials for the
AWS Mobile SDK. The retrieved credentials are valid for one hour, and the provider refreshes them when
they expire.
Unity
211
Amazon Cognito Developer Guide
Xamarin
The credentials provider communicates with Amazon Cognito, retrieving both the unique identifier for
authenticated and unauthenticated users as well as temporary, limited privilege AWS credentials for the
AWS Mobile SDK. The retrieved credentials are valid for one hour, and the provider refreshes them when
they expire.
Xamarin
The credentials provider communicates with Amazon Cognito, retrieving both the unique identifier for
authenticated and unauthenticated users as well as temporary, limited privilege AWS credentials for the
AWS Mobile SDK. The retrieved credentials are valid for one hour, and the provider refreshes them when
they expire.
The instructions below guide you through authentication with the identity providers supported by
Amazon Cognito identity pools.
Topics
• Facebook (Identity Pools) (p. 212)
• Login with Amazon (Identity Pools) (p. 217)
• Google (Identity Pools) (p. 220)
• Sign in with Apple (Identity Pools) (p. 227)
• Open ID Connect Providers (Identity Pools) (p. 231)
• SAML Identity Providers (Identity Pools) (p. 233)
Set Up Facebook
You need to register your application with Facebook before you can start authenticating Facebook users
and interacting with Facebook APIs.
The Facebook Developers portal takes you through the process of setting up your application. If you
haven't gone through that process yet, you must to do so before you can integrate Facebook in your
Amazon Cognito identity pool:
212
Amazon Cognito Developer Guide
Facebook
To set up Facebook
Android
The Facebook Getting Started Guide provides additional information on integrating with Facebook
Login.
iOS - Objective-C
The Facebook Getting Started Guide provides additional information about integrating with Facebook
Login.
iOS - Swift
The Facebook Getting Started Guide provides additional information about integrating with Facebook
Login.
JavaScript
The Facebook Getting Started Guide provides additional information about integrating with Facebook
Login.
Unity
The Facebook Getting Started Guide provides additional information about integrating with Facebook
Login.
Xamarin
To provide Facebook authentication, first follow the appropriate flow below to include and set up the
Facebook SDK in your application. Amazon Cognito identity pools use the Facebook access token to
generate a unique user identifier that is associated with an Amazon Cognito identity.
1. Choose Manage Identity Pools from the Amazon Cognito console home page.
2. Choose the name of the identity pool for which you want to enable Facebook as an external
provider. The Dashboard page for your identity pool appears.
3. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool
page appears.
4. Scroll down and choose Authentication providers to expand it.
5. Choose the Facebook tab.
6. Choose Unlock.
7. Enter the Facebook App ID you obtained from Facebook, and then choose Save Changes.
213
Amazon Cognito Developer Guide
Facebook
Using Facebook
Android
To provide Facebook authentication, first follow the Facebook guide to include their SDK in your
application. Then add a "Login with Facebook" button to your Android user interface. The Facebook SDK
uses a session object to track its state. Amazon Cognito uses the access token from this session object to
authenticate the user, generate the unique identifier, and, if needed, grant the user access to other AWS
resources.
Once you have authenticated your user with the Facebook SDK, add the session token to the Amazon
Cognito credentials provider.
The Facebook login process initializes a singleton session in its SDK. The Facebook session object
contains an OAuth token that Amazon Cognito uses to generate AWS credentials for your authenticated
end user. Amazon Cognito also uses the token to check against your user database for the existence of
a user matching this particular Facebook identity. If the user already exists, the API returns the existing
identifier. Otherwise a new identifier is returned. Identifiers are automatically cached by the client SDK
on the local device.
Note
After setting the logins map, you must make a call to refresh or get to actually get the AWS
credentials.
iOS - Objective-C
To add Facebook authentication, first follow the Facebook guide to integrate the Facebook SDK into
your application. Then add a Login with Facebook button to your user interface. The Facebook SDK uses
a session object to track its state. Amazon Cognito uses the access token from this session object to
authenticate the user and bind them to a unique Amazon Cognito identity pools (federated identities).
To provide the Facebook access token to Amazon Cognito, implement the AWSIdentityProviderManager
protocol.
214
Amazon Cognito Developer Guide
Facebook
userInfo:@{@"error":@"No current
Facebook access token"}]];
}
}
When you instantiate the AWSCognitoCredentialsProvider, pass the class that implements
AWSIdentityProviderManager as the value of identityProviderManager in the constructor.
For more information, go to the AWSCognitoCredentialsProvider reference page and choose
initWithRegionType:identityPoolId:identityProviderManager.
iOS - Swift
To add Facebook authentication, first follow the Facebook guide to integrate the Facebook SDK into
your application. Then add a Login with Facebook button to your user interface. The Facebook SDK uses
a session object to track its state. Amazon Cognito uses the access token from this session object to
authenticate the user and bind them to a unique Amazon Cognito identity pools (federated identities).
To provide the Facebook access token to Amazon Cognito, implement the AWSIdentityProviderManager
protocol.
When you instantiate the AWSCognitoCredentialsProvider, pass the class that implements
AWSIdentityProviderManager as the value of identityProviderManager in the constructor.
For more information, go to the AWSCognitoCredentialsProvider reference page and choose
initWithRegionType:identityPoolId:identityProviderManager.
JavaScript
To provide Facebook authentication, follow the Facebook Login for the Web to add the "Login with
Facebook" button on your website. The Facebook SDK uses a session object to track its state. Amazon
Cognito uses the access token from this session object to authenticate the user, generate the unique
identifier, and, if needed, grant the user access to other AWS resources.
Once you have authenticated your user with the Facebook SDK, add the session token to the Amazon
Cognito credentials provider.
FB.login(function (response) {
// Add the Facebook access token to the Amazon Cognito credentials login map.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'IDENTITY_POOL_ID',
215
Amazon Cognito Developer Guide
Facebook
Logins: {
'graph.facebook.com': response.authResponse.accessToken
}
});
} else {
console.log('There was a problem logging you in.');
}
});
The Facebook SDK obtains an OAuth token that Amazon Cognito uses to generate AWS credentials for
your authenticated end user. Amazon Cognito also uses the token to check against your user database
for the existence of a user matching this particular Facebook identity. If the user already exists, the API
returns the existing identifier. Otherwise a new identifier is returned. Identifiers are automatically cached
by the client SDK on the local device.
Note
After setting the logins map, you must make a call to refresh or get to get the credentials.
For a code example, see "Use Case 17, Integrating User Pools with Cognito Identity," in the
JavaScript README file.
Unity
To provide Facebook authentication, first follow the Facebook guide to include and set up their SDK in
your application. Amazon Cognito uses the Facebook access token from the 'FB' object to generate a
unique user identifier that is associated with an Amazon Cognito identity.
Once you have authenticated your user with the Facebook SDK, add the session token to the Amazon
Cognito credentials provider:
void Start()
{
FB.Init(delegate() {
if (FB.IsLoggedIn) { //User already logged in from a previous session
AddFacebookTokenToCognito();
} else {
FB.Login ("email", FacebookLoginCallback);
}
});
}
void AddFacebookTokenToCognito()
{
credentials.AddLogin ("graph.facebook.com",
AccessToken.CurrentAccessToken.TokenString);
216
Amazon Cognito Developer Guide
Login with Amazon
You should make sure to call FB.Login() and that FB.IsLoggedIn is true before using
FB.AccessToken.
Xamarin
Xamarin for Android:
There are two ways to set up Login with Amazon to work with Amazon Cognito. If you're not sure which
one to use, or if you need to use both, see "Setting Up Login with Amazon" in the Login with Amazon
FAQ.
• Through the Amazon Developer Portal. Use this method if you want to let your end users authenticate
with Login with Amazon, but you don’t have a Seller Central account.
217
Amazon Cognito Developer Guide
Login with Amazon
• Through Seller Central using http://login.amazon.com/. Use this method if you are a retail merchant
that uses Seller Central.
Note
For Xamarin, follow the Xamarin Getting Started Guide to integrate Login with Amazon into
your Xamarin application.
Note
Login with Amazon integration is not natively supported on the Unity platform. Integration
currently requires the use of a web view to go through the browser sign-in flow.
• Create a Security Profile ID for your application through the Amazon Developer Portal. Use this
method if you want to let your end users authenticate with Amazon, but you don’t have a Seller
Central account. The Developer Portal Login with Amazon documentation takes you through the
process of setting up Login with Amazon in your application, downloading the client SDK, and
declaring your application on the Amazon developer platform. Make a note of the Security Profile ID,
as you'll need to enter it as the Amazon App ID when you create an Amazon Cognito identity pool, as
described in Getting Credentials.
• Create an Application ID for your application through Seller Central using http://login.amazon.com/.
Use this method if you are a retail merchant that uses Seller Central. The Seller Central Login with
Amazon documentation takes you through the process of setting up Login with Amazon in your
application, downloading the client SDK, and declaring your application on the Amazon developer
platform. Make a note of the Application ID, as you'll need to enter it as the Amazon App ID when you
create an Amazon Cognito identity pool, as described in Getting Credentials.
1. Choose the name of the identity pool for which you want to enable Login with Amazon as an
external provider. The Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool
page appears.
3. Scroll down and choose Authentication providers to expand it.
4. Choose the Amazon tab.
5. Choose Unlock.
6. Enter the Amazon App ID you obtained from Amazon, and then choose Save Changes.
@Override
public void onSuccess(Bundle response) {
String token = response.getString(AuthzConstants.BUNDLE_KEY.TOKEN.val);
Map<String, String> logins = new HashMap<String, String>();
logins.put("www.amazon.com", token);
credentialsProvider.setLogins(logins);
218
Amazon Cognito Developer Guide
Login with Amazon
- (void)requestDidSucceed:(APIResult \*)apiResult {
if (apiResult.api == kAPIAuthorizeUser) {
[AIMobileLib getAccessTokenForScopes:[NSArray arrayWithObject:@"profile"]
withOverrideParams:nil delegate:self];
}
else if (apiResult.api == kAPIGetAccessToken) {
credentialsProvider.logins = @{ @(AWSCognitoLoginProviderKeyLoginWithAmazon):
apiResult.result };
}
}}
219
Amazon Cognito Developer Guide
Google
220
Amazon Cognito Developer Guide
Google
Android
Note
If your app uses Google and will be available on multiple mobile platforms, you should
configure it as an OpenID Connect Provider. Adding all created client IDs as additional audience
values to allow for better integration. To learn more about Google's cross-client identity model,
see Cross-client Identity.
Set Up Google
To enable Google Sign-in for Android, you must create a Google Developers console project for your
application.
For additional instructions on using the Google Developers console, see Managing projects in the
Developers Console.
For more information on integrating Google into your Android app, see the Google documentation for
Android.
Choose Manage Identity Pools from the Amazon Cognito Console home page:
1. Choose the name of the identity pool for which you want to enable Google as an external provider.
The Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool page
appears.
3. Scroll down and choose Authentication providers to expand it.
4. Choose the Google tab.
5. Choose Unlock.
6. Enter the Google Client ID you obtained from Google, and then choose Save Changes.
Use Google
To enable login with Google in your application, follow the Google documentation for Android.
Successful authentication results in an OpenID Connect authentication token, which Amazon Cognito
uses to authenticate the user and generate a unique identifier.
The following sample code shows how to retrieve the authentication token from the Google Play service:
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
String token = GoogleAuthUtil.getToken(getApplicationContext(), accounts[0].name,
"audience:server:client_id:YOUR_GOOGLE_CLIENT_ID");
Map<String, String> logins = new HashMap<String, String>();
221
Amazon Cognito Developer Guide
Google
logins.put("accounts.google.com", token);
credentialsProvider.setLogins(logins);
iOS - Objective-C
Note
If your app uses Google and will be available on multiple mobile platforms, you should
configure it as an OpenID Connect Provider. Add all created client IDs as additional audience
values to allow for better integration. To learn more about Google's cross-client identity model,
see Cross-client Identity.
To enable Google Sign-in for iOS, you must create a Google Developers console project for your
application.
Set Up Google
For additional instructions on using the Google Developers console, see Managing projects in the
Developers Console.
For more information on integrating Google into your iOS app, see the Google documentation for iOS.
Choose Manage Identity Pools from the Amazon Cognito Console home page:
1. Choose the name of the identity pool for which you want to enable Google as an external provider.
The Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool
page appears.
3. Scroll down and choose Authentication providers to expand it.
4. Choose the Google tab.
5. Choose Unlock.
6. Enter the Google Client ID you obtained from Google, and then choose Save Changes.
Use Google
To enable login with Google in your application, follow the Google documentation for iOS. Successful
authentication results in an OpenID Connect authentication token, which Amazon Cognito uses to
authenticate the user and generate a unique identifier.
222
Amazon Cognito Developer Guide
Google
iOS - Swift
Note
If your app uses Google and will be available on multiple mobile platforms, you should
configure it as an OpenID Connect Provider. Add all created client IDs as additional audience
values to allow for better integration. To learn more about Google's cross-client identity model,
see Cross-client Identity.
To enable Google Sign-in for iOS, you will need to create a Google Developers console project for your
application.
Set Up Google
For additional instructions on using the Google Developers console, see Managing projects in the
Developers Console.
For more information on integrating Google into your iOS app, see the Google documentation for iOS.
Choose Manage Identity Pools from the Amazon Cognito Console home page:
1. Choose the name of the identity pool for which you want to enable Google as an external provider.
The Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool
page appears.
3. Scroll down and choose Authentication providers to expand it.
4. Choose the Google tab.
5. Choose Unlock.
6. Enter the Google Client ID you obtained from Google, and then choose Save Changes.
Use Google
To enable login with Google in your application, follow the Google documentation for iOS. Successful
authentication results in an OpenID Connect authentication token, which Amazon Cognito uses to
authenticate the user and generate a unique identifier.
223
Amazon Cognito Developer Guide
Google
print(error.localizedDescription)
}
else {
let idToken = auth.parameters.objectForKey("id_token")
credentialsProvider.logins = [AWSCognitoLoginProviderKey.Google.rawValue: idToken!]
}
}
JavaScript
Note
If your app uses Google and will be available on multiple mobile platforms, you should
configure it as an OpenID Connect Provider. Add all created client IDs as additional audience
values to allow for better integration. To learn more about Google's cross-client identity model,
see Cross-client Identity.
Set Up Google
To enable Google Sign-in for your web application, you will need to create a Google Developers console
project for your application.
For additional instructions on using the Google Developers console, see Managing projects in the
Developers Console.
Choose Manage Identity Pools from the Amazon Cognito Console home page:
1. Choose the name of the identity pool for which you want to enable Google as an external provider.
The Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool page
appears.
3. Scroll down and choose Authentication providers to expand it.
4. Choose the Google tab.
5. Choose Unlock.
6. Enter the Google Client ID you obtained from Google, and then choose Save Changes.
Use Google
To enable login with Google in your application, follow the Google documentation for Web.
Successful authentication results in a response object that contains an id_token, which Amazon
Cognito uses to authenticate the user and generate a unique identifier:
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
224
Amazon Cognito Developer Guide
Google
// Add the Google access token to the Amazon Cognito credentials login map.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'IDENTITY_POOL_ID',
Logins: {
'accounts.google.com': authResult['id_token']
}
});
Unity
Set Up Google
To enable Google Sign-in for your web application, you will need to create a Google Developers console
project for your application.
1. Next, you will need to create an OpenID Provider in the IAM Console. For instructions on how to set up
an OpenID Provider, see Using OpenID Connect Identity Providers.
2. When prompted for your Provider URL, enter "https://accounts.google.com".
3. When prompted to enter a value in the Audience field, enter any one of the three client IDs that you
created in the previous steps.
4. After creating the provider, choose the provider name and add two more audiences, providing the two
remaining client IDs.
Choose Manage Identity Pools from the Amazon Cognito Console home page:
1. Choose the name of the identity pool for which you want to enable Google as an external provider.
The Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, choose Edit identity pool. The Edit identity pool page
appears.
3. Scroll down and choose Authentication providers to expand it.
4. Choose the Google tab.
225
Amazon Cognito Developer Guide
Google
5. Choose Unlock.
6. Enter the Google Client ID you obtained from Google, and then choose Save Changes.
1. Add the Google Play Games plugin for Unity to your Unity project.
2. In Unity, from the Windows menu, configure the plugin using the three IDs for the Android and iOS
platforms.
Use Google
The following sample code shows how to retrieve the authentication token from the Google Play service:
void Start()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
Social.localUser.Authenticate(GoogleLoginCallback);
}
Xamarin
Note
Google integration is not natively supported on the Xamarin platform. Integration currently
requires the use of a web view to go through the browser sign-in flow. To learn how Google
integration works with other SDKs, please select another platform.
To enable login with Google in your application, you will need to authenticate your users and obtain an
OpenID Connect token from them. Amazon Cognito uses this token to generate a unique user identifier
that is associated with an Amazon Cognito identity. Unfortunately, the Google SDK for Xamarin doesn't
allow you to retrieve the OpenID Connect token, so you must use an alternative client or the web flow in
a web view.
Once you have the token, you can set it in your CognitoAWSCredentials:
credentials.AddLogin("accounts.google.com", token);
Note
If your app uses Google and will be available on multiple mobile platforms, you should
configure it as an OpenID Connect Provider. Add all created client IDs as additional audience
values to allow for better integration. To learn more about Google's cross-client identity model,
see Cross-client Identity.
226
Amazon Cognito Developer Guide
Sign in with Apple
Adding Sign in with Apple as an authentication provider to an identity pool is a two-step process. First
you integrate Sign in with Apple in an application, and then you configure Sign in with Apple in identity
pools.
227
Amazon Cognito Developer Guide
Sign in with Apple
Note
To integrate Sign in with Apple with a native iOS application, see Implementing User
Authentication with Sign in with Apple.
To integrate Sign in with Apple in a platform other than native iOS, see Sign in with Apple JS.
1. Choose Manage Identity Pools from the Amazon Cognito console home page.
2. Choose the name of the identity pool for which you want to enable Apple as an external provider.
3. In the top-right corner of the dashboard, choose Edit identity pool.
4. Scroll down and choose Authentication providers to expand it.
5. Choose the Apple tab.
6. Enter the Bundle ID that you obtained from https://developer.apple.com. Then choose Save
Changes.
7. If you use Sign in with Apple with native iOS applications, enter the BundleID you obtained from
developer.apple.com. Or if you use Sign in with Apple with web or other applications, enter the
service ID. Then choose Save Changes.
This example generates (or retrieves) an Amazon Cognito ID. This is a public API so you don't need any
credentials to call this API.
This example returns credentials for the provided identity ID and Sign in with Apple login. This is a public
API so you don't need any credentials to call this API.
228
Amazon Cognito Developer Guide
Sign in with Apple
• To configure Sign in with Apple in your application, follow Configuring Your Web page for Sign In with
Apple in the Apple documentation.
• To add a Sign in with Apple button to your Android user interface, follow Displaying and Configuring
Sign In with Apple Buttons in the Apple documentation.
• To securely authenticate users using Sign in with Apple, follow Configuring Your webpage for Sign In
with Apple in the Apple documentation.
Sign in with Apple uses a session object to track its state. Amazon Cognito uses the ID token from this
session object to authenticate the user, generate the unique identifier, and, if needed, grant the user
access to other AWS resources.
@Override
public void onSuccess(Bundle response) {
String token = response.getString("id_token");
Map<String, String> logins = new HashMap<String, String>();
logins.put("appleid.apple.com", token);
credentialsProvider.setLogins(logins);
}
Amazon Cognito uses the ID token to authenticate the user, generate the unique identifier, and, if
needed, grant the user access to other AWS resources.
Amazon Cognito uses the ID token to authenticate the user, generate the unique identifier, and, if
needed, grant the user access to other AWS resources.
For more information on setting up Sign in with Apple in iOS, see Set up Sign in with Apple
229
Amazon Cognito Developer Guide
Sign in with Apple
print(error.localizedDescription)
}
else {
let idToken = auth.identityToken,
credentialsProvider.logins = ["appleid.apple.com": idToken!]
}
}
• To configure Sign in with Apple in your application, follow Configuring Your Web page for Sign In with
Apple in the Apple documentation.
• To add a Sign in with Apple button to your JavaScript user interface, follow Displaying and
Configuring Sign In with Apple Buttons in the Apple documentation.
• To securely authenticate users using Sign in with Apple, follow Configuring Your Web page for Sign In
with Apple in the Apple documentation.
Sign in with Apple uses a session object to track its state. Amazon Cognito uses the ID token from this
session object to authenticate the user, generate the unique identifier, and, if needed, grant the user
access to other AWS resources.
function signinCallback(authResult) {
// Add the apple's id token to the Amazon Cognito credentials login map.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'IDENTITY_POOL_ID',
Logins: {
'appleid.apple.com': authResult['id_token']
}
});
• To configure Sign in with Apple in your application, follow Configuring Your Web page for Sign In with
Apple in the Apple documentation.
• To add a Sign in with Apple button to your Xamarin user interface, follow Displaying and Configuring
Sign In with Apple Buttons in the Apple documentation.
• To securely authenticate users using Sign in with Apple, follow Configuring Your Web page for Sign In
with Apple in the Apple documentation.
Sign in with Apple uses a session object to track its state. Amazon Cognito uses the ID token from this
session object to authenticate the user, generate the unique identifier, and, if needed, grant the user
access to other AWS resources.
Once you have the token, you can set it in your CognitoAWSCredentials:
230
Amazon Cognito Developer Guide
Open ID Connect Providers
credentials.AddLogin("appleid.apple.com", token);
For information on how to create an OpenID Connect Provider, see the IAM documentation.
Once you've created an OpenID Connect provider in the IAM Console, you can associate it with an
identity pool. All configured providers will be visible in the Edit Identity Pool screen in the Amazon
Cognito Console under the OpenID Connect Providers header.
You can associate multiple OpenID Connect providers with a single identity pool.
Refer to your provider's documentation for how to login and receive an ID token.
Once you have a token, add the token to the logins map, using the URI of your provider as the key.
When first integrating with Amazon Cognito, you may receive an InvalidToken exception. It is
important to understand how Amazon Cognito validates OpenID Connect tokens.
Note
As specified here (https://tools.ietf.org/html/rfc7523), Amazon Cognito allows for a grace
period of 5 minutes to handle any clock skew between systems.
1. The iss parameter must match the key used in the logins map (such as login.provider.com).
2. The signature must be valid. The signature must be verifiable via an RSA public key.
3. The fingerprint of the certificate hosting the public key matches what's configured on your OpenId
Connect Provider.
4. If the azp parameter is present, check this value against listed client IDs in your OpenId Connect
provider.
5. If the azp parameter is not present, check the aud parameter against listed client IDs in your OpenId
Connect provider.
The website jwt.io is a valuable resource for decoding tokens to verify these values.
231
Amazon Cognito Developer Guide
Open ID Connect Providers
Android
Map<String, String> logins = new HashMap<String, String>();
logins.put("login.provider.com", token);
credentialsProvider.setLogins(logins);
iOS - Objective-C
credentialsProvider.logins = @{ "login.provider.com": token }
iOS - Swift
To provide the OIDC ID token to Amazon Cognito, implement the AWSIdentityProviderManager
protocol.
In the implementation of the logins method, return a dictionary containing the OIDC provider name that
you configured. This dictionary acts as the key and the current ID token from the authenticated user as
the value, as shown in the following code example.
When you instantiate the AWSCognitoCredentialsProvider, pass the class that implements
AWSIdentityProviderManager as the value of identityProviderManager in the constructor.
For more information, go to the AWSCognitoCredentialsProvider reference page and choose
initWithRegionType:identityPoolId:identityProviderManager.
JavaScript
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'IDENTITY_POOL_ID',
Logins: {
'login.provider.com': token
232
Amazon Cognito Developer Guide
SAML Identity Providers
}
});
Unity
credentials.AddLogin("login.provider.com", token);
Xamarin
credentials.AddLogin("login.provider.com", token);
1. Sign in to the Amazon Cognito console, choose Manage Identity Pools, and choose Create new
identity pool.
2. In the Authentication providers section, choose the SAML tab.
3. Choose the ARN of the SAML provider and then choose Create Pool.
233
Amazon Cognito Developer Guide
Developer Authenticated Identities
the user attribute information available from the identity provider. If multiple roles are received in
the SAML assertion, the optional customRoleArn parameter should be populated while calling
getCredentialsForIdentity. The input role received in the parameter will be assumed by the user if
it matches a role in the claim in the SAML assertion.
To add support for your SAML identity provider in Amazon Cognito, you must first authenticate users
with your SAML identity provider from your iOS or Android application. The code for integrating
and authenticating with the SAML identity provider is specific to SAML providers. After your user is
authenticated, you can provide the resulting SAML assertion to Amazon Cognito Identity using Amazon
Cognito APIs.
Android
If you are using the Android SDK, you can populate the logins map with the SAML assertion as follows.
iOS
If you are using the iOS SDK, you can provide the SAML assertion in AWSIdentityProviderManager as
follows.
// If SAML assertion contains multiple roles, resolve the role by setting the custom role.
// Implementing this is optional if there is only one role.
- (NSString *)customRoleArn {
return @"arn:aws:iam::accountId:role/customRoleName";
}
234
Amazon Cognito Developer Guide
Understanding the Authentication Flow
(Identity Pools) (p. 217), and Sign in with Apple (Identity Pools) (p. 227). With developer
authenticated identities, you can register and authenticate users via your own existing authentication
process, while still using Amazon Cognito to synchronize user data and access AWS resources. Using
developer authenticated identities involves interaction between the end user device, your backend for
authentication, and Amazon Cognito. For more details, please read our blog.
Note: Once the provider name has been set, it cannot be changed.
For additional instructions on working with the Amazon Cognito Console, see Using the Amazon Cognito
Console (p. 3).
// Return the developer provider name which you choose while setting up the
// identity pool in the &COG; Console
@Override
public String getProviderName() {
235
Amazon Cognito Developer Guide
Implement an Identity Provider
return developerProvider;
}
@Override
public String refresh() {
// Call the update method with updated identityId and token to make sure
// these are ready to be used from Credentials Provider.
update(identityId, token);
return token;
// If the app has a valid identityId return it, otherwise get a valid
// identityId from your backend.
@Override
public String getIdentityId() {
if (identityId == null) {
// Call to your backend
} else {
return identityId;
}
}
}
To use this identity provider, you have to pass it into CognitoCachingCredentialsProvider. Here's
an example:
iOS - Objective-C
To use developer authenticated identities, implement your own identity provider class which extends
AWSCognitoCredentialsProviderHelper. Your identity provider class should return a response object
containing the token as an attribute.
@implementation DeveloperAuthenticatedIdentityProvider
/*
* Use the token method to communicate with your backend to get an
* identityId and token.
*/
236
Amazon Cognito Developer Guide
Implement an Identity Provider
@end
To use this identity provider, pass it into AWSCognitoCredentialsProvider as shown in the following
example:
initWithRegionType:AWSRegionYOUR_IDENTITY_POOL_REGION
identityProvider:devAuth];
If you want to support both unauthenticated identities and developer authenticated identities, override
the logins method in your AWSCognitoCredentialsProviderHelper implementation.
If you want to support developer authenticated identities and social providers, you must manage who
the current provider is in your logins implementation of AWSCognitoCredentialsProviderHelper.
iOS - Swift
To use developer authenticated identities, implement your own identity provider class which extends
AWSCognitoCredentialsProviderHelper. Your identity provider class should return a response object
containing the token as an attribute.
import AWSCore
237
Amazon Cognito Developer Guide
Implement an Identity Provider
/*
* Use the token method to communicate with your backend to get an
* identityId and token.
*/
class DeveloperAuthenticatedIdentityProvider : AWSCognitoCredentialsProviderHelper {
override func token() -> AWSTask<NSString> {
//Write code to call your backend:
//pass username/password to backend or some sort of token to authenticate user, if
successful,
//from backend call getOpenIdTokenForDeveloperIdentity with logins map containing
"your.provider.name":"enduser.username"
//return the identity id and token to client
//You can use AWSTaskCompletionSource to do this asynchronously
To use this identity provider, pass it into AWSCognitoCredentialsProvider as shown in the following
example:
let devAuth =
DeveloperAuthenticatedIdentityProvider(regionType: .YOUR_IDENTITY_POOL_REGION,
identityPoolId: "YOUR_IDENTITY_POOL_ID", useEnhancedFlow: true,
identityProviderManager:nil)
let credentialsProvider =
AWSCognitoCredentialsProvider(regionType: .YOUR_IDENTITY_POOL_REGION,
identityProvider:devAuth)
let configuration = AWSServiceConfiguration(region: .YOUR_IDENTITY_POOL_REGION,
credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
If you want to support both unauthenticated identities and developer authenticated identities, override
the logins method in your AWSCognitoCredentialsProviderHelper implementation.
If you want to support developer authenticated identities and social providers, you must manage who
the current provider is in your logins implementation of AWSCognitoCredentialsProviderHelper.
238
Amazon Cognito Developer Guide
Implement an Identity Provider
JavaScript
Once you obtain an identity ID and session token from your backend, you will to pass them into the
AWS.CognitoIdentityCredentials provider. Here's an example:
Unity
To use developer-authenticated identities you have to extend CognitoAWSCredentials and override
the RefreshIdentity method to retrieve the user identity id and token from your backend and return
them. Below is a simple example of an identity provider that would contact a hypothetical backend at
'example.com':
using UnityEngine;
using System.Collections;
using Amazon.CognitoIdentity;
using System.Collections.Generic;
using ThirdParty.Json.LitJson;
using System;
using System.Threading;
239
Amazon Cognito Developer Guide
Implement an Identity Provider
The code above uses a thread dispatcher object to call a coroutine. If you don't have a way to do this in
your project, you can use the following script in your scenes:
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
Xamarin
To use developer-authenticated identities you have to extend CognitoAWSCredentials and override
the RefreshIdentity method to retrieve the user identity id and token from your backend and return
them. Below is a simple example of an identity provider that would contact a hypothetical backend at
'example.com':
240
Amazon Cognito Developer Guide
Updating the Logins Map (Android and iOS only)
credentialsProvider.setLogins(loginsMap);
credentialsProvider.refresh();
iOS - Objective-C
The iOS SDK only calls your logins method to get the latest logins map if there are no credentials
or they have expired. If you want to force the SDK to obtain new credentials (e.g., your end user went
from unauthenticated to authenticated and you want credentials against the authenticated user), call
clearCredentials on your credentialsProvider.
[credentialsProvider clearCredentials];
iOS - Swift
The iOS SDK only calls your logins method to get the latest logins map if there are no credentials
or they have expired. If you want to force the SDK to obtain new credentials (e.g., your end user went
from unauthenticated to authenticated and you want credentials against the authenticated user), call
clearCredentials on your credentialsProvider.
credentialsProvider.clearCredentials()
• You can specify a custom expiration time for the token so you can cache it. If you don't provide any
custom expiration time, the token is valid for 15 minutes.
• The maximum token duration you can set is 24 hours.
241
Amazon Cognito Developer Guide
Connect to an Existing Social Identity
• Be mindful of the security implications of increasing the token duration. If an attacker obtains this
token, they can exchange it for AWS credentials for the end user for the token duration.
The following Java snippet shows how to initialize an Amazon Cognito client and retrieve a token for a
developer authenticated identity.
// create a new request to retrieve the token for your end user
GetOpenIdTokenForDeveloperIdentityRequest request =
new GetOpenIdTokenForDeveloperIdentityRequest();
request.setIdentityPoolId("YOUR_COGNITO_IDENTITY_POOL_ID");
// set up your logins map with the username of your end user
HashMap<String,String> logins = new HashMap<>();
logins.put("YOUR_IDENTITY_PROVIDER_NAME","YOUR_END_USER_IDENTIFIER");
request.setLogins(logins);
Following the steps above, you should be able to integrate developer authenticated identities in your
app. If you have any issues or questions please feel free to post in our forums.
For example, if you are trying to link a custom identity to Facebook, you would add the
Facebook token in addition to your identity provider identifier to the logins map when you call
GetOpenIdTokenForDeveloperIdentity.
logins.put("YOUR_IDENTITY_PROVIDER_NAME","YOUR_END_USER_IDENTIFIER");
logins.put("graph.facebook.com","END_USERS_FACEBOOK_ACCESSTOKEN");
242
Amazon Cognito Developer Guide
Supporting Transition Between Providers
The refresh method should check the logins map, if the map is not empty and has a key with
developer provider name, then you should call your backend; otherwise just call the getIdentityId
method and return null.
setToken(null);
/**
* This is where you would call your backend
**/
} else {
// Call getIdentityId method and return null
this.getIdentityId();
return null;
}
}
Similarly the getIdentityId method will have two flows depending on the contents of the logins map:
if (identityId == null) {
/**
* This is where you would call your backend
**/
243
Amazon Cognito Developer Guide
Supporting Transition Between Providers
} else {
// Otherwise call &COG; using getIdentityId of super class
return super.getIdentityId();
}
} else {
return identityId;
}
iOS - Objective-C
Your application might require supporting unauthenticated identities or authenticated identities using
public providers (Login with Amazon, Sign in with Apple, Facebook, or Google) along with developer
authenticated identities. To do this, override the AWSCognitoCredentialsProviderHelper logins method
to be able to return the correct logins map based on the current identity provider. This example shows
you how you might pivot between unauthenticated, Facebook and developer authenticated.
When you transition from unauthenticated to authenticated, you should call [credentialsProvider
clearCredentials]; to force the SDK to get new authenticated credentials. When you
switch between two authenticated providers and you aren't trying to link the two providers (i.e.
you are not providing tokens for multiple providers in your logins dictionary), you should call
[credentialsProvider clearKeychain];. This will clear both the credentials and identity and
force the SDK to get new ones.
iOS - Swift
Your application might require supporting unauthenticated identities or authenticated identities using
public providers (Login with Amazon, Sign in with Apple, Facebook, or Google) along with developer
authenticated identities. To do this, override the AWSCognitoCredentialsProviderHelper logins method
to be able to return the correct logins map based on the current identity provider. This example shows
you how you might pivot between unauthenticated, Facebook and developer authenticated.
244
Amazon Cognito Developer Guide
Switching Identities
}
}
Unity
Your application might require supporting unauthenticated identities or authenticated identities using
public providers (Login with Amazon, Sign in with Apple, Facebook, or Google) along with developer
authenticated identities. The essential difference between developer authenticated identities and other
identities (unauthenticated identities and authenticated identities using public provider) is the way the
identityId and token are obtained. For other identities the mobile application will interact directly with
Amazon Cognito instead of contacting your authentication system. So the mobile application should be
able to support two distinct flows depending on the choice made by the app user. For this you will have
to make some changes to the custom identity provider.
Xamarin
Your application might require supporting unauthenticated identities or authenticated identities using
public providers (Login with Amazon, Sign in with Apple, Facebook, or Google) along with developer
authenticated identities. The essential difference between developer authenticated identities and other
identities (unauthenticated identities and authenticated identities using public provider) is the way the
identityId and token are obtained. For other identities the mobile application will interact directly with
Amazon Cognito instead of contacting your authentication system. So the mobile application should be
able to support two distinct flows depending on the choice made by the app user. For this you will have
to make some changes to the custom identity provider.
This section describes the case where your user chooses to switch from logging in with an
unauthenticated identity to using an authenticated identity.
Android
Users can log in to your application as unauthenticated guests. Eventually they might decide to log
in using one of the supported IdPs. Amazon Cognito makes sure that an old identity retains the same
unique identifier as the new one, and that the profile data is merged automatically.
245
Amazon Cognito Developer Guide
iOS - Objective-C
@override
public void identityChanged(String oldIdentityId, String newIdentityId) {
// handle the change
}
iOS - Objective-C
Users can log in to your application as unauthenticated guests. Eventually they might decide to log
in using one of the supported IdPs. Amazon Cognito makes sure that an old identity retains the same
unique identifier as the new one, and that the profile data is merged automatically.
-(void)identityDidChange:(NSNotification*)notification {
NSDictionary *userInfo = notification.userInfo;
NSLog(@"identity changed from %@ to %@",
[userInfo objectForKey:AWSCognitoNotificationPreviousId],
[userInfo objectForKey:AWSCognitoNotificationNewId]);
}
iOS - Swift
Users can log in to your application as unauthenticated guests. Eventually they might decide to log
in using one of the supported IdPs. Amazon Cognito makes sure that an old identity retains the same
unique identifier as the new one, and that the profile data is merged automatically.
[NSNotificationCenter.defaultCenter().addObserver(observer: self
selector:"identityDidChange"
name:AWSCognitoIdentityIdChangedNotification
object:nil)
JavaScript
Initially Unauthenticated User
Users typically start with the unauthenticated role. For this role, you set the credentials property of your
configuration object without a Logins property. In this case, your default configuration might look like
the following:
246
Amazon Cognito Developer Guide
Unity
You can also create a CognitoIdentityCredentials object. If you do, you must reset the credentials
properties of any existing service objects to reflect the updated credentials configuration information.
See Using the Global Configuration Object.
Unity
Users can log in to your application as unauthenticated guests. Eventually they might decide to log
in using one of the supported IdPs. Amazon Cognito makes sure that an old identity retains the same
unique identifier as the new one, and that the profile data is merged automatically.
Xamarin
Users can log in to your application as unauthenticated guests. Eventually they might decide to log
in using one of the supported IdPs. Amazon Cognito makes sure that an old identity retains the same
unique identifier as the new one, and that the profile data is merged automatically.
247
Amazon Cognito Developer Guide
Getting Started with Amazon Cognito Sync
Amazon Cognito Sync is an AWS service and client library that enables cross-device syncing of
application-related user data. You can use it to synchronize user profile data across mobile devices and
the web without requiring your own backend. The client libraries cache data locally so your app can read
and write data regardless of device connectivity status. When the device is online, you can synchronize
data, and if you set up push sync, notify other devices immediately that an update is available.
For information about Amazon Cognito Identity region availability, see AWS Service Region Availability.
To learn more about Amazon Cognito Sync, see the following topics.
Topics
• Getting Started with Amazon Cognito Sync (p. 248)
• Synchronizing Data (p. 249)
• Handling Callbacks (p. 256)
• Push Sync (p. 268)
• Amazon Cognito Streams (p. 274)
• Amazon Cognito Events (p. 275)
Amazon Cognito Sync is an AWS service and client library that enable cross-device syncing of
application-related user data. You can use it to synchronize user profile data across mobile devices and
web applications. The client libraries cache data locally so your app can read and write data regardless
of device connectivity status. When the device is online, you can synchronize data, and if you set up push
sync, notify other devices immediately that an update is available.
1. Open https://portal.aws.amazon.com/billing/signup.
2. Follow the online instructions.
248
Amazon Cognito Developer Guide
Set Up an Identity Pool in Amazon Cognito
Part of the sign-up procedure involves receiving a phone call and entering a verification code on the
phone keypad.
Synchronizing Data
If you're new to Amazon Cognito Sync, use AWS AppSync. Like Amazon Cognito Sync, AWS
AppSync is a service for synchronizing application data across devices.
It enables user data like app preferences or game state to be synchronized. It also extends these
capabilities by allowing multiple users to synchronize and collaborate in real time on shared
data.
Amazon Cognito lets you save end user data in datasets containing key-value pairs. This data is
associated with an Amazon Cognito identity, so that it can be accessed across logins and devices. To
sync this data between the Amazon Cognito service and an end user’s devices, invoke the synchronize
method. Each dataset can have a maximum size of 1 MB. You can associate up to 20 datasets with an
identity.
The Amazon Cognito Sync client creates a local cache for the identity data. Your app talks to this local
cache when it reads and writes keys. This guarantees that all of your changes made on the device are
immediately available on the device, even when you are offline. When the synchronize method is called,
changes from the service are pulled to the device, and any local changes are pushed to the service. At
this point the changes are available to other devices to synchronize.
Android
1. Create a credentials provider, following the instructions in Getting Credentials (p. 204).
2. Import the Amazon Cognito package: import com.amazonaws.mobileconnectors.cognito.*;
3. Initialize Amazon Cognito Sync, passing in the Android app context, the identity pool ID, an AWS
region, and an initialized Amazon Cognito credentials provider:
249
Amazon Cognito Developer Guide
Initializing the Amazon Cognito Sync Client
Regions.YOUR_REGION,
credentialsProvider);
iOS - Objective-C
1. Create a credentials provider, following the instructions in Getting Credentials (p. 204).
2. Import AWSCore and Cognito, and initialize AWSCognito:
#import <AWSiOSSDKv2/AWSCore.h>
#import <AWSCognitoSync/Cognito.h>
3. If you're using CocoaPods, replace <AWSiOSSDKv2/AWSCore.h> with AWSCore.h and follow the
same syntax for the Amazon Cognito import.
iOS - Swift
1. Create a credentials provider, following the instructions in Getting Credentials (p. 204).
2. Import and initialize AWSCognito:
import AWSCognito
let syncClient = AWSCognito.default()!
JavaScript
1. Download the Amazon Cognito Sync Manager for JavaScript.
2. Include the Sync Manager library in your project.
3. Create a credentials provider, following the instructions in Getting Credentials (p. 204).
4. Initialize the Sync Manager:
Unity
1. You will need to first create an instance of CognitoAWSCredentials, following the instructions in
Getting Credentials (p. 204).
2. Create an instance of CognitoSyncManager, passing the CognitoAwsCredentials object and a
AmazonCognitoSyncConfig with, at least, the region set:
Xamarin
1. You will need to first create an instance of CognitoAWSCredentials, following the instructions in
Getting Credentials (p. 204).
250
Amazon Cognito Developer Guide
Understanding Datasets
Understanding Datasets
With Amazon Cognito, end user profile data is organized into datasets. Each dataset can contain up
to 1MB of data in the form of key-value pairs. A dataset is the most granular entity on which you can
perform a sync operation. Read and write operations performed on a dataset only affect the local store
until the synchronize method is invoked. A dataset is identified by a unique string. You can create a new
dataset or open an existing one as shown in the following.
Android
Dataset dataset = client.openOrCreateDataset("datasetname");
To delete a dataset, first call the method to remove it from local storage, then call the synchronize
method to delete the dataset from Amazon Cognito:
dataset.delete();
dataset.synchronize(syncCallback);
iOS - Objective-C
AWSCognitoDataset *dataset = [syncClient openOrCreateDataset:@"myDataSet"];
To delete a dataset, first call the method to remove it from local storage, then call the synchronize
method to delete the dataset from Amazon Cognito:
[dataset clear];
[dataset synchronize];
iOS - Swift
let dataset = syncClient.openOrCreateDataset("myDataSet")!
To delete a dataset, first call the method to remove it from local storage, then call the synchronize
method to delete the dataset from Amazon Cognito:
dataset.clear()
dataset.synchronize()
JavaScript
syncManager.openOrCreateDataset('myDatasetName', function(err, dataset) {
// ...
251
Amazon Cognito Developer Guide
Reading and Writing Data in Datasets
});
Unity
string myValue = dataset.Get("myKey");
dataset.Put("myKey", "newValue");
dataset.Remove("myKey");
Xamarin
Dataset dataset = syncManager.OpenOrCreateDataset("myDatasetName");
To delete a dataset, first call the method to remove it from local storage, then call the synchronize
method to delete the dataset from Amazon Cognito:
dataset.Delete();
dataset.SynchronizeAsync();
Note that values written to a dataset only affect the local cached copy of the data until you call the
synchronize method.
Android
String value = dataset.get("myKey");
dataset.put("myKey", "my value");
iOS - Objective-C
[dataset setString:@"my value" forKey:@"myKey"];
NSString *value = [dataset stringForKey:@"myKey"];
iOS - Swift
dataset.setString("my value", forKey:"myKey")
let value = dataset.stringForKey("myKey")
JavaScript
252
Amazon Cognito Developer Guide
Reading and Writing Data in Datasets
});
Unity
string myValue = dataset.Get("myKey");
dataset.Put("myKey", "newValue");
Xamarin
//obtain a value
string myValue = dataset.Get("myKey");
Android
You can use the remove method to remove keys from a dataset:
dataset.remove("myKey");
iOS - Objective-C
You can use removeObjectForKey to delete a key from a dataset:
[dataset removeObjectForKey:@"myKey"];
iOS - Swift
You can use removeObjectForKey to delete a key from a dataset:
dataset.removeObjectForKey("myKey")
Unity
You can use Remove to delete a key from a dataset:
dataset.Remove("myKey");
253
Amazon Cognito Developer Guide
Synchronizing Local Data with the Sync Store
Xamarin
You can use Remove to delete a key from a dataset:
dataset.Remove("myKey");
dataset.synchronize(syncCallback);
To learn more about dataset synchronization and the different callbacks, see Handling
Callbacks (p. 256).
iOS - Objective-C
The synchronize method compares local cached data to the data stored in the Amazon Cognito Sync
store. Remote changes are pulled from the Amazon Cognito Sync store; conflict resolution is invoked if
any conflicts occur; and updated values on the device are pushed to the service. To synchronize a dataset,
call its synchronize method:
The synchronize method is asynchronous and returns an AWSTask object to handle the response:
The synchronizeOnConnectivity method attempts to synchronize when the device has connectivity.
First, synchronizeOnConnectivity checks for connectivity and, if the device is online, immediately
invokes synchronize and returns the AWSTask object associated with the attempt.
If the device is offline, synchronizeOnConnectivity 1) schedules a synchronize for the next time
the device comes online and 2) returns an AWSTask with a nil result. The scheduled synchronize is only
254
Amazon Cognito Developer Guide
Synchronizing Local Data with the Sync Store
valid for the lifecycle of the dataset object. The data will not be synchronized if the app is exited before
connectivity is regained. If you want to be notified when events occur during the scheduled synchronize,
you must add observers of the notifications found in AWSCognito.
To learn more about dataset synchronization and the different callbacks, see Handling
Callbacks (p. 256).
iOS - Swift
The synchronize method compares local cached data to the data stored in the Amazon Cognito Sync
store. Remote changes are pulled from the Amazon Cognito Sync store; conflict resolution is invoked if
any conflicts occur; and updated values on the device are pushed to the service. To synchronize a dataset,
call its synchronize method:
The synchronize method is asynchronous and returns an AWSTask object to handle the response:
if task.isCancelled {
// Task cancelled.
} else if task.error != nil {
// Error while executing task
} else {
// Task succeeded. The data was saved in the sync store.
}
return task
})
The synchronizeOnConnectivity method attempts to synchronize when the device has connectivity.
First, synchronizeOnConnectivity checks for connectivity and, if the device is online, immediately
invokes synchronize and returns the AWSTask object associated with the attempt.
If the device is offline, synchronizeOnConnectivity 1) schedules a synchronize for the next time the
device comes online and 2) returns an AWSTask object with a nil result. The scheduled synchronize is
only valid for the lifecycle of the dataset object. The data will not be synchronized if the app is exited
before connectivity is regained. If you want to be notified when events occur during the scheduled
synchronize, you must add observers of the notifications found in AWSCognito.
To learn more about dataset synchronization and the different callbacks, see Handling
Callbacks (p. 256).
JavaScript
The synchronize method compares local cached data to the data stored in the Amazon Cognito Sync
store. Remote changes are pulled from the Amazon Cognito Sync store; conflict resolution is invoked if
any conflicts occur; and updated values on the device are pushed to the service. To synchronize a dataset,
call its synchronize method:
dataset.synchronize();
To learn more about dataset synchronization and the different callbacks, see Handling
Callbacks (p. 256).
Unity
The synchronize method compares local cached data to the data stored in the Amazon Cognito Sync
store. Remote changes are pulled from the Amazon Cognito Sync store; conflict resolution is invoked if
255
Amazon Cognito Developer Guide
Handling Callbacks
any conflicts occur; and updated values on the device are pushed to the service. To synchronize a dataset,
call its synchronize method:
dataset.Synchronize();
Synchronize will run asynchronously and will end up calling one of the several callbacks you can specify
in the Dataset.
To learn more about dataset synchronization and the different callbacks, see Handling
Callbacks (p. 256).
Xamarin
The synchronize method compares local cached data to the data stored in the Amazon Cognito Sync
store. Remote changes are pulled from the Amazon Cognito Sync store; conflict resolution is invoked if
any conflicts occur; and updated values on the device are pushed to the service. To synchronize a dataset,
call its synchronize method:
dataset.SynchronizeAsync();
To learn more about dataset synchronization and the different callbacks, see Handling
Callbacks (p. 256).
Handling Callbacks
If you're new to Amazon Cognito Sync, use AWS AppSync. Like Amazon Cognito Sync, AWS
AppSync is a service for synchronizing application data across devices.
It enables user data like app preferences or game state to be synchronized. It also extends these
capabilities by allowing multiple users to synchronize and collaborate in real time on shared
data.
Android
SyncCallback Interface
By implementing the SyncCallback interface, you can receive notifications on your app about
dataset synchronization. Your app can then make active decisions about deleting local data, merging
unauthenticated and authenticated profiles, and resolving sync conflicts. You should implement the
following methods, which are required by the interface:
• onSuccess()
• onFailure()
• onConflict()
• onDatasetDeleted()
• onDatasetsMerged()
Note that, if you don't want to specify all the callbacks, you can also use the class
DefaultSyncCallback which provides default, empty implementations for all of them.
onSuccess
256
Amazon Cognito Developer Guide
Android
The onSuccess() callback is triggered when a dataset is successfully downloaded from the sync store.
@Override
public void onSuccess(Dataset dataset, List<Record> newRecords) {
}
onFailure
@Override
public void onFailure(DataStorageException dse) {
}
onConflict
Conflicts may arise if the same key has been modified on the local store and in the sync store. The
onConflict() method handles conflict resolution. If you don't implement this method, the Amazon
Cognito Sync client defaults to using the most recent change.
@Override
public boolean onConflict(Dataset dataset, final List<SyncConflict> conflicts) {
List<Record> resolvedRecords = new ArrayList<Record>();
for (SyncConflict conflict : conflicts) {
/* resolved by taking remote records */
resolvedRecords.add(conflict.resolveWithRemoteRecord());
onDatasetDeleted
When a dataset is deleted, the Amazon Cognito client uses the SyncCallback interface to
confirm whether the local cached copy of the dataset should be deleted too. Implement the
onDatasetDeleted() method to tell the client SDK what to do with the local data.
@Override
public boolean onDatasetDeleted(Dataset dataset, String datasetName) {
// return true to delete the local copy of the dataset
return true;
}
onDatasetMerged
When two previously unconnected identities are linked together, all of their datasets are merged.
Applications are notified of the merge through the onDatasetsMerged() method:
@Override
257
Amazon Cognito Developer Guide
iOS - Objective-C
iOS - Objective-C
Sync Notifications
The Amazon Cognito client will emit a number of NSNotification events during a synchronize call.
You can register to monitor these notifications via the standard NSNotificationCenter:
[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(myNotificationHandler:)
name:NOTIFICATION_TYPE
object:nil];
AWSCognitoDidStartSynchronizeNotification
Called when a synchronize operation is starting. The userInfo will contain the key dataset which is the
name of the dataset being synchronized.
AWSCognitoDidEndSynchronizeNotification
Called when a synchronize operation completes (successfully or otherwise). The userInfo will contain
the key dataset which is the name of the dataset being synchronized.
AWSCognitoDidFailToSynchronizeNotification
Called when a synchronize operation fails. The userInfo will contain the key dataset which is the name
of the dataset being synchronized and the key error which will contain the error that caused the failure.
AWSCognitoDidChangeRemoteValueNotification
Called when local changes are successfully pushed to Amazon Cognito. The userInfo will contain the
key dataset which is the name of the dataset being synchronized and the key keys which will contain an
NSArray of record keys that were pushed.
AWSCognitoDidChangeLocalValueFromRemoteNotification
Called when a local value changes due to a synchronize operation. The userInfo will contain the key
dataset which is the name of the dataset being synchronized and the key keys which will contain an
NSArray of record keys that changed.
During a sync operation, conflicts may arise if the same key has been modified on the local store and in
the sync store. If you haven't set a conflict resolution handler, Amazon Cognito defaults to choosing the
most recent update.
By implementing and assigning an AWSCognitoRecordConflictHandler you can alter the default conflict
resolution. The AWSCognitoConflict input parameter conflict contains an AWSCognitoRecord object for
both the local cached data and for the conflicting record in the sync store. Using the AWSCognitoConflict
you can resolve the conflict with the local record: [conflict resolveWithLocalRecord], the remote record:
[conflict resolveWithRemoteRecord] or a brand new value: [conflict resolveWithValue:value]. Returning
nil from this method prevents synchronization from continuing and the conflicts will be presented again
the next time the sync process starts.
258
Amazon Cognito Developer Guide
iOS - Objective-C
You can set the conflict resolution handler at the client level:
When a dataset is deleted, the Amazon Cognito client uses the AWSCognitoDatasetDeletedHandler
to confirm whether the local cached copy of the dataset should be deleted too. If no
AWSCognitoDatasetDeletedHandler is implemented, the local data will be purged automatically.
Implement an AWSCognitoDatasetDeletedHandler if you wish to keep a copy of the local data
before wiping, or to keep the local data.
You can set the dataset deleted handler at the client level:
When two previously unconnected identities are linked together, all of their datasets are merged.
Applications are notified of the merge through the DatasetMergeHandler. The handler will receive
the name of the root dataset as well as an array of dataset names that are marked as merges of the root
dataset.
If no DatasetMergeHandler is implemented, these datasets will be ignored, but will continue to use up
space in the identity's 20 maximum total datasets.
You can set the dataset merge handler at the client level:
259
Amazon Cognito Developer Guide
iOS - Swift
}
};
iOS - Swift
Sync Notifications
The Amazon Cognito client will emit a number of NSNotification events during a synchronize call.
You can register to monitor these notifications via the standard NSNotificationCenter:
NSNotificationCenter.defaultCenter().addObserver(observer: self,
selector: "myNotificationHandler",
name:NOTIFICATION_TYPE,
object:nil)
AWSCognitoDidStartSynchronizeNotification
Called when a synchronize operation is starting. The userInfo will contain the key dataset which is the
name of the dataset being synchronized.
AWSCognitoDidEndSynchronizeNotification
Called when a synchronize operation completes (successfully or otherwise). The userInfo will contain
the key dataset which is the name of the dataset being synchronized.
AWSCognitoDidFailToSynchronizeNotification
Called when a synchronize operation fails. The userInfo will contain the key dataset which is the name
of the dataset being synchronized and the key error which will contain the error that caused the failure.
AWSCognitoDidChangeRemoteValueNotification
Called when local changes are successfully pushed to Amazon Cognito. The userInfo will contain the
key dataset which is the name of the dataset being synchronized and the key keys which will contain an
NSArray of record keys that were pushed.
AWSCognitoDidChangeLocalValueFromRemoteNotification
Called when a local value changes due to a synchronize operation. The userInfo will contain the key
dataset which is the name of the dataset being synchronized and the key keys which will contain an
NSArray of record keys that changed.
260
Amazon Cognito Developer Guide
iOS - Swift
During a sync operation, conflicts may arise if the same key has been modified on the local store and in
the sync store. If you haven't set a conflict resolution handler, Amazon Cognito defaults to choosing the
most recent update.
You can set the conflict resolution handler at the client level:
client.conflictHandler = {
(datasetName: String?, conflict: AWSCognitoConflict?) -> AWSCognitoResolvedConflict? in
return conflict.resolveWithLocalRecord()
}
dataset.conflictHandler = {
(datasetName: String?, conflict: AWSCognitoConflict?) -> AWSCognitoResolvedConflict? in
return conflict.resolveWithLocalRecord()
}
When a dataset is deleted, the Amazon Cognito client uses the AWSCognitoDatasetDeletedHandler
to confirm whether the local cached copy of the dataset should be deleted too. If no
AWSCognitoDatasetDeletedHandler is implemented, the local data will be purged automatically.
Implement an AWSCognitoDatasetDeletedHandler if you wish to keep a copy of the local data
before wiping, or to keep the local data.
You can set the dataset deleted handler at the client level:
client.datasetDeletedHandler = {
(datasetName: String!) -> Bool in
// make a backup of the data if you choose
...
// delete the local data (default behaviour)
return true
}
dataset.datasetDeletedHandler = {
(datasetName: String!) -> Bool in
// make a backup of the data if you choose
...
// delete the local data (default behaviour)
return true
}
When two previously unconnected identities are linked together, all of their datasets are merged.
Applications are notified of the merge through the DatasetMergeHandler. The handler will receive
261
Amazon Cognito Developer Guide
JavaScript
the name of the root dataset as well as an array of dataset names that are marked as merges of the root
dataset.
If no DatasetMergeHandler is implemented, these datasets will be ignored, but will continue to use up
space in the identity's 20 maximum total datasets.
You can set the dataset merge handler at the client level:
client.datasetMergedHandler = {
(datasetName: String!, datasets: [AnyObject]!) -> Void in
for nameObject in datasets {
if let name = nameObject as? String {
let merged = AWSCognito.defaultCognito().openOrCreateDataset(name)
merged.clear()
merged.synchronize()
}
}
}
dataset.datasetMergedHandler = {
(datasetName: String!, datasets: [AnyObject]!) -> Void in
for nameObject in datasets {
if let name = nameObject as? String {
let merged = AWSCognito.defaultCognito().openOrCreateDataset(name)
// do something with the data if it differs from existing dataset
...
// now delete it
merged.clear()
merged.synchronize()
}
}
}
JavaScript
Synchronization Callbacks
When performing a synchronize() on a dataset, you can optionally specify callbacks to handle each of the
following states:
dataset.synchronize({
onFailure: function(err) {
//...
},
262
Amazon Cognito Developer Guide
JavaScript
});
onSuccess()
The onSuccess() callback is triggered when a dataset is successfully updated from the sync store. If
you do not define a callback, the synchronization will succeed silently.
onFailure()
onFailure() is called if an exception occurs during synchronization. If you do not define a callback, the
synchronization will fail silently.
onFailure: function(err) {
console.log('Synchronization failed.');
console.log(err);
}
onConflict()
Conflicts may arise if the same key has been modified on the local store and in the sync store.
The onConflict() method handles conflict resolution. If you don't implement this method, the
synchronization will be aborted when there is a conflict.
dataset.resolve(resolved, function() {
return callback(true);
});
onDatasetDeleted()
263
Amazon Cognito Developer Guide
Unity
When a dataset is deleted, the Amazon Cognito client uses the onDatasetDeleted() callback to
decide whether the local cached copy of the dataset should be deleted too. By default, the dataset will
not be deleted.
return callback(true);
onDatasetMerged()
When two previously unconnected identities are linked together, all of their datasets are merged.
Applications are notified of the merge through the onDatasetsMerged() callback.
return callback(false);
Unity
After you open or create a dataset, you can set different callbacks to it that will be triggered when you
use the Synchronize method. This is the way to register your callbacks to them:
dataset.OnSyncSuccess += this.HandleSyncSuccess;
dataset.OnSyncFailure += this.HandleSyncFailure;
dataset.OnSyncConflict = this.HandleSyncConflict;
dataset.OnDatasetMerged = this.HandleDatasetMerged;
dataset.OnDatasetDeleted = this.HandleDatasetDeleted;
Note that SyncSuccess and SyncFailure use += instead of = so you can subscribe more than one
callback to them.
OnSyncSuccess
The OnSyncSuccess callback is triggered when a dataset is successfully updated from the cloud. If you
do not define a callback, the synchronization will succeed silently.
OnSyncFailure
OnSyncFailure is called if an exception occurs during synchronization. If you do not define a callback,
the synchronization will fail silently.
264
Amazon Cognito Developer Guide
Unity
{
Dataset dataset = sender as Dataset;
if (dataset.Metadata != null) {
Debug.Log("Sync failed for dataset : " + dataset.Metadata.DatasetName);
} else {
Debug.Log("Sync failed");
}
// Handle the error
Debug.LogException(e.Exception);
}
OnSyncConflict
Conflicts may arise if the same key has been modified on the local store and in the sync store. The
OnSyncConflict callback handles conflict resolution. If you don't implement this method, the
synchronization will be aborted when there is a conflict.
OnDatasetDeleted
When a dataset is deleted, the Amazon Cognito client uses the OnDatasetDeleted callback to decide
whether the local cached copy of the dataset should be deleted too. By default, the dataset will not be
deleted.
OnDatasetMerged
When two previously unconnected identities are linked together, all of their datasets are merged.
Applications are notified of the merge through the OnDatasetsMerged callback.
265
Amazon Cognito Developer Guide
Xamarin
{
foreach (string name in mergedDatasetNames)
{
Dataset mergedDataset = syncManager.OpenOrCreateDataset(name);
//Lambda function to delete the dataset after fetching it
EventHandler<SyncSuccessEvent> lambda;
lambda = (object sender, SyncSuccessEvent e) => {
ICollection<string> existingValues = localDataset.GetAll().Values;
ICollection<string> newValues = mergedDataset.GetAll().Values;
Xamarin
After you open or create a dataset, you can set different callbacks to it that will be triggered when you
use the Synchronize method. This is the way to register your callbacks to them:
dataset.OnSyncSuccess += this.HandleSyncSuccess;
dataset.OnSyncFailure += this.HandleSyncFailure;
dataset.OnSyncConflict = this.HandleSyncConflict;
dataset.OnDatasetMerged = this.HandleDatasetMerged;
dataset.OnDatasetDeleted = this.HandleDatasetDeleted;
Note that SyncSuccess and SyncFailure use += instead of = so you can subscribe more than one
callback to them.
OnSyncSuccess
The OnSyncSuccess callback is triggered when a dataset is successfully updated from the cloud. If you
do not define a callback, the synchronization will succeed silently.
OnSyncFailure
OnSyncFailure is called if an exception occurs during synchronization. If you do not define a callback,
the synchronization will fail silently.
266
Amazon Cognito Developer Guide
Xamarin
{
Dataset dataset = sender as Dataset;
if (dataset.Metadata != null) {
Console.WriteLine("Sync failed for dataset : " + dataset.Metadata.DatasetName);
} else {
Console.WriteLine("Sync failed");
}
}
OnSyncConflict
Conflicts may arise if the same key has been modified on the local store and in the sync store. The
OnSyncConflict callback handles conflict resolution. If you don't implement this method, the
synchronization will be aborted when there is a conflict.
OnDatasetDeleted
When a dataset is deleted, the Amazon Cognito client uses the OnDatasetDeleted callback to decide
whether the local cached copy of the dataset should be deleted too. By default, the dataset will not be
deleted.
OnDatasetMerged
When two previously unconnected identities are linked together, all of their datasets are merged.
Applications are notified of the merge through the OnDatasetsMerged callback.
267
Amazon Cognito Developer Guide
Push Sync
{
Dataset mergedDataset = syncManager.OpenOrCreateDataset(name);
mergedDataset.OnSyncSuccess += lambda;
mergedDataset.SynchronizeAsync(); //Asnchronously fetch the dataset
}
Push Sync
If you're new to Amazon Cognito Sync, use AWS AppSync. Like Amazon Cognito Sync, AWS
AppSync is a service for synchronizing application data across devices.
It enables user data like app preferences or game state to be synchronized. It also extends these
capabilities by allowing multiple users to synchronize and collaborate in real time on shared
data.
Amazon Cognito automatically tracks the association between identity and devices. Using the push
synchronization, or push sync, feature, you can ensure that every instance of a given identity is notified
when identity data changes. Push sync ensures that, whenever the sync store data changes for a
particular identity, all devices associated with that identity receive a silent push notification informing
them of the change.
Note
Push sync is not supported for JavaScript, Unity, or Xamarin.
Before you can use push sync, you must first set up your account for push sync and enable push sync in
the Amazon Cognito console.
1. Click the name of the identity pool for which you want to enable push sync. The Dashboard page for
your identity pool appears.
2. In the top-right corner of the Dashboard page, click Manage Identity Pools. The Federated Identities
page appears.
3. Scroll down and click Push synchronization to expand it.
4. In the Service role dropdown menu, select the IAM role that grants Cognito permission to send an
SNS notification. Click Create role to create or modify the roles associated with your identity pool in
the AWS IAM Console.
5. Select a platform application, and then click Save Changes.
6. Grant SNS Access to Your Application
268
Amazon Cognito Developer Guide
Use Push Sync in Your App: Android
In the IAM console, configure your IAM roles to have full SNS access, or create a new role that trusts
cognito-sync and has full SNS access. To learn more about IAM roles, see Roles (Delegation and
Federation).
You can now subscribe a device to receive updates from a particular dataset:
To stop receiving push notifications from a dataset, simply call the unsubscribe method. To subscribe to
all datasets (or a specific subset) in the CognitoSyncManager object, use subscribeAll():
if (client.isDeviceRegistered()) {
try {
client.subscribeAll();
} catch (SubscribeFailedException sfe) {
Log.e(TAG, "Failed to subscribe to datasets", sfe);
} catch (AmazonClientException ace) {
Log.e(TAG, "An unknown error caused the subscription to fail", ace);
}
}
In your implementation of the Android BroadcastReceiver object, you can check the latest version of the
modified dataset and decide if your app needs to synchronize again:
@Override
public void onReceive(Context context, Intent intent) {
269
Amazon Cognito Developer Guide
Use Push Sync in Your App: iOS - Objective-C
In debug mode, your device will register with the APNs sandbox; in release mode, it will register with
APNs. To receive updates from a particular dataset, use the subscribe method:
270
Amazon Cognito Developer Guide
Use Push Sync in Your App: iOS - Objective-C
}
return nil;
}
];
To stop receiving push notifications from a dataset, simply call the unsubscribe method:
Before calling subscribeAll, be sure to synchronize at least once on each dataset, so that the datasets
exist on the server.
If you post a notification using notification handler, you can then respond to the notification elsewhere
in the application where you have a handle to your dataset. If you subscribe to the notification like this ...
- (void)didReceivePushSync:(NSNotification*)notification
{
NSDictionary * data = [(NSDictionary *)[notification object] objectForKey:@"data"];
NSString * identityId = [data objectForKey:@"identityId"];
NSString * datasetName = [data objectForKey:@"datasetName"];
if([self.dataset.name isEqualToString:datasetName] && [self.identityId
isEqualToString:identityId]){
271
Amazon Cognito Developer Guide
Use Push Sync in Your App: iOS - Swift
} else {
print("Successfully registered device with id: \(task.result)")
}
return task
})
In debug mode, your device will register with the APNs sandbox; in release mode, it will register with
APNs. To receive updates from a particular dataset, use the subscribe method:
syncClient.openOrCreateDataset("MyDataset").subscribe().continueWith(block: { (task:
AWSTask!) -> AnyObject! in
if (task.error != nil) {
print("Unable to subscribe to dataset: " + task.error.localizedDescription)
} else {
print("Successfully subscribed to dataset: \(task.result)")
}
return task
})
To stop receiving push notifications from a dataset, call the unsubscribe method:
syncClient.openOrCreateDataset("MyDataset").unsubscribe().continueWith(block: { (task:
AWSTask!) -> AnyObject! in
if (task.error != nil) {
272
Amazon Cognito Developer Guide
Use Push Sync in Your App: iOS - Swift
} else {
print("Successfully unsubscribed to dataset: \(task.result)")
}
return task
})
syncClient.openOrCreateDataset("MyDataset").subscribeAll().continueWith(block: { (task:
AWSTask!) -> AnyObject! in
if (task.error != nil) {
print("Unable to subscribe to all datasets: " + task.error.localizedDescription)
} else {
print("Successfully subscribed to all datasets: \(task.result)")
}
return task
})
Before calling subscribeAll, be sure to synchronize at least once on each dataset, so that the datasets
exist on the server.
NSNotificationCenter.defaultCenter().postNotificationName("CognitoPushNotification",
object: userInfo)
})
If you post a notification using notification handler, you can then respond to the notification elsewhere
in the application where you have a handle to your dataset. If you subscribe to the notification like this ...
NSNotificationCenter.defaultCenter().addObserver(observer:self,
selector:"didReceivePushSync:",
name:"CognitoPushNotification",
object:nil)
273
Amazon Cognito Developer Guide
Amazon Cognito Streams
Amazon Cognito Streams gives developers control and insight into their data stored in Amazon Cognito.
Developers can now configure a Kinesis stream to receive events as data is updated and synchronized.
Amazon Cognito can push each dataset change to a Kinesis stream you own in real time.
Using Amazon Cognito Streams, you can move all of your Sync data to Kinesis, which can then be
streamed to a data warehouse tool such as Amazon Redshift for further analysis. To learn more about
Kinesis, see Getting Started Using Amazon Kinesis.
Configuring Streams
You can set up Amazon Cognito Streams in the Amazon Cognito console. To enable Amazon Cognito
Streams in the Amazon Cognito console, you need to select the Kinesis stream to publish to and an IAM
role that grants Amazon Cognito permission to put events in the selected stream.
1. Click the name of the identity pool for which you want to set up Amazon Cognito Streams. The
Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, click Manage Identity Pools. The Manage Federated
Identities page appears.
3. Scroll down and click Cognito Streams to expand it.
4. In the Stream name dropdown menu, select the name of an existing Kinesis stream. Alternatively,
click Create stream to create one, entering a stream name and the number of shards. To learn about
shards and for help on estimating the number of shards needed for your stream, see the Kinesis
Developer Guide.
5. In the Publish role dropdown menu, select the IAM role that grants Amazon Cognito permission to
publish your stream. Click Create role to create or modify the roles associated with your identity pool
in the AWS IAM Console.
6. In the Stream status dropdown menu, select Enabled to enable the stream updates. Click Save
Changes.
After you've successfully configured Amazon Cognito streams, all subsequent updates to datasets in this
identity pool will be sent to the stream.
274
Amazon Cognito Developer Guide
Amazon Cognito Events
Stream Contents
Each record sent to the stream represents a single synchronization. Here is an example of a record sent
to the stream:
{
"identityPoolId": "Pool Id",
"identityId": "Identity Id",
"dataSetName": "Dataset Name",
"operation": "(replace|remove)",
"kinesisSyncRecords": [
{
"key": "Key",
"value": "Value",
"syncCount": 1,
"lastModifiedDate": 1424801824343,
"deviceLastModifiedDate": 1424801824343,
"op": "(replace|remove)"
},
...
],
"lastModifiedDate": 1424801824343,
"kinesisSyncRecordsURL": "S3Url",
"payloadType": "(S3Url|Inline)",
"syncCount": 1
}
For updates that are larger than the Kinesis maximum payload size of 50 KB, a presigned Amazon S3 URL
will be included that contains the full contents of the update.
After you have configured Amazon Cognito streams, if you delete the Kinesis stream or change the role
trust permission so that it can no longer be assumed by Amazon Cognito Sync, Amazon Cognito streams
will be disabled. You will need to either recreate the Kinesis stream or fix the role, and then you will need
to reenable the stream.
Bulk Publishing
Once you have configured Amazon Cognito streams, you will be able to execute a bulk publish operation
for the existing data in your identity pool. After you initiate a bulk publish operation, either via the
console or directly via the API, Amazon Cognito will start publishing this data to the same stream that is
receiving your updates.
Amazon Cognito does not guarantee uniqueness of data sent to the stream when using the bulk publish
operation. You may receive the same update both as an update as well as part of a bulk publish. Keep
this in mind when processing the records from your stream.
To bulk publish all of your streams, follow steps 1-6 under Configuring Streams and then click Start bulk
publish. You are limited to one ongoing bulk publish operation at any given time and to one successful
bulk publish request every 24 hours.
Amazon Cognito Events allows you to execute an AWS Lambda function in response to important events
in Amazon Cognito. Amazon Cognito raises the Sync Trigger event when a dataset is synchronized. You
275
Amazon Cognito Developer Guide
Amazon Cognito Events
can use the Sync Trigger event to take an action when a user updates data. The function can evaluate
and optionally manipulate the data before it is stored in the cloud and synchronized to the user's other
devices. This is useful to validate data coming from the device before it is synchronized to the user's
other devices, or to update other values in the dataset based on incoming data such as issuing an award
when a player reaches a new level.
The steps below will guide you through setting up a Lambda function that executes each time a Amazon
Cognito Dataset is synchronized.
Note
When using Amazon Cognito events, you can only use the credentials obtained from Amazon
Cognito Identity. If you have an associated Lambda function, but you call UpdateRecords with
AWS account credentials (developer credentials), your Lambda function will not be invoked.
To integrate Lambda with Amazon Cognito, you first need to create a function in Lambda. To do so:
Now that you have an appropriate function written in Lambda, you need to choose that function as the
handler for the Amazon Cognito Sync Trigger event. The steps below walk you through this process.
1. Click the name of the identity pool for which you want to set up Amazon Cognito Events. The
Dashboard page for your identity pool appears.
2. In the top-right corner of the Dashboard page, click Manage Federated Identities. The Manage
Federated Identities page appears.
3. Scroll down and click Cognito Events to expand it.
4. In the Sync Trigger dropdown menu, select the Lambda function that you want to trigger when a Sync
event occurs.
5. Click Save Changes.
Now, your Lambda function will be executed each time a dataset is synchronized. The next section
explains how you can read and modify the data in your function as it is being synchronized.
Sync triggers follow the service provider interface programming paradigm. Amazon Cognito will provide
input in the following JSON format to your Lambda function.
276
Amazon Cognito Developer Guide
Amazon Cognito Events
{
"version": 2,
"eventType": "SyncTrigger",
"region": "us-east-1",
"identityPoolId": "identityPoolId",
"identityId": "identityId",
"datasetName": "datasetName",
"datasetRecords": {
"SampleKey1": {
"oldValue": "oldValue1",
"newValue": "newValue1",
"op": "replace"
},
"SampleKey2": {
"oldValue": "oldValue2",
"newValue": "newValue2",
"op": "replace"
},..
}
}
Amazon Cognito expects the return value of the function in the same format as the input. A complete
example is provided below.
Some key points to keep in mind when writing functions for the Sync Trigger event:
• When your Lambda function is invoked during UpdateRecords, it must respond within 5 seconds. If it
does not, the Amazon Cognito Sync service throws a LambdaSocketTimeoutException exception. It
is not possible to increase this timeout value.
• If you get a LambdaThrottledException exception, you should retry the sync operation (update
records).
• Amazon Cognito will provide all the records present in the dataset as input to the function.
• Records updated by the app user will have the 'op' field set as “replace” and the records deleted will
have 'op' field as "remove".
• You can modify any record, even if it is not updated by the app user.
• All the fields except the datasetRecords are read only and should not be changed. Changing these
fields will result in a failure to update the records.
• To modify the value of a record, simply update the value and set the 'op' to "replace".
• To remove a record, either set the ‘op’ to remove or set the value to null.
• To add a record, simply add a new record to the datasetRecords array.
• Any omitted record in the response will be ignored for the update.
Here is a sample Lambda function showing how to access, modify and remove the data.
console.log('Loading function');
277
Amazon Cognito Developer Guide
Amazon Cognito Events
//Remove a key
if('SampleKey2' in event.datasetRecords){
event.datasetRecords.SampleKey2.op = 'remove';
}
//Add a key
if(!('SampleKey3' in event.datasetRecords)){
event.datasetRecords.SampleKey3={'newValue':'ModifyValue3', 'op' : 'replace'};
}
}
context.done(null, event);
};
278
Amazon Cognito Developer Guide
Data Protection
Security is a shared responsibility between AWS and you. The shared responsibility model describes this
as security of the cloud and security in the cloud:
• Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in
the AWS Cloud. AWS also provides you with services that you can use securely. Third-party auditors
regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs.
To learn about the compliance programs that apply to Amazon Cognito, see AWS Services in Scope by
Compliance Program.
• Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also
responsible for other factors including the sensitivity of your data, your company’s requirements, and
applicable laws and regulations
This documentation helps you understand how to apply the shared responsibility model when using
Amazon Cognito. It shows you how to configure Amazon Cognito to meet your security and compliance
objectives. You also learn how to use other AWS services that help you to monitor and secure your
Amazon Cognito resources.
Contents
• Data Protection in Amazon Cognito (p. 279)
• Identity and Access Management in Amazon Cognito user pools (p. 280)
• Logging in and Monitoring in Amazon Cognito (p. 292)
• Compliance Validation for Amazon Cognito (p. 301)
• Resilience in Amazon Cognito (p. 302)
• Infrastructure Security in Amazon Cognito (p. 303)
• Configuration and Vulnerability Analysis in Amazon Cognito user pools (p. 303)
• Security Best Practices for Amazon Cognito user pools (p. 303)
For data protection purposes, we recommend that you protect AWS account credentials and set up
individual user accounts with AWS Identity and Access Management (IAM). That way each user is given
only the permissions necessary to fulfill their job duties. We also recommend that you secure your data
in the following ways:
279
Amazon Cognito Developer Guide
Data Encryption
We strongly recommend that you never put sensitive identifying information, such as your customers'
account numbers, into free-form fields such as a Name field. This includes when you work with Amazon
Cognito or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter
into Amazon Cognito or other services might get picked up for inclusion in diagnostic logs. When you
provide a URL to an external server, don't include credentials information in the URL to validate your
request to that server.
Data-Encryption
Data encryption typically falls into two categories: encryption at rest and encryption in transit.
Encryption at Rest
Data within Amazon Cognito is encrypted at rest in accordance with industry standards.
Encryption in Transit
All requests to Amazon Cognito must be made over the Transport Layer Security protocol (TLS). Clients
must support Transport Layer Security (TLS) 1.0 or later. We recommend TLS 1.2 or later. Clients must
also support cipher suites with perfect forward secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or
Elliptic Curve Ephemeral Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support
these modes.
Note
Amazon Cognito encrypts customer content internally and doesn't support customer provided
keys.
In Amazon Cognito identity pools (federated identities), it is possible to restrict an IAM user's access to a
specific identity pool, using the Amazon Resource Name (ARN) format, as in the following example. For
more information about ARNs, see IAM Identifiers.
arn:aws:cognito-identity:REGION:ACCOUNT_ID:identitypool/IDENTITY_POOL_ID
280
Amazon Cognito Developer Guide
Example Policies
In Amazon Cognito Sync, customers can also restrict access by the identity pool ID, identity ID, and
dataset name.
For APIs that operate on an identity pool, the identity pool ARN format is the same as for Amazon
Cognito Federated Identities, except that the service name is cognito-sync instead of cognito-
identity:
arn:aws:cognito-sync:REGION:ACCOUNT_ID:identitypool/IDENTITY_POOL_ID
For APIs that operate on a single identity, such as RegisterDevice, you can refer to the individual
identity by the following ARN format:
arn:aws:cognito-sync:REGION:ACCOUNT_ID:identitypool/IDENTITY_POOL_ID/identity/IDENTITY_ID
For APIs that operate on datasets, such as UpdateRecords and ListRecords, you can refer to the
individual dataset using the following ARN format:
arn:aws:cognito-sync:REGION:ACCOUNT_ID:identitypool/IDENTITY_POOL_ID/identity/IDENTITY_ID/
dataset/DATASET_NAME
For Amazon Cognito Your User Pools, it is possible to restrict an IAM user's access to a specific user pool,
using the following ARN format:
arn:aws:cognito-idp:REGION:ACCOUNT_ID:userpool/USER_POOL_ID
Example Policies
Restricting Console Access to a Specific Identity Pool
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cognito-identity:ListIdentityPools"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"cognito-identity:*"
],
"Resource": "arn:aws:cognito-identity:us-east-1:0123456789:identitypool/us-
east-1:1a1a1a1a-ffff-1111-9999-12345678"
},
{
"Effect": "Allow",
"Action": [
"cognito-sync:*"
],
"Resource": "arn:aws:cognito-sync:us-east-1:0123456789:identitypool/us-
east-1:1a1a1a1a-ffff-1111-9999-12345678"
}
281
Amazon Cognito Developer Guide
Managed Policies
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cognito-sync:ListRecords",
"cognito-sync:UpdateRecords"
],
"Resource": "arn:aws:cognito-sync:us-east-1:0123456789:identitypool/us-
east-1:1a1a1a1a-ffff-1111-9999-12345678/identity/*/dataset/UserProfile"
}
]
}
Managed Policies
A number of policies are available via the IAM Console that customers can use to grant access to Amazon
Cognito:
• AmazonCognitoPowerUser - Permissions for accessing and managing all aspects of your identity pools.
• AmazonCognitoReadOnly - Permissions for read only access to your identity pools.
• AmazonCognitoDeveloperAuthenticatedIdentities - Permissions for your authentication system to
integrate with Amazon Cognito.
These policies are maintained by the Amazon Cognito team, so even as new APIs are added your IAM
users will continue to have the same level of access.
Note
Because creating a new identity pool also requires creating IAM roles, any IAM user you want to
be able to create new identity pools with must have the admin policy applied as well.
• GetId
• GetOpenIdToken
• GetCredentialsForIdentity
• UnlinkIdentity
• ChangePassword
• ConfirmDevice
• ConfirmForgotPassword
282
Amazon Cognito Developer Guide
Using Service-Linked Roles
• ConfirmSignUp
• DeleteUser
• DeleteUserAttributes
• ForgetDevice
• ForgotPassword
• GetDevice
• GetUser
• GetUserAttributeVerificationCode
• GlobalSignOut
• InitiateAuth
• ListDevices
• ResendConfirmationCode
• RespondToAuthChallenge
• SetUserSettings
• SignUp
• UpdateDeviceStatus
• UpdateUserAttributes
• VerifyUserAttribute
Contents
• Using Service-Linked Roles for Amazon Cognito (p. 283)
• Authentication with a User Pool (p. 286)
A service-linked role makes setting up Amazon Cognito easier because you don’t have to manually add
the necessary permissions. Amazon Cognito defines the permissions of its service-linked roles, and unless
defined otherwise, only Amazon Cognito can assume its roles. The defined permissions include the trust
policy and the permissions policy, and that permissions policy cannot be attached to any other IAM
entity.
You can delete a service-linked role only after first deleting their related resources. This protects your
Amazon Cognito resources because you can't inadvertently remove permission to access the resources.
For information about other services that support service-linked roles, see AWS Services That Work with
IAM and look for the services that have Yes in the Service-Linked Role column. Choose a Yes with a link
to view the service-linked role documentation for that service.
• AmazonCognitoIdpEmailService – Allows Amazon Cognito user pools service to use your Amazon SES
identities for sending email.
283
Amazon Cognito Developer Guide
Using Service-Linked Roles
• AmazonCognitoIdp – Allows Amazon Cognito user pools to publish events and configure endpoints
for your Amazon Pinpoint projects.
The AmazonCognitoIdpEmailService service-linked role trusts the following services to assume the
role:
• email.cognito-idp.amazonaws.com
The role permissions policy allows Amazon Cognito to complete the following actions on the specified
resources:
The policy denies Amazon Cognito the ability to complete the following actions on the specified
resources:
Denied Actions
• Action: ses:List*
• Resource: *
With these permissions, Amazon Cognito can use your verified email addresses in Amazon SES only to
email your users. Amazon Cognito emails your users when they perform certain actions in the client app
for a user pool, such as signing up or resetting a password.
You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or
delete a service-linked role. For more information, see Service-Linked Role Permissions in the IAM User
Guide.
AmazonCognitoIdp
The AmazonCognitoIdp service-linked role trusts the following services to assume the role:
• email.cognito-idp.amazonaws.com
The role permissions policy allows Amazon Cognito to complete the following actions on the specified
resources:
• Action: cognito-idp:Describe
• Resource: *
With this permission, Amazon Cognito can call Describe Amazon Cognito API operations for you.
Note
When you integrate Amazon Cognito with Amazon Pinpoint using createUserPoolClient
and updateUserPoolClient, resource permissions will be added to the SLR as an
inline policy. The inline policy will provide mobiletargeting:UpdateEndpoint and
mobiletargeting:PutEvents permissions. These permissions allow Amazon Cognito to
publish events and configure endpoints for Pinpoint projects you integrate with Cognito.
284
Amazon Cognito Developer Guide
Using Service-Linked Roles
If you delete this service-linked role, and then need to create it again, you can use the same process to
recreate the role in your account. When you configure a user pool to use your Amazon SES configuration
to handle email delivery, Amazon Cognito creates the service-linked role for you again.
Before Amazon Cognito can create this role, the IAM permissions that you use to set up your user pool
must include the iam:CreateServiceLinkedRole action. For more information about updating
permissions in IAM, see Changing Permissions for an IAM User in the IAM User Guide.
Remember to do these actions in each AWS region that contains a user pool that uses the role.
Note
If the Amazon Cognito service is using the role when you try to delete the resources, then the
deletion might fail. If that happens, wait for a few minutes and try the operation again.
1. Sign in the AWS Management Console and open the Amazon Cognito console at https://
console.aws.amazon.com/cognito.
2. Choose Manage User Pools.
3. On the Your User Pools page, choose the user pool that you want to delete.
4. Choose Delete pool.
5. In the Delete user pool window, type delete, and choose Delete pool.
To update an Amazon Cognito user pool to use the default email functionality
1. Sign in the AWS Management Console and open the Amazon Cognito console at https://
console.aws.amazon.com/cognito.
2. Choose Manage User Pools.
3. On the Your User Pools page, choose the user pool that you want to update.
285
Amazon Cognito Developer Guide
Authentication
Use the IAM console, the AWS CLI, or the AWS API to delete AmazonCognitoIdpEmailService or
AmazonCognitoIdpEmailService service-linked roles. For more information, see Deleting a Service-Linked
Role in the IAM User Guide.
After successful authentication, Amazon Cognito returns user pool tokens to your app. You can use the
tokens to grant your users access to your own server-side resources, or to the Amazon API Gateway. Or,
you can exchange them for AWS credentials to access other AWS services.
User pool token handling and management for your web or mobile app is provided on the client side
through Amazon Cognito SDKs. Likewise, the Mobile SDK for iOS and the Mobile SDK for Android
automatically refresh your ID and access tokens if there is a valid (non-expired) refresh token present,
and the ID and access tokens have a minimum remaining validity of 5 minutes. For information on the
SDKs, and sample code for JavaScript, Android, and iOS see Amazon Cognito User Pool SDKs.
After your app user successfully signs in, Amazon Cognito creates a session and returns an ID, access, and
refresh token for the authenticated user.
JavaScript
// Amazon Cognito creates a session which includes the id, access, and refresh tokens
of an authenticated user.
var authenticationData = {
Username : 'username',
Password : 'password',
};
var authenticationDetails = new
AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : 'us-east-1_ExaMPle',
ClientId : '1example23456789'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
286
Amazon Cognito Developer Guide
Authentication
Username : 'username',
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
/* Use the idToken for Logins Map when Federating User Pools with identity
pools or when passing through an Authorization Header to an API Gateway Authorizer */
var idToken = result.idToken.jwtToken;
},
onFailure: function(err) {
alert(err);
},
});
Android
// Session is an object of the type CognitoUserSession, and includes the id, access,
and refresh tokens for a user.
iOS - Swift
iOS - Objective-C
Topics
• User Pool Authentication Flow (p. 287)
A user authenticates by answering successive challenges until authentication either fails or the user
is issued tokens. With these two steps, which can be repeated to include different challenges, we can
support any custom authentication flow.
287
Amazon Cognito Developer Guide
Authentication
You can customize your authentication flow with AWS Lambda triggers. These triggers issue and verify
their own challenges as part of the authentication flow.
You can also use admin authentication flow for use on secure backend servers. You can use the user
migration authentication flow to allow user migration without requiring your users to reset their
passwords.
Note
We allow five failed sign-in attempts. After that we start temporary lockouts with exponentially
increasing times starting at 1 second and doubling after each failed attempt up to about 15
minutes. Attempts during a temporary lockout period are ignored. After the temporary lockout
period, if the next attempt fails, a new temporary lockout starts with twice the duration as the
last. Waiting about 15 minutes without any attempts will also reset the temporary lockout.
Please note that this behavior is subject to change.
Topics
• Client-Side Authentication Flow (p. 288)
• Server-Side Authentication Flow (p. 289)
• Custom Authentication Flow (p. 289)
• Built-in Authentication Flow and Challenges (p. 290)
• Custom Authentication Flow and Challenges (p. 290)
• Use SRP Password Verification in Custom Authentication Flow (p. 290)
• Admin authentication flow (p. 291)
• User migration authentication flow (p. 291)
1. The user enters their user name and password into the app.
2. The app calls the InitiateAuth operation with the user's user name and SRP details.
288
Amazon Cognito Developer Guide
Authentication
Note
The app generates the SRP details by using the Amazon Cognito SRP support in the Android,
iOS, and JavaScript SDKs.
3. The app calls the RespondToAuthChallenge operation. If the call succeeds, it returns the user's
tokens, and the authentication flow is complete.
For server-side apps, user pool authentication is similar to that for client-side apps, except for the
following:
• The server-side app calls the AdminInitiateAuth API operation (instead of InitiateAuth). This
operation requires AWS admin credentials. This operation returns the authentication parameters.
• Once it has the authentication parameters, the app calls the AdminRespondToAuthChallenge API
operation (instead of RespondToAuthChallenge), which also requires AWS admin credentials.
The custom authentication flow is designed to allow for a series of challenge and response cycles that
can be customized to meet different requirements. The flow starts with a call to the InitiateAuth
API operation that indicates the type of authentication that will be used and provides any initial
authentication parameters. Amazon Cognito will respond to the InitiateAuth call with one of the
following:
If Amazon Cognito responds to the InitiateAuth call with a challenge, the app gathers more input
and calls the RespondToAuthChallenge operation, providing the challenge responses and passing
289
Amazon Cognito Developer Guide
Authentication
back the session. Amazon Cognito responds to the RespondToAuthChallenge call similarly to the
InitiateAuth call, providing tokens if the user is signed in, another challenge, or an error. If another
challenge is returned, the sequence repeats with the app calling RespondToAuthChallenge until
the user is signed in or an error is returned. More details are provided in the API documentation for the
InitiateAuth and RespondToAuthChallenge API operations.
• The DefineAuthChallenge Lambda trigger takes as input a session array of previous challenges
and responses. It then outputs the next challenge name and Booleans that indicate whether the user
is authenticated (and should be granted tokens) or not. 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. CreateAuthChallenge is called when
DefineAuthChallenge returns CUSTOM_CHALLENGE as the next challenge, and the next type of
challenge is passed 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.
• To initiate SRP password verification in a custom flow, the app calls InitiateAuth with
CUSTOM_AUTH as the Authflow. It includes in the AuthParameters map SRP_A: (the SRP A value)
and CHALLENGE_NAME: SRP_A.
• The DefineAuthChallenge Lambda trigger is invoked with an initial session of challengeName:
SRP_A and challengeResult: true, and should respond with challengeName:
PASSWORD_VERIFIER, issueTokens: false, and failAuthentication: false.
• The app next needs to call RespondToAuthChallenge with challengeName:
PASSWORD_VERIFIER and the other parameters required for SRP in the challengeResponses map.
• If the password is verified, the DefineAuthChallenge Lambda trigger is invoked with a
second session of challengeName: PASSWORD_VERIFIER and challengeResult: true.
At that point the DefineAuthChallenge Lambda trigger can respond with challengeName:
CUSTOM_CHALLENGE to start the custom challenge.
290
Amazon Cognito Developer Guide
Authentication
• If MFA is enabled for a user, it is handled automatically after the password is verified.
Note
The Amazon Cognito hosted sign-in webpage does not support the custom authentication flow.
For more information about the Lambda triggers, including sample code, see Customizing User Pool
Workflows with Lambda Triggers (p. 64).
Note
The Amazon Cognito hosted sign-in web page does not support the custom authentication flow.
AdminInitiateAuth Request {
"AuthFlow":"ADMIN_USER_PASSWORD_AUTH",
"AuthParameters":{
"USERNAME":"<username>",
"PASSWORD":"<password>"
},
"ClientId":"<clientId>",
"UserPoolId":"<userPoolId>"
}
These admin authentication operations require developer credentials and use the AWS Signature
Version 4 (SigV4) signing process. These operations are available in standard AWS SDKs including
Node.js, which is convenient for use in Lambda functions. In order to use these operations and have
them accept passwords in plaintext, you must enable them for the app in the console. Alternatively,
you can pass ADMIN_USER_PASSWORD_AUTH for the ExplicitAuthFlow parameter in calls to
CreateUserPoolClient or UpdateUserPoolClient. The ADMIN_USER_PASSWORD_AUTH AuthFlow
is not accepted for the InitiateAuth and RespondToAuthChallenge operations.
When you have completed migrating all your users, we recommend switching flows to the more secure
SRP flow. The SRP flow does not send any passwords over the network.
291
Amazon Cognito Developer Guide
Logging and Monitoring
To learn more about Lambda triggers see Customizing User Pool Workflows with Lambda
Triggers (p. 64).
For more information about migrating users with a Lambda trigger see Importing Users into User Pools
With a User Migration Lambda Trigger (p. 130).
• Amazon CloudWatch Metrics – With CloudWatch metrics you can monitor, report and take automatic
actions in case of an event in near real time. For example, you can create CloudWatch dashboards
on the provided metrics to monitor your Amazon Cognito user pools, or you can create CloudWatch
alarms on the provided metrics to notify you on breach of a set threshold.
• AWS CloudTrail – With CloudTrail you can capture API calls from the Amazon Cognito console and
from code calls to the Amazon Cognito API operations. For example, when a user authenticates,
CloudTrail can record details such as the IP address in the request, who made the request, and when it
was made.
Topics
• Tracking quotas and usage in CloudWatch and Service Quotas (p. 292)
• Metrics for Amazon Cognito user pools (p. 293)
• Dimensions for Amazon Cognito user pools (p. 297)
• Use the Service Quotas console to track metrics (p. 298)
• Use the CloudWatch console to track metrics (p. 298)
• Create a CloudWatch alarm for a quota (p. 299)
• Logging Amazon Cognito API Calls with AWS CloudTrail (p. 299)
You can use Service Quotas to view and manage your Amazon Cognito user pools quota usage. The
Service Quotas console has three features, view service quotas, request a service quota increase, and
view current utilization. You can use the first feature to view quotas and see whether the quota is
adjustable. You can use the second feature to request a Service Quotas increase. You can use the last
feature to view quota utilization. This feature is only available after your account has been active for
awhile. For more information on viewing quotas in the Service Quotas console, see Viewing Service
Quotas.
Note
Amazon Cognito metrics are available at 5 minute intervals. For more information about
retention periods in CloudWatch, visit the Amazon CloudWatch FAQ page.
292
Amazon Cognito Developer Guide
Metrics for Amazon Cognito user pools
Metric Description
Units: Count
293
Amazon Cognito Developer Guide
Metrics for Amazon Cognito user pools
Metric Description
Metric dimension: UserPool, UserPoolClient
Units: Count
Units: Count
294
Amazon Cognito Developer Guide
Metrics for Amazon Cognito user pools
Metric Description
Units: Count
Units: Count
295
Amazon Cognito Developer Guide
Metrics for Amazon Cognito user pools
Metric Description
Units: Count
Units: Count
296
Amazon Cognito Developer Guide
Dimensions for Amazon Cognito user pools
Metric Description
Units: Count
Units: Count
Units: Count
297
Amazon Cognito Developer Guide
Use the Service Quotas console to track metrics
Dimension Description
To view Amazon Cognito user pools service quotas utilization, complete the following steps.
Note
Metrics that haven't had any new data points in the past two weeks don't appear in the console.
They also don't appear when you enter their metric name or dimension names in the search box
298
Amazon Cognito Developer Guide
Create a CloudWatch alarm for a quota
in the All metrics tab in the console, and they are not returned in the results of a list-metrics
command. The best way to retrieve these metrics is with the get-metric-data or get-
metric-statistics commands in the AWS CLI.
To learn more about CloudTrail, including how to configure and enable it, see the AWS CloudTrail User
Guide.
You can also create Amazon CloudWatch alarms for specific CloudTrail events. For example, you can set
up CloudWatch to trigger an alarm if an identity pool configuration is changed. For more information,
see Creating CloudWatch Alarms for CloudTrail Events: Examples.
For an ongoing record of events in your AWS account, including events for Amazon Cognito, create a
trail. A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create
a trail in the console, the trail applies to all Regions. The trail logs events from all Regions in the AWS
partition and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you can
299
Amazon Cognito Developer Guide
Logging Amazon Cognito API Calls with AWS CloudTrail
configure other AWS services to further analyze and act upon the event data collected in CloudTrail logs.
For more information, see:
Amazon Cognito supports logging for all of the actions listed on the User Pool Actions page as events in
CloudTrail log files. Amazon Cognito records UserSub but not UserName in CloudTrail logs for requests
that are specific to a user. You can find a user for a given UserSub by calling the ListUsers API, and
using a filter for sub.
Note
Hosted UI and federation calls are currently not included in CloudTrail.
• CreateIdentityPool
• DeleteIdentityPool
• DescribeIdentityPool
• GetIdentityPoolRoles
• ListIdentityPools
• SetIdentityPoolRoles
• UpdateIdentityPool
• BulkPublish
• DescribeIdentityPoolUsage
• GetBulkPublishDetails
• GetCognitoEvents
• GetIdentityPoolConfiguration
• ListIdentityPoolUsage
• SetCognitoEvents
• SetIdentityPoolConfiguration
Every event or log entry contains information about who generated the request. The identity
information helps you determine the following:
• Whether the request was made with root or IAM user credentials.
• Whether the request was made with temporary security credentials for a role or federated user.
• Whether the request was made by another AWS service.
300
Amazon Cognito Developer Guide
Compliance Validation
The following example is a log entry for a request for the CreateIdentityPool action. The request
was made by an IAM user named Alice.
{
"eventVersion":"1.03",
"userIdentity":{
"type":"IAMUser",
"principalId":"PRINCIPAL_ID",
"arn":"arn:aws:iam::123456789012:user/Alice",
"accountId":"123456789012",
"accessKeyId":"['EXAMPLE_KEY_ID']",
"userName":"Alice"
},
"eventTime":"2016-01-07T02:04:30Z",
"eventSource":"cognito-identity.amazonaws.com",
"eventName":"CreateIdentityPool",
"awsRegion":"us-east-1",
"sourceIPAddress":"127.0.0.1",
"userAgent":"USER_AGENT",
"requestParameters":{
"identityPoolName":"TestPool",
"allowUnauthenticatedIdentities":true,
"supportedLoginProviders":{
"graph.facebook.com":"000000000000000"
}
},
"responseElements":{
"identityPoolName":"TestPool",
"identityPoolId":"us-east-1:1cf667a2-49a6-454b-9e45-23199EXAMPLE",
"allowUnauthenticatedIdentities":true,
"supportedLoginProviders":{
"graph.facebook.com":"000000000000000"
}
},
"requestID":"15cc73a1-0780-460c-91e8-e12ef034e116",
"eventID":"f1d47f93-c708-495b-bff1-cb935a6064b2",
"eventType":"AwsApiCall",
"recipientAccountId":"123456789012"
}
For a list of AWS services in scope of specific compliance programs, see AWS Services in Scope by
Compliance Program. For general information, see AWS Compliance Programs.
You can download third-party audit reports using AWS Artifact. For more information, see Downloading
Reports in AWS Artifact.
301
Amazon Cognito Developer Guide
Resilience
Your compliance responsibility when using Amazon Cognito is determined by the sensitivity of your data,
your company's compliance objectives, and applicable laws and regulations. AWS provides the following
resources to help with compliance:
• Security and Compliance Quick Start Guides – These deployment guides discuss architectural
considerations and provide steps for deploying security- and compliance-focused baseline
environments on AWS.
• Architecting for HIPAA Security and Compliance Whitepaper – This whitepaper describes how
companies can use AWS to create HIPAA-compliant applications.
• AWS Compliance Resources – This collection of workbooks and guides might apply to your industry
and location.
• Evaluating Resources with Rules in the AWS Config Developer Guide – AWS Config; assesses how well
your resource configurations comply with internal practices, industry guidelines, and regulations.
• AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS
that helps you check your compliance with security industry standards and best practices.
For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure.
Topics
• Regional Data Considerations (p. 302)
• If the default no-reply@verificationemail.com email address setting is used for routing verification of
emails addresses with Amazon Cognito user pools, emails are routed through the US West (Oregon)
Region.
• If a different email address is used to configure Amazon Simple Email Service (Amazon SES) with
Amazon Cognito user pools, that email address is routed through the AWS Region associated with the
email address in Amazon SES.
• SMS messages from Amazon Cognito user pools are routed through the same region AWS SNS unless
noted otherwise on Configuring Email or Phone Verification.
• If Amazon Pinpoint analytics are used with Amazon Cognito user pools, the event data is routed to the
US East (N. Virginia) Region.
Note
Amazon Pinpoint is available in several AWS Regions in North America, Europe, Asia, and
Oceania. Amazon Pinpoint regions include the Amazon Pinpoint API. If a Amazon Pinpoint
region is supported by Amazon Cognito, then Amazon Cognito will send events to Amazon
Pinpoint projects within the same Amazon Pinpoint region. If a region isn't supported by
302
Amazon Cognito Developer Guide
Infrastructure Security
Amazon Pinpoint, then Amazon Cognito will only support sending events in us-east-1. For
Amazon Pinpoint detailed region information, see Amazon Pinpoint endpoints and quotas and
Using Amazon Pinpoint Analytics with Amazon Cognito User Pools.
You use AWS published API calls to access Amazon Cognito through the network. Clients must support
Transport Layer Security (TLS) 1.0 or later. We recommend TLS 1.2 or later. Clients must also support
cipher suites with perfect forward secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve
Ephemeral Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support these modes.
Additionally, requests must be signed using an access key ID and a secret access key that is associated
with an IAM principal. Or you can use the AWS Security Token Service (AWS STS) to generate temporary
security credentials to sign requests.
Topics
• Adding Multi-Factor Authentication (MFA) to a User Pool (p. 303)
• Adding Advanced Security to a User Pool (p. 307)
303
Amazon Cognito Developer Guide
Adding Multi-Factor Authentication (MFA)
With adaptive authentication, you can configure your user pool to require second factor authentication
in response to an increased risk level. To add adaptive authentication to your user pool, see Adding
Advanced Security to a User Pool (p. 307).
When multi-factor authentication (MFA) is set to requiredfor a user pool, all users must complete
MFA to sign in. Each user needs at least one MFA factor such as SMS or TOTP setup to sign in. To avoid
having users blocked from signing in when MFA is required, you must include the MFA setup in user
onboarding.
If you enable SMS as an MFA factor, you can require phone numbers and have them verified during sign-
up. If you have MFA set to required and only support SMS as a factor, most users will need to have a
phone number. Users without phone numbers will need your support to add a phone number to their
profile before they can sign in. You can use unverified phone numbers for SMS MFA. These numbers will
have a verified status after multi-factor authentication succeeds.
Setting up users in user pools for TOTP tokens occurs during initial sign-in. The setting to enable or
disable TOTP as an MFA factor for a user pool controls whether users can set up TOTP for themselves. If
your users have set up TOTP, they can use it for MFA even if TOTP is later disabled for the user pool.
Topics
• Prerequisites (p. 304)
• Configuring Multi-Factor Authentication (p. 304)
• SMS Text Message MFA (p. 305)
• TOTP Software Token MFA (p. 306)
Prerequisites
Before you begin, you need the following:
• You can only choose MFA as Required in the Amazon Cognito user pool console when you initially
create a user pool. The SetUserPoolMfaConfig API operation can be used to set MFA to required for
existing user pools.
• Phone numbers must be verified if MFA is enabled and SMS text message is chosen as a second factor.
• Advanced security features require that MFA is enabled, and set as optional in the Amazon Cognito
user pool console. For more information, see Adding Advanced Security to a User Pool (p. 307).
304
Amazon Cognito Developer Guide
Adding Multi-Factor Authentication (MFA)
3. Choose Optional to enable MFA on a per-user basis or if you are using the risk-based adaptive
authentication. For more information on adaptive authentication, see Adding Advanced Security to a
User Pool (p. 307).
4. Choose which second factors to support in your app. Your users can use SMS text message or Time-
based One-time Password as a second factor. We recommend using TOTP, which allows SMS to be
used as a password recovery mechanism rather than as an authentication factor.
5. If you're using SMS text messages as a second factor and you don't have an IAM role defined with
this permission, then you can create one in the console. Choose Create role to create an IAM
role that allows Amazon Cognito to send SMS messages to your users on your behalf. For more
information, see IAM Roles.
6. Choose Save changes.
If a user no longer has access to their device where the SMS text message MFA codes are sent, they
must request help from your customer service office. An administrator with necessary AWS account
permissions can change the user's phone number, but only through the AWS CLI or the API.
When a user successfully goes through the SMS text message MFA flow, their phone number is also
marked as verified.
305
Amazon Cognito Developer Guide
Adding Multi-Factor Authentication (MFA)
Note
SMS for MFA is charged separately. (There is no charge for sending verification codes to
email addresses.) For information about Amazon SNS pricing, see Worldwide SMS Pricing. For
the current list of countries where SMS messaging is available, see Supported Regions and
Countries.
Important
To ensure that SMS messages are sent to verify phone numbers and for SMS text message MFA,
you must request an increased spend limit from Amazon SNS.
Amazon Cognito uses Amazon SNS for sending SMS messages to users. The number of SMS
messages Amazon SNS delivers is subject to spend limits. Spend limits can be specified for an
AWS account and for individual messages, and the limits apply only to the cost of sending SMS
messages.
The default spend limit per account (if not specified) is 1.00 USD per month. If you want to raise
the limit, submit an SNS Limit Increase case in the AWS Support Center. For New limit value,
enter your desired monthly spend limit. In the Use Case Description field, explain that you're
requesting an SMS monthly spend limit increase.
To add MFA to your user pool, see Adding Multi-Factor Authentication (MFA) to a User Pool (p. 303).
You can enable TOTP MFA for your user pool in the Amazon Cognito console, through the Amazon
Cognito hosted UI, or using Amazon Cognito API operations. At the user pool level, you can configure
MFA and enable TOTP MFA by calling SetUserPoolMfaConfig.
Note
If TOTP software token MFA isn't enabled for the user pool, users can't be associated or verified
with the token. They receive this SoftwareTokenMFANotFoundException exception:
"Software Token MFA has not been enabled by the userPool." Users who have previously
associated and verified a TOTP token can continue to use it for MFA if the software token MFA is
later disabled for the user pool.
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.
To add MFA to your user pool, see Adding Multi-Factor Authentication (MFA) to a User Pool (p. 303).
1. When your user chooses TOTP software token MFA, call AssociateSoftwareToken to return a unique
generated shared secret key code for the user account. The request for this API method takes an
access token or a session string, but not both. As a convenience, you can distribute the secret key as a
quick response (QR) code.
2. The key code or QR code appears on your app. Your user needs to enter it into a TOTP-generating app
such as Google Authenticator.
3. Your user enters the key code into the TOTP-generating app to associate a new account with your
client app.
306
Amazon Cognito Developer Guide
Adding Advanced Security
1. After a new TOTP account is associated with your app, it generates a temporary password.
2. Your user enters the temporary password into your app, which responds with a call to
VerifySoftwareToken. On the Amazon Cognito service server, a TOTP code is generated and compared
with your user's temporary password. If they match, then the service marks it as verified.
3. If the code is correct, check that the time used is in the range and within the maximum number of
retries. Amazon Cognito also accepts TOTP tokens that are one 30-second window early or late to
account for clock skew. If your user passes all of the steps, the verification is complete.
If the code is wrong, the verification cannot be finished and your user can either try again or cancel.
We recommend that your user sync the time of their TOTP-generating app.
1. Your user enters their user name and password to sign in to your client app.
2. The TOTP MFA challenge is invoked, and your user is prompted by your app to enter a temporary
password.
3. Your user gets the temporary password from an associated TOTP-generating app.
4. 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 should be called to get a response to the new
TOTP authentication challenge.
5. If the token is verified by Amazon Cognito, the sign-in is successful and your user continues with the
authentication flow.
1. Your client app should ask your user to enter their password.
2. If the password is correct, remove the TOTP token.
Note
A delete TOTP software token operation is not currently available in the API. This
functionality is planned for a future release. Use SetUserMFAPreference to disable TOTP MFA
for an individual user.
Topics
307
Amazon Cognito Developer Guide
Adding Advanced Security
Prerequisites
Before you begin, you need:
• A user pool with an app client. For more information, see Getting Started with User Pools (p. 17).
• 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 Multi-Factor Authentication
(MFA) to a User Pool (p. 303).
• If you're using email for notifications, go to the Amazon SES console to configure and verify an email
address or domain to use with your notification emails. For more information about Amazon SES, see
Verifying Identities in Amazon SES.
We recommend keeping the advanced security features in audit mode for two weeks before
enabling actions. This allows Amazon Cognito to learn the usage patterns of your app users.
3. From the drop-down list, choose What app client do you want to customize settings for?. The
default is to leave your settings as global for all app clients.
4. For Which action do you want to take with the compromised credentials?, choose Allow or Block
use.
5. Choose Customize when compromised credentials are blocked to select which events should
trigger compromised credentials checks:
• Sign-in
• Sign-up
• Password change
6. Choose how to respond to malicious sign-in attempts under How do you want to use adaptive
authentication for sign-in attempts rated as low, medium and high risk?. You can allow or block
the sign-in attempt, or require additional challenges before allowing the sign-in.
To send email notifications when anomalous sign-in attempts are detected, choose Notify users .
308
Amazon Cognito Developer Guide
Adding Advanced Security
7. If you chose Notify users in the previous step, then you can customize the email notification
messages by using the Notification message customization form:
8. Choose Customize to customize adaptive authentication notifications with both HTML and plaintext
email versions. To learn more about email templates, see Message Templates (p. 165).
9. Type any IP addresses that you want to Always allow, or Always block, regardless of the advanced
security risk assessment. Specify the IP address ranges in CIDR notation (such as 192.168.100.0/24).
10. Choose Save changes.
309
Amazon Cognito Developer Guide
Adding Advanced Security
From the Advanced security page in the Amazon Cognito console, you can choose whether to allow,
or block the user if compromised credentials are detected. Blocking requires users to choose another
password. Choosing Allow publishes all attempted uses of compromised credentials to Amazon
CloudWatch. For more information, see Viewing Advanced Security Metrics (p. 313).
You can also choose whether Amazon Cognito checks for compromised credentials during sign-in, sign-
up, and password changes.
Note
Currently, Amazon Cognito doesn't check for compromised credentials for sign-in operations
with Secure Remote Password (SRP) flow, which doesn't send the password during sign-in. Sign-
ins that use the AdminInitiateAuth API with ADMIN_NO_SRP_AUTH flow and the InitiateAuth
API with USER_PASSWORD_AUTH flow are checked for compromised credentials.
To add compromised credentials protections to your user pool, see Adding Advanced Security to a User
Pool (p. 307).
Amazon Cognito publishes sign-in attempts, their risk levels, and failed challenges to Amazon
CloudWatch. For more information, see Viewing Advanced Security Metrics (p. 313).
To add adaptive authentication to your user pool, see Adding Advanced Security to a User Pool (p. 307).
Topics
• Adaptive Authentication Overview (p. 311)
• Creating a Device Fingerprint (p. 311)
• Viewing User Event History (p. 311)
• Providing Event Feedback (p. 313)
• Sending Notification Messages (p. 313)
310
Amazon Cognito Developer Guide
Adding Advanced Security
For each risk level, you can choose from the following options:
Option Action
Note
*Phone numbers don't need to be verified to be used for SMS as a second authentication factor.
For information on enabling advanced security from your web or mobile app, see Enabling User Pool
Advanced Security from Your App (p. 315).
Collect user context data from the client side when your app is calling Amazon Cognito from your server.
The following is an example that uses the JavaScript SDK method getData.
We recommend incorporating the latest Amazon Cognito SDK into your app. This enables adaptive
authentication to collect device fingerprinting information—such as device ID, model, and time zone. For
more information about Amazon Cognito SDKs, see Install a user pool SDK.
311
Amazon Cognito Developer Guide
Adding Advanced Security
Each sign-in event has an event ID, context data such as location, device details, and risk detection
results associated with it.
You can correlate the event id to the token issued as well. The issued token, such as the ID token and
access token, carries this event ID in its payload. Even using the refresh token persists the original event
ID. The original event ID can be traced back to the event ID of the sign-in event that resulted in issuing
the Amazon Cognito tokens. This enables you to trace usage of a token within your system to a particular
authentication event.
312
Amazon Cognito Developer Guide
Adding Advanced Security
In the console, on the Users and groups tab, the sign-in history is listed, and if you click an entry, you
can mark the event as valid or invalid. You can also provide feedback through the user pool API method
AdminUpdateAuthEventFeedback, and through the AWS CLI command admin-update-auth-event-
feedback.
In the How do you want to use adaptive authentication for sign-in attempts rated as low, medium
and high risk? section choose Notify Users for the low, medium, and high-risk cases.
You can customize notification emails, and provide both plaintext and HTML versions. Choose Customize
from Adaptive authentication notification messages to customize your email notifications. To learn
more about email templates, see Message Templates (p. 165).
313
Amazon Cognito Developer Guide
Adding Advanced Security
• To filter by resource, choose the resource ID, and then choose Add to search.
• To filter by metric, choose the metric name, and then choose Add to search.
Amazon Cognito offers you two predefined groups of metrics for ready analysis in CloudWatch. By Risk
Classification identifies the granularity of the risk level for requests that Amazon Cognito identified as
risky, and the By Request Classification reflects metrics aggregated by request level.
314
Amazon Cognito Developer Guide
Adding Advanced Security
1. You might need to update your Amazon Cognito SDK to the latest version. For more information
about Amazon Cognito SDKs, see Install a user pool SDK.
2. To use the Auth SDK to enable the hosted UI, see the CognitoAuth JavaScript sample app.
3. Set AdvancedSecurityDataCollectionFlag to true. Also, set UserPoolId to your user pool ID.
4. In your application replace <region> with your AWS Region such as us-east-1, and add this source
reference to your JavaScript file:
<script src="https://amazon-cognito-assets.<region>.amazoncognito.com/amazon-cognito-
advanced-security-data.min.js"></script>
For more information, see Sample for Amazon Cognito Auth SDK for JavaScript.
1. You might need to update your Amazon Cognito SDK to the latest version. For more information
about Amazon Cognito SDKs, see Install a user pool SDK.
2. To use the Auth SDK to enable the hosted UI, see the CognitoAuth Android sample app.
3. Use { transitive = true; } while importing aws-android-sdk-cognitoauth through
Maven in Gradle.
compile "com.amazonaws:aws-android-sdk-cognitoidentityprovider-asf:1.0.0"
For more information, see AWS SDK for Android - Amazon Cognito Identity Provider ASF.
1. You might need to update your Amazon Cognito SDK to the latest version. For more information
about Amazon Cognito SDKs, see Install a user pool SDK.
2. To use the Auth SDK to enable the hosted UI, see the CognitoAuth iOS sample app.
3. To configure the Auth SDK by using Info.plist, add the PoolIdForEnablingASF key to your Amazon
Cognito user pool configuration, and set it to your user pool ID.
To configure the Auth SDK using AWSCognitoAuthConfiguration, use this initializer and specify
your user pool ID as userPoolIdForEnablingASF.
315
Amazon Cognito Developer Guide
Supported Resources
• Identify and organize your AWS resources. Many AWS services support tagging, so you can assign
the same tag to resources from different services to indicate that the resources are related. For
example, you could assign the same tag to an Amazon Cognito user pool that you assign to an Amazon
DynamoDB table.
• Track your AWS costs. You activate these tags on the AWS Billing and Cost Management dashboard.
AWS uses the tags to categorize your costs and deliver a monthly cost allocation report to you. For
more information, see Use Cost Allocation Tags in the AWS Billing and Cost Management User Guide.
• Control access to your resources based on the tags that are assigned to them. You control access by
specifying tag keys and values in the conditions for an AWS Identity and Access Management (IAM)
policy. For example, you could allow an IAM user to update a user pool, but only if the user pool has an
owner tag with a value of that user's name. For more information, see Controlling Access Using Tags in
the IAM User Guide.
You can use the AWS CLI or the Amazon Cognito API to add, edit, or delete tags for user pools and
identity pools. For user pools specifically, you can also manage tags by using the Amazon Cognito
console.
For tips on using tags, see the AWS Tagging Strategies post on the AWS Answers blog.
The following sections provide more information about tags for Amazon Cognito.
• User pools
• Identity pools
Tag Restrictions
The following basic restrictions apply to tags on Amazon Cognito resources:
316
Amazon Cognito Developer Guide
Managing Tags with the Console
For identity pools, the console does not include tagging features, so you must manage tags
programmatically. For example, you can use the AWS CLI.
1. Sign in the AWS Management Console and open the Amazon Cognito console at https://
console.aws.amazon.com/cognito.
2. Choose Manage User Pools.
3. On the Your User Pools page, choose the user pool that you want to add tags to.
4. In the navigation menu on the left, choose Tags.
5. Unless your user pool already has tags, choose Add tag to add the first one.
6. Specify values for Tag Key and Tag Value.
7. For each additional tag that you want to add, choose Add another tag.
8. When you are finished adding tags, choose Save changes.
On the Tags page, you can also edit the keys and values of any existing tags. To remove a tag, choose the
x in the top-right corner of the tag.
Assigning tags
Use the following commands to assign tags to your existing user pools and identity pools.
• resource-arn – The Amazon Resource Name (ARN) of the user pool that you are applying tags to. To
look up the ARN, choose the user pool in the Amazon Cognito console, and view the Pool ARN value
on the General settings tab.
• tags – The key-value pairs of the tags.
317
Amazon Cognito Developer Guide
Viewing tags
Assign tags to an identity pool by using tag-resource within the cognito-identity set of
commands:
• resource-arn – The Amazon Resource Name (ARN) of the identity pool that you are applying tags to.
To look up the ARN, choose the identity pool in the Amazon Cognito console, and choose Edit identity
pool. Then, at Identity pool ID, choose Show ARN.
• tags – The key-value pairs of the tags.
Viewing tags
Use the following commands to view the tags that you have assigned to your user pools and identity
pools.
View the tags that are assigned to a user pool by using list-tags-for-resource within the
cognito-idp set of commands:
View the tags that are assigned to an identity pool by using list-tags-for-resource within the
cognito-identity set of commands:
Removing tags
Use the following commands to remove tags from your user pools and identity pools.
Remove tags from a user pool by using untag-resource within the cognito-idp set of commands:
318
Amazon Cognito Developer Guide
Applying tags when you create resources
For the --tag-keys parameter, specify one or more tag keys, and do not include the tag values.
Remove tags from an identity pool by using untag-resource within the cognito-identity set of
commands:
For the --tag-keys parameter, specify one or more tag keys, and do not include the tag values.
Important
After you delete a user or identity pool, tags related to the deleted pool can still appear in the
console or API calls up to thirty days after the deletion.
When you create a user pool by using the create-user-pool command, you can specify tags with the
--user-pool-tags parameter:
When you create an identity pool by using the create-identity-pool command, you can specify tags
with the --identity-pool-tags parameter:
• TagResource
319
Amazon Cognito Developer Guide
API Actions for Identity Pool Tags
• ListTagsForResource
• UntagResource
• CreateUserPool
• TagResource
• ListTagsForResource
• UntagResource
• CreateIdentityPool
320
Amazon Cognito Developer Guide
Operation Quotas
Operation Quotas
Quota categorization
Amazon Cognito limits the number of operations, such as InitiateAuth or
RespondToAuthChallenge, that you can use to perform certain user actions in your applications.
These operations are grouped into categories of common use cases, such as UserAuthentication or
UserCreation. For a list of categorized operations, see Category operations (p. 322). The categories
make it easier to monitor usage and request quota increases.
Operation quotas are defined as the number of allowed requests per second (RPS) for all operations
within a category. The Amazon Cognito user pools service applies quotas to all operations in
each category. For example, the category UserCreation, includes four operations, SignUp,
ConfirmSignUp, AdminCreateUser, and AdminConfirmSignUp. It's allocated with a combined quota
of 30 RPS. Each operation within this category can call up to 30 RPS separately or combined if multiple
operations take place at the same time.
Note
The category quota is enforced for each AWS account across all user pools in an account and
region.
321
Amazon Cognito Developer Guide
Category operations
authentication challenges set up in developers’ apps. This elevated quota is sufficient to cover the large
majority of use cases. Beyond the three-time per authentication call threshold, the excess rate will be
counted towards the UserAuthentication category limit.
For example, if your quota for the UserAuthentication category is 80 RPS, you can call
RespondToAuthChallenge or AdminRespondToAuthChallenge up to 240 RPS (80 RPS x 3).
If the app is set up to have four rounds of challenge per authentication call and you have 70 sign-
ins per second, then total RespondToAuthChallenge will be 280 RPS (70 x 4), which is 40 RPS
above the quota. The extra 40 RPS will be added to 70 InitiateAuth calls. The total usage of
UserAuthentication category is 110 RPS (40 + 70). This exceeds the category quota set at 80 RPS so
this app would get throttled because it's 30 RPS above the category quota of 80 RPS.
Category operations
You can find the mappings between operations and their respective categories in the following table. All
categories listed in this table have adjustable quotas, which can be increased upon customer requests.
For more information, see API request rate quotas (p. 327). Adjustable quotas are applied at the
account level. There are some category operations that are subject to more constrained quota rules with
a lower limit threshold at the user pool level. You can find these categories with an asterisk in the table
and their quotas in the note below the table.
Note
The rate limit for each category depends on Monthly Active Users (MAUs). The default limits
support up to two million MAUs. It's not recommended to submit a limit increase request if you
have less than one million MAUs.
Category operation quotas, are applied across all users in a user pool. There are also per-user quotas that
apply to each user. For each user, you can make up to ten requests per second that are "read" operations
including signing in or getting profile or device information. You can also make up to ten requests per
second that are "write" operations, including updating profile information or MFA settings. You can't
change per-user quotas.
• InitiateAuth
UserAuthentication Operations that 120
authenticate
• RespondToAuthChallenge (sign-
in) a user.
• AdminInitiateAuth
• AdminRespondToAuthChallenge
These operations
are subject to
Operation special
handling (p. 321).
322
Amazon Cognito Developer Guide
Category operations
UserUpdate • AdminAddUserToGroup
The operations 25
that customers
• AdminDeleteUserAttributes
use to manage
• AdminUpdateUserAttributes
users and user
• AdminDeleteUser attributes,
• AdminDisableUser
• AdminEnableUser
• AdminLinkProviderForUser
• AdminDisableProviderForUser
• VerifyUserAttribute
• DeleteUser
• DeleteUserAttributes
• UpdateUserAttributes
• AdminUserGlobalSignOut
• GlobalSignOut
• AdminRemoveUserFromGroup
323
Amazon Cognito Developer Guide
Category operations
• AdminForgetDeviceOperations
UserResourceUpdate 25
that update
• AdminUpdateAuthEventFeedback
user resource
• AdminSetUserMFAPreference
information, such
• AdminSetUserSettings
as group.
• AdminUpdateDeviceStatus
• UpdateDeviceStatus
• UpdateAuthEventFeedback
• ConfirmDevice
• SetUserMFAPreference
• SetUserSettings
• VerifySoftwareToken
• AssociateSoftwareToken
• ForgetDevice
• DescribeIdentityProvider
UserPoolResourceRead Operations that 20
retrieve a resource
• DescribeResourceServer
from a user pool,
• DescribeUserImportJob
such as group.*
• DescribeUserPoolDomain
• GetCSVHeader
• GetGroup
• GetSigningCertificate
• GetIdentityProviderByIdentifier
• GetUserPoolMfaConfig
• ListGroups
• ListIdentityProviders
• ListResourceServers
• ListTagsForResource
• ListUserImportJobs
• DescribeRiskConfiguration
• GetUICustomization
324
Amazon Cognito Developer Guide
Track quota usage
• AddCustomAttributes
UserPoolResourceUpdate Operations that 15
• CreateGroup update resource
information for a
• CreateIdentityProvider
user pool, such as
• CreateResourceServer
group.*
• CreateUserImportJob
• CreateUserPoolDomain
• DeleteGroup
• DeleteIdentityProvider
• DeleteResourceServer
• DeleteUserPoolDomain
• SetUserPoolMfaConfig
• StartUserImportJob
• StopUserImportJob
• UpdateGroup
• UpdateIdentityProvider
• UpdateResourceServer
• SetRiskConfiguration
• SetUICustomization
• TagResource
• UntagResource
• DescribeUserPoolClient
UserPoolClientRead Operations that 15
• ListUserPoolClientslist your user pool
clients.*
• CreateUserPoolClient
UserPoolClientUpdate Operations that 15
create, update,
• DeleteUserPoolClient
and delete your
• UpdateUserPoolClient
user pool clients.*
*Any individual operation in this category has a constraint that prevents the operation from being called
at a rate higher than 5 RPS for a single user pool.
Utilization and usage are two terms that may help you understand service quota monitoring. Utilization
is the percentage of a service quota in use. For example, if the quota value is 200 resources and 150
325
Amazon Cognito Developer Guide
Identify quota requirements
resources are in use, the utilization is 75%. Usage is the number of resources or operations in use for a
service quota.
You can track and collect Amazon Cognito user pools utilization metrics using CloudWatch. The
CloudWatch dashboard will display metrics about every AWS service you use. You can use CloudWatch
to create metric alarms. The alarms can be setup to send you notifications or make a change to a specific
resource that you are monitoring. For more information on CloudWatch metrics, For more information
on Service Quotas, see Track your CloudWatch usage metrics.
Amazon Cognito user pools is integrated with Service Quotas, which is a browser-based interface that
you can use to view and manage your service quota usage. In the Service Quotas console, you can look
up the value of a specific quota, view monitoring information, request a quota increase, and setup
CloudWatch alarms. After your account has been active a while, you can view a graph of your resource
utilization.
For more information on viewing quotas in the Service Quotas console, see Viewing Service Quotas.
In addition, if you assume the average user session is two hours, and tokens are configured to expire
after an hour, each user has to refresh their tokens once during this session. Then the required average
quota for the UserAuthentication category to support this load is 70 RPS.
If you assume a peak-to-average ratio of 3:1 by accounting the variance of user sign-in frequency during
the eight hour period, then you need the desired UserAuthentication quota of 200 RPS.
Note
If you call multiple operations for each user action, you need to sum up the individual operation
call rates at the category level.
Optimize quotas
Follow one of the approached below to handle a peak call rate.
You can catch the error at every API call, and then re-try the attempt after a back-off period. You can
adjust the back-off algorithm according to business needs and load. Amazon SDKs have built-in retry
logic. For more information on Amazon Tools and SDKs, see Tools to Build on AWS.
Use a external database for frequently updated attributes
If your application requires several calls to a user pool to read or write custom attributes, use
external storage. You can use your preferred database to store custom attributes or use a cache layer
to load a user profile during sign-in. You can reference this profile from the cache when needed
instead of reloading the user profile from a user pool.
326
Amazon Cognito Developer Guide
API request rate quotas
Applications have to validate JWT tokens before trusting them. You can verify the signature and
validity of tokens on the client side without sending API calls to a user pool. After the token is
validated, you can trust claims in the token and use the claims instead of making more getUser API
calls. For more information on JSON token verification, see Verifying a JSON Web Token.
• To request a quota increase using the Service Quotas console, see Requesting a API quota increase in
the Service Quotas User Guide.
• If the quota is not yet available in Service Quotas, use the Service limit increase form.
Note
Only adjustable quotas can be increased.
Resource quotas
Resource quotas are quotas that limit the number and size of your resources. You can request an increase
to the adjustable resource quotas in Amazon Cognito. To request a quota increase, you can use the
Service Quotas console or use the Service limit increase form. To request a quota from the Service
Quotas console, see Requesting a quota increase in the Service Quotas User Guide. If the quota is not yet
available in Service Quotas, use the Service limit increase form.
Resource Quota
327
Amazon Cognito Developer Guide
Non-adjustable resource quotas
Resource Quota
Resource Quota
Token Quota
Resource Quota
328
Amazon Cognito Developer Guide
Non-adjustable resource quotas
Resource Quota
¹This quota applies only if you are using the default email feature for an Amazon Cognito User Pool.
To enable a higher email delivery volume, configure your user pool to use your Amazon SES email
configuration. For more information, see Email Settings for Amazon Cognito User Pools (p. 140).
Resource Quota
Resource Quota
329
Amazon Cognito Developer Guide
Non-adjustable resource quotas
Resource Quota
Resource Quota
330
Amazon Cognito Developer Guide
User Pools API Reference
Topics
• Amazon Cognito User Pools API Reference (p. 331)
• Amazon Cognito user pools Auth API Reference (p. 331)
• Amazon Cognito Identity Pools (Federated Identities) API Reference (p. 343)
• Amazon Cognito Sync API Reference (p. 343)
For a complete user pool API reference see Amazon Cognito user pools API Reference.
This section contains the HTTPS contract to the Amazon Cognito authentication server from a user
pool client, including sample requests and responses. It describes the expected behavior from the
authentication server for positive and negative conditions.
In addition to the server contract REST API, Amazon Cognito also provides Auth SDKs for Android, iOS,
and JavaScript that make it easier to form requests and interact with the server. Learn more about the
Amazon Cognito SDKs.
For more information on the specification see OpenID Connect 1.0 and OAuth 2.0.
Topics
• AUTHORIZATION Endpoint (p. 331)
• TOKEN Endpoint (p. 336)
• USERINFO Endpoint (p. 340)
• LOGIN Endpoint (p. 341)
• LOGOUT Endpoint (p. 342)
AUTHORIZATION Endpoint
The /oauth2/authorize endpoint signs the user in.
331
Amazon Cognito Developer Guide
AUTHORIZATION Endpoint
GET /oauth2/authorize
The /oauth2/authorize endpoint only supports HTTPS GET. The user pool client typically makes this
request through a browser. Web browsers include Chrome or Firefox. Android browsers include Custom
Chrome Tab. iOS browsers include Safari View Control.
The authorization server requires HTTPS instead of HTTP as the protocol when accessing the
authorization endpoint. For more information on the specification see Authorization Endpoint.
Request Parameters
response_type
The response type. Must be code or token. Indicates whether the client wants an authorization
code (authorization code grant flow) for the end user or directly issues tokens for end user (implicit
flow).
Required
client_id
Must be a pre-registered client in the user pool and must be enabled for federation.
Required
redirect_uri
The URL to which the authentication server redirects the browser after authorization has been
granted by the user.
Amazon Cognito requires HTTPS over HTTP except for http://localhost for testing purposes
only.
Required
state
An opaque value the clients adds to the initial request. The authorization server includes this value
when redirecting back to the client.
332
Amazon Cognito Developer Guide
AUTHORIZATION Endpoint
Optional
idp_identifier
Used by the developer to map to a provider name without exposing the provider name.
Optional
scope
Can be a combination of any system-reserved scopes or custom scopes 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 preassociated with the client or
it will be ignored at runtime.
If the client doesn't request any scopes, the authentication server uses all scopes 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.
Optional
code_challenge_method
The method used to generate the challenge. The PKCE RFC defines two methods, S256 and plain;
however, Amazon Cognito authentication server supports only S256.
Optional
code_challenge
Sample Request
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=ad398u21ijw3s9w3939&
redirect_uri=https://YOUR_APP/redirect_uri&
state=STATE&
scope=openid+profile+aws.cognito.signin.user.admin
Sample Response
The Amazon Cognito authentication server redirects back to your app with the authorization code and
state. The code and state must be returned in the query string parameters and not in the fragment. A
query string is the part of a web request that appears after a '?' character; the string can contain one or
more parameters separated by '&' characters. A fragment is the part of a web request that appears after
a '#' character to specify a subsection of a document.
333
Amazon Cognito Developer Guide
AUTHORIZATION Endpoint
Note
The response returns a one time use code that is valid for five minutes.
Sample Request
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=ad398u21ijw3s9w3939&
redirect_uri=https://YOUR_APP/redirect_uri&
state=STATE&
scope=aws.cognito.signin.user.admin&
code_challenge_method=S256&
code_challenge=CODE_CHALLENGE
Sample Response
The authentication server redirects back to your app with the authorization code and state. The code and
state must be returned in the query string parameters and not in the fragment.
Sample Request
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=token&
client_id=ad398u21ijw3s9w3939&
redirect_uri=https://YOUR_APP/redirect_uri&
state=STATE&
scope=aws.cognito.signin.user.admin
Sample Response
The Amazon Cognito authorization server redirects back to your app with access token. Since openid
scope was not requested, an ID token is not returned. A refresh token is never returned in this flow.
Token and state are returned in the fragment and not in the query string.
Sample Request
GET
https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/
authorize?
response_type=token&
client_id=ad398u21ijw3s9w3939&
redirect_uri=https://YOUR_APP/redirect_uri&
334
Amazon Cognito Developer Guide
AUTHORIZATION Endpoint
state=STATE&
scope=aws.cognito.signin.user.admin+openid+profile
Sample Response
The authorization server redirects back to your app with access token and ID token (because openid
scope was included).
• If client_id and redirect_uri are valid but there are other problems with the request
parameters (for example, if response_type is not included; if code_challenge is supplied but
code_challenge_method is not supplied; or if code_challenge_method is not 'S256'), the
authentication server redirects the error to client's redirect_uri.
335
Amazon Cognito Developer Guide
TOKEN Endpoint
TOKEN Endpoint
The /oauth2/token endpoint gets the user's tokens.
POST /oauth2/token
The /oauth2/token endpoint only supports HTTPS POST. The user pool client makes requests to this
endpoint directly and not through the system browser.
If the client was issued a secret, the client must pass its client_id and client_secret
in the authorization header through Basic HTTP authorization. The secret is Basic
Base64Encode(client_id:client_secret).
Content-Type
Grant type.
Required
client_id
Client ID.
Must be a preregistered client in the user pool. The client must be enabled for Amazon Cognito
federation.
336
Amazon Cognito Developer Guide
TOKEN Endpoint
Can be a combination of any custom scopes associated with a client. Any scope requested must be
preassociated with the client or it will be ignored at runtime. If the client doesn't request any scopes,
the authentication server uses all custom scopes associated with the client.
Must be the same redirect_uri that was used to get authorization_code in /oauth2/
authorize.
Required if grant_type is authorization_code and the authorization code was requested with
PKCE.
Sample Request
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token&
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic aSdxd892iujendek328uedj
grant_type=authorization_code&
client_id=djc98u3jiedmi283eu928&
code=AUTHORIZATION_CODE&
redirect_uri=com.myclientapp://myclient/redirect
Sample response
HTTP/1.1 200 OK
Content-Type: application/json
{
"access_token":"eyJz9sdfsdfsdfsd",
"refresh_token":"dn43ud8uj32nk2je",
"id_token":"dmcxd329ujdmkemkd349r",
"token_type":"Bearer",
"expires_in":3600
337
Amazon Cognito Developer Guide
TOKEN Endpoint
Note
The token endpoint returns refresh_token only when the grant_type is
authorization_code.
Sample Request
grant_type=client_credentials&
scope={resourceServerIdentifier1}/{scope1} {resourceServerIdentifier2}/{scope2}
Sample response
HTTP/1.1 200 OK
Content-Type: application/json
{
"access_token":"eyJz9sdfsdfsdfsd",
"token_type":"Bearer",
"expires_in":3600
}
Sample Request
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic aSdxd892iujendek328uedj
grant_type=authorization_code&
client_id=djc98u3jiedmi283eu928&
code=AUTHORIZATION_CODE&
code_verifier=CODE_VERIFIER&
redirect_uri=com.myclientapp://myclient/redirect
Sample response
HTTP/1.1 200 OK
Content-Type: application/json
{
"access_token":"eyJz9sdfsdfsdfsd",
"refresh_token":"dn43ud8uj32nk2je",
"id_token":"dmcxd329ujdmkemkd349r",
"token_type":"Bearer",
"expires_in":3600
}
Note
The token endpoint returns refresh_token only when the grant_type is
authorization_code.
338
Amazon Cognito Developer Guide
TOKEN Endpoint
Sample Request
grant_type=refresh_token&
client_id=djc98u3jiedmi283eu928&
refresh_token=REFRESH_TOKEN
Sample Response
HTTP/1.1 200 OK
Content-Type: application/json
{
"access_token":"eyJz9sdfsdfsdfsd",
"refresh_token":"dn43ud8uj32nk2je",
"id_token":"dmcxd329ujdmkemkd349r",
"token_type":"Bearer",
"expires_in":3600
}
Note
The token endpoint returns refresh_token only when the grant_type is
authorization_code.
{
"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
Client is not allowed for code grant flow or for refreshing tokens.
339
Amazon Cognito Developer Guide
USERINFO Endpoint
unsupported_grant_type
USERINFO Endpoint
The /oauth2/userInfo endpoint returns information about the authenticated user.
GET /oauth2/userInfo
The user pool client makes requests to this endpoint directly and not through a browser.
For more information see UserInfo Endpoint in the OpenID Connect (OIDC) specification.
Topics
• Request Parameters in Header (p. 340)
• Sample Request (p. 340)
• Sample Positive Response (p. 340)
• Sample Negative Responses (p. 340)
Required
Sample Request
GET https://<your-user-pool-domain>/oauth2/userInfo
Authorization: Bearer <access_token>
340
Amazon Cognito Developer Guide
LOGIN Endpoint
WWW-Authenticate: error="invalid_request",
error_description="Bad OAuth2 request at UserInfo Endpoint"
invalid_request
Invalid Token
invalid_token
LOGIN Endpoint
The /login endpoint signs the user in. It loads the login page and presents the authentication options
configured for the client to the user.
GET /login
The /login endpoint only supports HTTPS GET. The user pool client makes this request through a
system browser. System browsers for JavaScript include Chrome or Firefox. Android browsers include
Custom Chrome Tab. iOS browsers include Safari View Control.
Request Parameters
client_id
The app client ID for your app. To obtain an app client ID, register the app in the user pool. For more
information, see Configuring a User Pool App Client (p. 169).
Required
redirect_uri
The URI where the user is redirected after a successful authentication. It should be configured on
response_type of the specified client_id.
Required
response_type
The OAuth response type, which can be code for code grant flow and token for implicit flow.
Required
state
An opaque value the client adds to the initial request. The value is then returned back to the client
upon redirect.
341
Amazon Cognito Developer Guide
LOGOUT Endpoint
scope
Can be a combination of any system-reserved scopes or custom scopes 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 preassociated with the client or
it is ignored at runtime.
If the client doesn't request any scopes, the authentication server uses all scopes associated with the
client.
An ID token is only returned if an openid scope is requested. The access token can only be used
against Amazon Cognito user pools if an aws.cognito.signin.user.admin scope is requested.
The phone, email, and profile scopes can only be requested if an openid scope is also requested.
These scopes dictate the claims that go inside the ID token.
Optional
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
LOGOUT Endpoint
The /logout endpoint signs the user out.
GET /logout
The /logout endpoint only supports HTTPS GET. The user pool client typically makes this request
through the system browser, which would typically be Custom Chrome Tab in Android and Safari View
Control in iOS.
Request Parameters
client_id
The app client ID for your app. To obtain an app client ID, you must register the app in the user pool.
For more information, see Configuring a User Pool App Client (p. 169).
Required
logout_uri
A sign-out URL that you registered for your client app. For more information, see Configuring a User
Pool App Client (p. 29).
Optional
Sample Requests
Example #1: Logout and Redirect Back to Client
342
Amazon Cognito Developer Guide
Identity Pools API Reference
This example clears out the existing session and redirects back to the client. Both parameters are
required.
GET https://mydomain.auth.us-east-1.amazoncognito.com/logout?
client_id=ad398u21ijw3s9w3939&
logout_uri=https://myclient/logout
Example #2: Logout and Prompt the User to Sign In As Another User
This example clears out the existing session and shows the login screen, using the same parameters as
for GET /oauth2/authorize.
GET https://mydomain.auth.us-east-1.amazoncognito.com/logout?
response_type=code&
client_id=ad398u21ijw3s9w3939&
redirect_uri=https://YOUR_APP/redirect_uri&
state=STATE&
scope=openid+profile+aws.cognito.signin.user.admin
For a complete identity pools (federated identities) API reference see Amazon Cognito API Reference.
For more information on Amazon Cognito Sync API Reference, see Amazon Cognito Sync API Reference.
343
Amazon Cognito Developer Guide
Attributes for access control Amazon Cognito Identity Pools January 15, 2021
provide attributes for access
control (AFAC) as a way for
customers to grant users access
to AWS resources. Authorization
can be done based on users'
attributes from the identity
provider which they used to
federate with Amazon Cognito.
Custom SMS Sender Lambda The Custom SMS Sender November 2020
Trigger and Custom Email Lambda Trigger and Custom
Sender Lambda Trigger Email Sender Lambda Trigger
allow you to enable a third-party
provider to send email and SMS
notifications to your users from
within your Lambda function
code.
Amazon Cognito token updates Updated expiration information October 29, 2020
was added to Access, ID, and
Refresh tokens.
Amazon Cognito Service Quotas Service Quotas are available October 29, 2020
for Amazon Cognito category
quotas. You can use the Service
Quotas console to view quota
usage, request a quota increase,
and create CloudWatch alarms
to monitor your quota usage.
As part of this change the
Available CloudWatch Metrics
344
Amazon Cognito Developer Guide
Amazon Cognito quota Quota categories are available August 17, 2020
categorization to help you monitor quota
usage and request an increase.
The quotas are grouped into
categories based on common
use cases.
Amazon Cognito Pinpoint New service-linked role was May 13, 2020
document updates added. Instructions were
updated on "Using Amazon
Pinpoint Analytics with Amazon
Cognito User Pools".
New Amazon Cognito dedicated The Security chapter can help April 30, 2020
security chapter your organization get in-depth
information about both the
built-in and the configurable
security of AWS services.
Our new chapters provide
information about the security
of the cloud and in the cloud.
Amazon Cognito Identity Pools Sign in with Apple is available April 7, 2020
now supports Sign in with Apple in all regions where Amazon
Cognito operates, except cn-
north-1 region.
New information about AWS Added information about November 22, 2019
Amplify integrating Amazon
Cognito (p. 12) with your web
or mobile app by using AWS
Amplify SDKs and libraries.
Removed information about
using the Amazon Cognito SDKs
that preceded AWS Amplify.
345
Amazon Cognito Developer Guide
New attribute for user pool Amazon Cognito now includes October 4, 2019
triggers a clientMetadata parameter
in the event information that
it passes to the AWS Lambda
functions for most user pool
triggers. You can use this
parameter to enhance your
custom authentication workflow
with additional data.
New limit The soft limits for user pools June 17, 2019
now include a limit for the
number of users. For more
information, see Quotas in
Amazon Cognito (p. 321).
Amazon SES email settings for You can configure a user pool April 8, 2019
Amazon Cognito user pools so that Amazon Cognito emails
your users by using your Amazon
SES configuration. This setting
allows Amazon Cognito to send
email with a higher delivery
volume than is otherwise
possible. For more information,
see Email Settings for Amazon
Cognito User Pools (p. 140).
Change the certificate for a If you use a custom domain December 19, 2018
custom domain to host the Amazon Cognito
hosted UI, you can change the
SSL certificate for this domain as
needed. For more information,
see Changing the SSL Certificate
for Your Custom Domain (p. 36).
New limit A new limit is added for the December 14, 2018
maximum number of groups
that each user can belong to. For
more information, see Quotas in
Amazon Cognito (p. 321).
Updated limits The soft limits for user December 11, 2018
pools are updated. For more
information, see Quotas in
Amazon Cognito (p. 321).
346
Amazon Cognito Developer Guide
Documentation update for Added guidance for initiating November 13, 2018
testing emails emails from Amazon Cognito
while you test your app. For
more information, see Sending
Emails While Testing Your
App (p. 120).
Amazon Cognito Advanced Added new security features to June 14, 2018
Security enable developers to protect
their apps and users from
malicious bots, secure user
accounts against compromised
credentials, and automatically
adjust the challenges required to
sign in based on the calculated
risk of the sign in attempt.
Custom Domains for Amazon Allow developers to use their June 4, 2018
Cognito Hosted UI own fully custom domain for the
hosted UI in Amazon Cognito
User Pools.
Amazon Cognito User Pools Added user pool sign-in through May 17, 2018
OIDC Identity Provider an OpenID Connect (OIDC)
identity provider such as
Salesforce or Ping Identity.
347
Amazon Cognito Developer Guide
Amazon Cognito Advanced Added new security features to November 28, 2017
Security Beta enable developers to protect
their apps and users from
malicious bots, secure user
accounts against credentials
in the wild that have been
compromised elsewhere on
the internet, and automatically
adjust the challenges required to
sign in based on the calculated
risk of the sign in attempt.
Amazon Pinpoint integration Added the ability to use Amazon September 26, 2017
Pinpoint to provide analytics for
your Amazon Cognito User Pools
apps and to enrich the user data
for Amazon Pinpoint campaigns.
For more information, see Using
Amazon Pinpoint Analytics
with Amazon Cognito User
Pools (p. 111).
Federation and built-in app UI Added the ability to allow your August 10, 2017
features of Amazon Cognito users to sign in to your user
User Pools pool through Facebook, Google,
Login with Amazon, or a SAML
identity provider. Added a
customizable built-in app UI and
OAuth 2.0 support with custom
claims.
HIPAA and PCI compliance- Added the ability to allow your July 6, 2017
related feature changes users to use a phone number
or email address as their user
name.
User groups and role-based Added administrative capability December 15, 2016
access control features to create and manage user
groups. Administrators can
assign IAM roles to users
based on group membership
and administrator-created
rules. For more information,
see Adding Groups to a User
Pool (p. 124) and Role-Based
Access Control (p. 201).
348
Amazon Cognito Developer Guide
General availability of Cognito Added the Cognito User Pools July 28, 2016
User Pools feature. Use this feature to
create and maintain a user
directory and add sign-up and
sign-in to your mobile app or
web application using user
pools. For more information,
see Amazon Cognito user
pools (p. 16).
349
Amazon Cognito Developer Guide
Data stream to Amazon Kinesis Provides control and insight March 4, 2015
into your data streams. For
more information, see Amazon
Cognito Streams (p. 274).
OpenID Connect support Enables support for OpenID October 23, 2014
Connect providers. For more
information, see Identity Pools
(Federated Identities) External
Identity Providers (p. 212).
350