

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

An Amazon Cognito identity pool is a directory of federated identities that you can exchange for AWS credentials. Identity pools generate temporary AWS credentials for the users of your app, whether they’ve signed in or you haven’t identified them yet. With AWS Identity and Access Management (IAM) roles and policies, you can choose the level of permission that you want to grant to your users. Users can start out as guests and retrieve assets that you keep in AWS services. Then they can sign in with a third-party identity provider to unlock access to assets that you make available to registered members. The third-party identity provider can be a consumer (social) OAuth 2.0 provider like Apple or Google, a custom SAML or OIDC identity provider, or a custom authentication scheme, also called a *developer provider*, of your own design.Features of Amazon Cognito identity pools

**Sign requests for AWS services**  
[Sign API requests](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html) to AWS services like Amazon Simple Storage Service (Amazon S3) and Amazon DynamoDB. Analyze user activity with services like Amazon Pinpoint and Amazon CloudWatch.

**Filter requests with resource-based policies**  
Exercise granular control over user access to your resources. Transform user claims into [IAM session tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html), and build IAM policies that grant resource access to distinct subsets of your users.

**Assign guest access**  
For your users who haven’t signed in yet, configure your identity pool to generate AWS credentials with a narrow scope of access. Authenticate users through a single sign-on provider to elevate their access.

**Assign IAM roles based on user characteristics**  
Assign a single IAM role to all of your authenticated users, or choose the role based on the claims of each user.

**Accept a variety of identity providers**  
Exchange an ID or access token, a user pool token, a SAML assertion, or a social-provider OAuth token for AWS credentials.

**Validate your own identities**  
Perform your own user validation and use your developer AWS credentials to issue credentials for your users.

You might already have an Amazon Cognito user pool that provides authentication and authorization services to your app. You can set up your user pool as an identity provider (IdP) to your identity pool. When you do, your users can authenticate through your user pool IdPs, consolidate their claims into a common OIDC identity token, and exchange that token for AWS credentials. Your user can then present their credentials in a signed request to your AWS services.

You can also present authenticated claims from any of your identity providers directly to your identity pool. Amazon Cognito customizes user claims from SAML, OAuth, and OIDC providers into an [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API request for short-term credentials.

Amazon Cognito user pools are like OIDC identity providers to your SSO-enabled apps. Identity pools act as an *AWS* identity provider to any app with resource dependencies that work best with IAM authorization.

Amazon Cognito identity pools support the following identity providers:
+ Public providers: [Setting up Login with Amazon as an identity pools IdP](amazon.md), [Setting up Facebook as an identity pools IdP](facebook.md), [Setting up Google as an identity pool IdP](google.md), [Setting up Sign in with Apple as an identity pool IdP](apple.md), Twitter.
+ [Amazon Cognito user pools](cognito-user-pools.md)
+ [Setting up an OIDC provider as an identity pool IdP](open-id.md)
+ [Setting up a SAML provider as an identity pool IdP](saml-identity-provider.md)
+ [Developer-authenticated identities](developer-authenticated-identities.md)

For information about Amazon Cognito identity pools Region availability, see [AWS Service Region Availability](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/).

For more information about Amazon Cognito identity pools, see the following topics.

**Topics**
+ [Identity pools console overview](identity-pools.md)
+ [Identity pools authentication flow](authentication-flow.md)
+ [IAM roles](iam-roles.md)
+ [Security best practices for Amazon Cognito identity pools](identity-pools-security-best-practices.md)
+ [Using attributes for access control](attributes-for-access-control.md)
+ [Using role-based access control](role-based-access-control.md)
+ [Getting credentials](getting-credentials.md)
+ [Accessing AWS services with temporary credentials](accessing-aws-services.md)
+ [Identity pools third-party identity providers](external-identity-providers.md)
+ [Developer-authenticated identities](developer-authenticated-identities.md)
+ [Switching unauthenticated users to authenticated users](switching-identities.md)

# Identity pools console overview
<a name="identity-pools"></a>

Amazon Cognito identity pools provide temporary AWS credentials for users who are guests (unauthenticated) and for users who have been authenticated and received a token. An identity pool is a store of user identifiers linked to your external identity providers.

One way to understand the features and options of identity pools is to create one in the Amazon Cognito console. You can explore the effect of different settings on authentication flows, role-based and attribute-based access control, and guest access. From there, you can proceed to later chapters in this guide and add the appropriate components to your application so that you can implement identity pool authentication.

**Topics**
+ [Create an identity pool](#identity-pools-create)
+ [User IAM roles](#user-iam-roles)
+ [Authenticated and unauthenticated identities](#authenticated-and-unauthenticated-identities)
+ [Activate or deactivate guest access](#enable-or-disable-unauthenticated-identities)
+ [Change the role associated with an identity type](#change-the-role-associated-with-an-identity-type)
+ [Edit identity providers](#enable-or-edit-authentication-providers)
+ [Delete an identity pool](#delete-an-identity-pool)
+ [Delete an identity from an identity pool](#delete-an-identity-from-an-identity-pool)
+ [Using Amazon Cognito Sync with identity pools](#identity-pools-sync)

## Create an identity pool
<a name="identity-pools-create"></a>

**To create a new identity pool in the console**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home) and select **Identity pools**.

1. Choose **Create identity pool**.

1. In **Configure identity pool trust**, choose to set up your identity pool for **Authenticated access**, **Guest access**, or both.

   1. If you chose **Authenticated access**, select one or more **Identity types** that you want to set as the source of authenticated identities in your identity pool. If you configure a **Custom developer provider**, you can't modify or delete it after you create your identity pool.

1. In **Configure permissions**, choose a default IAM role for authenticated or guest users in your identity pool.

   1. Choose to **Create a new IAM role** if you want Amazon Cognito to create a new role for you with basic permissions and a trust relationship with your identity pool. Enter an **IAM role name** to identify your new role, for example `myidentitypool_authenticatedrole`. Select **View policy document** to review the permissions that Amazon Cognito will assign to your new IAM role.

   1. You can choose to **Use an existing IAM role** if you already have a role in your AWS account that you want to use. You must configure your IAM role trust policy to include `cognito-identity.amazonaws.com`. Configure your role trust policy to only allow Amazon Cognito to assume the role when it presents evidence that the request originated from an authenticated user in your specific identity pool. For more information, see [Role trust and permissions](iam-roles.md#role-trust-and-permissions).

1. In **Connect identity providers**, enter the details of the identity providers (IdPs) that you chose in **Configure identity pool trust**. You might be asked to provide OAuth app client information, choose a Amazon Cognito user pool, choose an IAM IdP, or enter a custom identifier for a developer provider.

   1. Choose the **Role settings** for each IdP. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**. With a Amazon Cognito user pool IdP, you can also **Choose role with preferred\$1role in tokens**. For more information about the `cognito:preferred_role` claim, see [Assigning precedence values to groups](cognito-user-pools-user-groups.md#assigning-precedence-values-to-groups).

      1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

      1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

   1. Configure **Attributes for access control** for each IdP. Attributes for access control maps user claims to [principal tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_iam-tags.html) that Amazon Cognito applies to their temporary session. You can build IAM policies to filter user access based on the tags that you apply to their session.

      1. To apply no principal tags, choose **Inactive**.

      1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

      1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. In **Configure properties**, enter a **Name** under **Identity pool name**.

1. Under **Basic (classic) authentication**, choose whether you want to **Activate basic flow**. With the basic flow active, you can bypass the role selections you made for your IdPs and call [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) directly. For more information, see [Identity pools authentication flow](authentication-flow.md).

1. Under **Tags**, choose **Add tag** if you want to apply [tags](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) to your identity pool.

1. In **Review and create**, confirm the selections that you made for your new identity pool. Select **Edit** to return to the wizard and change any settings. When you're done, select **Create identity pool**.

## User IAM roles
<a name="user-iam-roles"></a>

An IAM role defines the permissions for your users to access AWS resources, like [Amazon Cognito Sync](cognito-sync.md). Users of your application will assume the roles you create. You can specify different roles for authenticated and unauthenticated users. To learn more about IAM roles, see [IAM roles](iam-roles.md).

## Authenticated and unauthenticated identities
<a name="authenticated-and-unauthenticated-identities"></a>

Amazon Cognito identity pools support both authenticated and unauthenticated identities. Authenticated identities belong to users who are authenticated by any supported identity provider. Unauthenticated identities typically belong to guest users.
+ To configure authenticated identities with a public login provider, see [Identity pools third-party identity providers](external-identity-providers.md).
+ To configure your own backend authentication process, see [Developer-authenticated identities](developer-authenticated-identities.md).

## Activate or deactivate guest access
<a name="enable-or-disable-unauthenticated-identities"></a>

 Amazon Cognito identity pools guest access (unauthenticated identities) provides a unique identifier and AWS credentials for users who do not authenticate with an identity provider. If your application allows users who do not log in, you can activate access for unauthenticated identities. To learn more, see [Getting started with Amazon Cognito identity pools](getting-started-with-identity-pools.md).

**To update guest access in an identity pool**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Locate **Guest access**. In an identity pool that doesn't currently support guest access, **Status** is **Inactive**.

   1. If **Guest access** is **Active** and you want to deactivate it, select **Deactivate**.

   1. If **Guest access** is **Inactive** and you want to activate it, select **Edit**.

      1. Choose a default IAM role for guest users in your identity pool.

        1. Choose to **Create a new IAM role** if you want Amazon Cognito to create a new role for you with basic permissions and a trust relationship with your identity pool. Enter an **IAM role name** to identify your new role, for example `myidentitypool_authenticatedrole`. Select **View policy document** to review the permissions that Amazon Cognito will assign to your new IAM role.

        1. You can choose to **Use an existing IAM role** if you already have a role in your AWS account that you want to use. You must configure your IAM role trust policy to include `cognito-identity.amazonaws.com`. Configure your role trust policy to only allow Amazon Cognito to assume the role when it presents evidence that the request originated from an authenticated user in your specific identity pool. For more information, see [Role trust and permissions](iam-roles.md#role-trust-and-permissions).

        1. Select **Save changes**.

        1. To activate guest access, select **Activate** in the **User access** tab.

## Change the role associated with an identity type
<a name="change-the-role-associated-with-an-identity-type"></a>

Every identity in your identity pool is either authenticated or unauthenticated. Authenticated identities belong to users who are authenticated by a public login provider (Amazon Cognito user pools, Login with Amazon, Sign in with Apple, Facebook, Google, SAML, or any OpenID Connect Providers) or a developer provider (your own backend authentication process). Unauthenticated identities typically belong to guest users.

For each identity type, there is an assigned role. This role has a policy attached to it that dictates which AWS services that role can access. When Amazon Cognito receives a request, the service determines the identity type, determines the role assigned to that identity type, and uses 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](https://console.aws.amazon.com/iam/home).

**To change the identity pool default authenticated or unauthenticated role**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Locate **Guest access** or **Authenticated access**. In an identity pool that isn't currently configured for that access type, **Status** is **Inactive**. Select **Edit**.

1. Choose a default IAM role for guest or authenticated users in your identity pool.

   1. Choose to **Create a new IAM role** if you want Amazon Cognito to create a new role for you with basic permissions and a trust relationship with your identity pool. Enter an **IAM role name** to identify your new role, for example `myidentitypool_authenticatedrole`. Select **View policy document** to review the permissions that Amazon Cognito will assign to your new IAM role.

   1. You can choose to **Use an existing IAM role** if you already have a role in your AWS account that you want to use. You must configure your IAM role trust policy to include `cognito-identity.amazonaws.com`. Configure your role trust policy to only allow Amazon Cognito to assume the role when it presents evidence that the request originated from an authenticated user in your specific identity pool. For more information, see [Role trust and permissions](iam-roles.md#role-trust-and-permissions).

1. Select **Save changes**.

## Edit identity providers
<a name="enable-or-edit-authentication-providers"></a>

If you allow your users to authenticate using consumer identity providers (for example, Amazon Cognito user pools, Login with Amazon, Sign in with Apple, Facebook, or Google), you can specify your application identifiers in the Amazon Cognito identity pools (federated identities) console. This associates the application ID (provided by the public login provider) with your identity pool.

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 [Using role-based access control](role-based-access-control.md).

**Warning**  
Changing the linked IdP application ID in your identity pool prevents existing users from authenticating with that identity pool. For more information, see [Identity pools third-party identity providers](external-identity-providers.md).

**To update an identity pool identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Locate **Identity providers**. Choose the identity provider that you want to edit. If you want to add a new IdP, select **Add identity provider**.

   1. If you chose **Add identity provider**, choose one of the **Identity types** that you want to add.

1. To change the application ID, choose **Edit** in **Identity provider information**.

1. To change the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, choose **Edit** in **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**. With a Amazon Cognito user pool IdP, you can also **Choose role with preferred\$1role in tokens**. For more information about the `cognito:preferred_role` claim, see [Assigning precedence values to groups](cognito-user-pools-user-groups.md#assigning-precedence-values-to-groups).

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, choose **Edit** in **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

## Delete an identity pool
<a name="delete-an-identity-pool"></a>

You can't undo identity pool deletion. After you delete an identity pool, all apps and users that depend on it stop working.

**To delete an identity pool**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select the radio button next to the identity pool that you want to delete.

1. Select **Delete**.

1. Enter or paste the name of your identity pool and select **Delete**.

**Warning**  
When you select 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 using the identity pool to stop working.

## Delete an identity from an identity pool
<a name="delete-an-identity-from-an-identity-pool"></a>

When you delete an identity from an identity pool, you remove the identifying information that Amazon Cognito has stored for that federated user. When your user requests credentials again, they receive a new identity ID if your identity pool still trusts their identity provider. You can't undo this operation.

**To delete an identity**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **Identity browser** tab.

1. Select the check boxes next to the identities that you want to delete and choose **Delete**. Confirm that you want to delete the identities and choose **Delete**.

## Using Amazon Cognito Sync with identity pools
<a name="identity-pools-sync"></a>

 Amazon Cognito Sync is an AWS service and client library that makes it possible to sync application-related user data across devices. Amazon Cognito Sync can synchronize user profile data across mobile devices and the web without using your own backend. The client libraries cache data locally so that your app can read and write data regardless of device connectivity status. When the device is online, you can synchronize data. If you set up push sync, you can notify other devices immediately that an update is available. 

### Managing datasets
<a name="managing-datasets-in-the-amazon-cognito-console"></a>

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 isn't saved until you select **Synchronize** in the console. The change isn't visible to the end user until the identity calls **Synchronize**. The data being synchronized from other devices for individual identities is visible once you refresh the list datasets page for a particular identity.

#### Create a dataset for an identity
<a name="create-a-dataset-for-an-identity"></a>

Amazon Cognito Sync associates a dataset with one identity. You can populate your dataset with identifying information about the user that the identity represents, then sync that information to all of your user's devices.

**To add a dataset and dataset records to an identity**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **Identity browser** tab.

1. Select the identity that you want to edit.

1. In **Datasets**, choose **Create dataset**.

1. Enter a **Dataset name** and select **Create dataset**.

1. If you want to add records to your dataset, choose your dataset from identity details. In **Records**, select **Create record**.

1. Enter a **Key** and **Value** for your record. Choose **Confirm**. Repeat to add more records.

#### Delete a dataset associated with an identity
<a name="delete-a-dataset-associated-with-an-identity"></a>

**To delete a dataset and its records from an identity**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **Identity browser** tab.

1. Select the identity that contains the dataset that you want to delete.

1. In **Datasets**, choose the radio button next to the dataset that you want to delete.

1. Select **Delete**. Review your choice and select **Delete** again.

### Bulk publish data
<a name="bulk-publish-data"></a>

 Bulk publish can be used to export data already stored in your Amazon Cognito Sync store to a Amazon Kinesis stream. For instructions on how to bulk publish all of your streams, see [Implementing Amazon Cognito Sync streams](cognito-streams.md). 

### Activate push synchronization
<a name="enable-push-synchronization"></a>

 Amazon Cognito automatically tracks the association between identity and devices. Using the push sync feature, you can make sure that every instance of a given identity is notified when identity data changes. Push sync makes it so that, whenever the dataset changes for an identity, all devices associated with that identity receive a silent push notification informing them of the change.

 You can activate push sync in the Amazon Cognito console. 

**To activate push synchronization**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **Identity pool properties** tab.

1. In **Push synchronization**, select **Edit**

1. Select **Activate push synchronization with your identity pool**.

1. Choose one of the Amazon Simple Notification Service (Amazon SNS) **Platform applications** that you created in the current AWS Region. Amazon Cognito publishes push notifications to your platform application. Select **Create platform application** to navigate to the Amazon SNS console and create a new one.

1. To publish to your platform application, Amazon Cognito assumes an IAM role in your AWS account. Choose to **Create a new IAM role** if you want Amazon Cognito to create a new role for you with basic permissions and a trust relationship with your identity pool. Enter an **IAM role name** to identify your new role, for example `myidentitypool_authenticatedrole`. Select **View policy document** to review the permissions that Amazon Cognito will assign to your new IAM role.

1. You can choose to **Use an existing IAM role** if you already have a role in your AWS account that you want to use. You must configure your IAM role trust policy to include `cognito-identity.amazonaws.com`. Configure your role trust policy to only allow Amazon Cognito to assume the role when it presents evidence that the request originated from an authenticated user in your specific identity pool. For more information, see [Role trust and permissions](iam-roles.md#role-trust-and-permissions).

1. Select **Save changes**.

### Set up Amazon Cognito Streams
<a name="set-up-cognito-streams"></a>

 Amazon Cognito Streams gives developers control and insight into their data stored in Amazon Cognito Sync. Developers can now configure a Kinesis stream to receive events as data. Amazon Cognito can push each dataset change to a Kinesis stream you own in real time. For instructions on how to set up Amazon Cognito Streams in the Amazon Cognito console, see [Implementing Amazon Cognito Sync streams](cognito-streams.md). 

### Set up Amazon Cognito Events
<a name="set-up-cognito-events"></a>

 Amazon Cognito Events allows you to run an AWS Lambda function in response to important events in Amazon Cognito Sync. Amazon Cognito Sync raises the Sync Trigger event when a dataset is synchronized. You can use the Sync Trigger event to take an action when a user updates data. For instructions on setting up Amazon Cognito Events from the console, see [Customizing workflows with Amazon Cognito Events](cognito-events.md). 

 To learn more about AWS Lambda, see [AWS Lambda](https://aws.amazon.com/lambda/). 

# Identity pools authentication flow
<a name="authentication-flow"></a>

Amazon Cognito helps you create unique identifiers for your end users that are kept consistent across devices and platforms. Amazon Cognito also delivers temporary, limited-privilege credentials to your application to access AWS resources. This page covers the basics of how authentication in Amazon Cognito works and explains the lifecycle of an identity inside your identity pool.

**External provider authflow**

A user authenticating with Amazon Cognito goes 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](https://console.aws.amazon.com/cognito/) creates 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](iam-roles.md).

Identity pools accept the following artifacts from providers:


| Provider | Authentication artifact | 
| --- | --- | 
| Amazon Cognito user pool | ID token | 
| OpenID Connect (OIDC) | ID token | 
| SAML 2.0 | SAML assertion | 
| Social provider | Access token | 

## The enhanced (simplified) authentication flow
<a name="authentication-flow-enhanced"></a>

When you use the enhanced authflow, your app first presents a proof of authentication from an authorized Amazon Cognito user pool or third-party identity provider in a [GetId](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html) request. 

1. Your application presents a proof of authentication–a JSON web token or a SAML assertion–from an authorized Amazon Cognito user pool or third-party identity provider in a [GetID](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html) request.

1. Your identity pool returns an identity ID.

1. Your application combines the identity ID with the same proof of authentication in a [GetCredentialsForIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html) request.

1. Your identity pool returns AWS credentials.

1. Your application signs AWS API requests with the temporary credentials.

Enhanced authentication manages the logic of IAM role selection and credentials retrieval in your identity pool configuration. You can configure your identity pool to select a default role, to apply attribute-based access control (ABAC) or role-based access control (RBAC) principles to role selection. The AWS credentials from enhanced authentication are valid for one hour.

**Order of operations in Enhanced authentication**

1. `GetId`

1. `GetCredentialsForIdentity`

![\[A diagram that shows the flow of enhanced authentication\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/amazon-cognito-ext-auth-enhanced-flow.png)


## The basic (classic) authentication flow
<a name="authentication-flow-basic"></a>

When you implement the basic authentication flow, your application selects the IAM role that you want users to assume.

1. Your application presents a proof of authentication–a JSON web token or a SAML assertion–from an authorized Amazon Cognito user pool or third-party identity provider in a [GetID](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html) request.

1. Your identity pool returns an identity ID.

1. Your application combines the identity ID with the same proof of authentication in a [GetOpenIdToken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html) request.

1. `GetOpenIdToken` returns a new OAuth 2.0 token that is issued by your identity pool.

1. Your application presents the new token in an [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) request.

1. AWS Security Token Service (AWS STS) returns AWS credentials.

1. Your application signs AWS API requests with the temporary credentials.

The basic workflow gives you more granular control over the credentials that you distribute to your users. The `GetCredentialsForIdentity` request of the enhanced authflow requests a role based on the contents of an access token. The `AssumeRoleWithWebIdentity` request in the classic workflow grants your app a greater ability to request credentials for any AWS Identity and Access Management role that you have configured with a sufficient trust policy. You can also request a custom role session duration.

You can sign in with the Basic authflow in user pools that don't have role mappings. This type of identity pool doesn't have a default authenticated or unauthenticated role, and doesn't have role-based or attribute-based access control configured. When you attempt `GetOpenIdToken` in an identity pool with role mappings, you receive the following error.

```
Basic (classic) flow is not supported with RoleMappings, please use enhanced flow.
```

**Order of operations in Basic authentication**

1. `GetId`

1. `GetOpenIdToken`

1. `AssumeRoleWithWebIdentity`

![\[A diagram that shows the flow of basic authentication\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/amazon-cognito-ext-auth-basic-flow.png)


## The developer-authenticated authentication flow
<a name="authentication-flow-developer"></a>

When using [Developer-authenticated identities](developer-authenticated-identities.md), your client uses a different authflow that includes code outside of Amazon Cognito to validate the user in your own authentication system. From the perspective of your identity pool, the claims that you present in your request for an identity are arbitrary identifiers, and the authentication is authorized by IAM credentials that you encode in your application.

**Order of operations in Enhanced authentication with a developer provider**

1. Login via Developer Provider (code outside of Amazon Cognito)

1. Validate the user login (code outside of Amazon Cognito)

1. [GetOpenIdTokenForDeveloperIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html)

1. [GetCredentialsForIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html)

![\[A diagram that shows the flow of developer-authenticated enhanced authentication\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/amazon-cognito-dev-auth-enhanced-flow.png)


**Order of operations in basic authentication with a developer provider**

1. Implement logic outside of identity pool to sign in and generate a developer-provider identifier.

1. Retrieve stored server-side AWS credentials.

1. Send developer provider identifier in a [GetOpenIdTokenForDeveloperIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html) API request signed with authorized AWS credentials.

1. Request application credentials with [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html).

![\[A diagram that shows the flow of developer-authenticated basic authentication\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/amazon-cognito-dev-auth-basic-flow.png)


## Which authentication flow should I implement?
<a name="authentication-flow-choosing"></a>

The **enhanced flow** is the most secure choice with the lowest level of developer effort:
+ The enhanced flow reduces the complexity, size, and rate of API requests.
+ Your application doesn't need to make additional API requests to AWS STS.
+ Your identity pool evaluates your users for the IAM role credentials that they should receive. You don't need to embed logic for role selection in your client.

**Important**  
When you create a new identity pool, don't activate basic (classic) authentication by default, as a best practice. To implement basic authentication, first evaluate the trust relationships of your IAM roles for web identities. Then build the logic for role selection into your client and secure the client against modification by users.

The **basic authentication flow** delegates the logic of IAM role selection to your application. In this flow, Amazon Cognito validates your user's authenticated or unauthenticated session and issues a token that you can exchange for credentials with AWS STS. Users can exchange the tokens from basic authentication for any IAM roles that trust your identity pool and `amr`, or authenticated/unauthenticated state.

Similarly, understand that **developer authentication** is a shortcut around validation of identity provider authentication. Amazon Cognito trusts the AWS credentials that authorize a [GetOpenIdTokenForDeveloperIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html) request without additional validation of the request contents. Secure the secrets that authorize developer authentication from access by users.

## Authentication flow API operations overview
<a name="authentication-flow-operations"></a>

**GetId**  
The [GetId](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html) API call is the first call necessary to establish a new identity in Amazon Cognito.    
Unauthenticated access  
Amazon Cognito can grant 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 and 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\$1, Login with Amazon, or Sign in with Apple), users can also supply tokens (OAuth or OpenID Connect) that identify them in those providers. When used in a call to `GetId`, Amazon Cognito creates a new authenticated identity or returns the identity already associated with that particular login. Amazon Cognito does this by validating the token with the provider and making sure of the following:  
+ The token is valid and from the configured provider.
+ The token is not expired.
+ The token matches the application identifier created with that provider (for example, Facebook app ID).
+ The token matches the user identifier.

**GetCredentialsForIdentity**  
The [GetCredentialsForIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html) API can be called after you establish an identity ID. This operation is functionally equivalent to calling [GetOpenIdToken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html), then [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html).  
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](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_SetIdentityPoolRoles.html) operation.

**GetOpenIdToken**  
Make a [GetOpenIdToken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html) API request after you establish an identity ID. Cache identity IDs after your first request, and start subsequent basic (classic) sessions for that identity with `GetOpenIdToken`.  
The response to a `GetOpenIdToken` API request is a token that Amazon Cognito generates. You can submit this token as the `WebIdentityToken` parameter in an [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) request.  
Before you submit the OpenID token, verify it in your app. You can use OIDC libraries in your SDK or a library like [https://github.com/awslabs/aws-jwt-verify](https://github.com/awslabs/aws-jwt-verify) to confirm that Amazon Cognito issued the token. The signing key ID, or `kid`, of the OpenID token is one of those listed in the Amazon Cognito Identity [jwks\$1uri document](https://cognito-identity.amazonaws.com/.well-known/jwks_uri)†. These keys are subject to change. Your function that verifies Amazon Cognito Identity tokens should periodically update its list of keys from the *jwks\$1uri* document. Amazon Cognito sets the refresh duration in the *jwks\$1uri* cache-control response header, currently set to a `max-age` of 30 days.    
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 identities or identities that you have deactivated.  
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 that you pass in may not be the one that is returned.  
Linking logins  
If you submit 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 results in a `ResourceConflictException` error response. If a login is merely linked to an existing identity, the identity ID returned from `GetOpenIdToken` is the same as the one that you 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 associated logins and the other is disabled. In this case, the identity ID of the parent/owner is returned. You must update your local cache if this value differs. The providers in the AWS Mobile SDKs or AWS SDK for JavaScript in the Browser perform this operation for you.

**GetOpenIdTokenForDeveloperIdentity**  
The [GetOpenIdTokenForDeveloperIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html) operation replaces the use of [GetId](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html) and [GetOpenIdToken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html) from the device when using developer authenticated identities. Because your application signs requests to this API operation with AWS credentials, Amazon Cognito trusts that the user identifier supplied in the request is valid. Developer authentication replaces the token validation that Amazon Cognito performs with external providers.  
The payload for this API includes a `logins` map. This map 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 creates a new identity and returns the new identity ID and an OpenID Connect token for that identity. If the user identifier is already linked, Amazon Cognito returns the pre-existing identity ID and an OpenID Connect token. Cache developer identity IDs after your first request, and start subsequent basic (classic) sessions for that identity with `GetOpenIdTokenForDeveloperIdentity`.  
The response to a `GetOpenIdTokenForDeveloperIdentity` API request is a token that Amazon Cognito generates. You can submit this token as the `WebIdentityToken` parameter in an `AssumeRoleWithWebIdentity` request.  
Before you submit the OpenID Connect token, verify it in your app. You can use OIDC libraries in your SDK or a library like [https://github.com/awslabs/aws-jwt-verify](https://github.com/awslabs/aws-jwt-verify) to confirm that Amazon Cognito issued the token. The signing key ID, or `kid`, of the OpenID Connect token is one of those listed in the Amazon Cognito Identity [*jwks\$1uri* document](https://cognito-identity.amazonaws.com/.well-known/jwks_uri)†. These keys are subject to change. Your function that verifies Amazon Cognito Identity tokens should periodically update its list of keys from the *jwks\$1uri* document. Amazon Cognito sets the refresh duration in the *jwks\$1uri* `cache-control` response header, currently set to a `max-age` of 30 days.    
Linking logins  
As with external providers, supplying additional logins that are not already associated with an identity implicitly links those logins to that identity. If you link an external provider login to an identity, the user can use the external provider authflow with that provider. However, 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 and explicit merging through the [MergeDeveloperIdentities](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_MergeDeveloperIdentities.html) API. With explicit merging, you can mark two identities with user identifiers in your system as a single identity. If you supply the source and destination user identifiers, Amazon Cognito merges them. The next time you request an OpenID Connect token for either user identifier, the same identity id is returned.

**AssumeRoleWithWebIdentity**  
After you have an OpenID Connect token, you can then trade this for temporary AWS credentials through the [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API request to AWS Security Token Service (AWS STS).  
Because there is no restriction on the number of identities that you can create, it is important to understand the permissions that you're granting to your users. Set up different IAM roles for your application: one for unauthenticated users, and one for authenticated users. The Amazon Cognito console can create default roles when you first set up your identity pool. These roles have effectively no permissions granted. Modify them to meet your needs.  
Learn more about [Role trust and permissions](iam-roles.md#role-trust-and-permissions).

† The default Amazon Cognito Identity [https://cognito-identity.amazonaws.com/.well-known/jwks_uri](https://cognito-identity.amazonaws.com/.well-known/jwks_uri) document contains information about the keys that sign tokens for identity pools in most AWS Regions. The following Regions have different *jwks\$1uri* documents.


| AWS Region | Path to *jwks\$1uri* document | 
| --- |--- |
| AWS GovCloud (US-West) | https://cognito-identity.us-gov-west-1.amazonaws.com/.well-known/jwks\$1uri | 
| China (Beijing) | https://cognito-identity---cn-north-1.amazonaws.com.rproxy.govskope.ca.cn/.well-known/jwks\$1uri | 
| Opt-in Regions like Europe (Milan) and Africa (Cape Town) | https://cognito-identity.Region.amazonaws.com/.well-known/jwks\$1uri | 

You can also extrapolate the *jwks\$1uri* from the issuer or `iss` that you receive in the OpenID token from Amazon Cognito. The OIDC-standard discovery endpoint `<issuer>/.well-known/openid-configuration` lists a path to the *jwks\$1uri* for your token.

# IAM roles
<a name="iam-roles"></a>

While creating an identity pool, you're 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. With the IAM role, you can 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 [Using role-based access control](role-based-access-control.md).

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.

Modify IAM roles to allow or restrict access to other services. To do so, [log in to the IAM Console](https://console.aws.amazon.com/iam/home). Then select **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 selecting the corresponding **Manage Policy** link. To learn more about using and defining policies, see [Overview of IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html).

**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](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#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](#trust-policies)
+ [Access policies](#access-policies)
+ [Role trust and permissions](#role-trust-and-permissions)

## Set up a trust policy
<a name="trust-policies"></a>

Amazon Cognito uses IAM roles to generate temporary credentials for your application's users. Access to permissions is controlled by a role's trust relationships. Learn more about [Role trust and permissions](#role-trust-and-permissions). Amazon Cognito brokers connections between AWS STS and identity pool IdPs.

The token presented to AWS STS is generated by an identity pool, which translates a user pool, social, or OIDC provider token, or a SAML assertion, to its own token. The identity pool token contains an `aud` claim that is the identity pool ID.

Where the `Principal` of an IAM role trust policy is an identity pools service principal like `cognito-identity.amazonaws.com`, you can't create or modify role trust policies such that they permit any identity pool to assume the role. With the identity pool principal, the `Action` element must have a `Condition` that requires that `AssumeRoleWithWebIndentity` be performed only by your identity pools, as specified by a condition key like `cognito-identity.amazonaws.com:aud`. Other condition keys are available, but `aud` is required. If you attempt to save a role trust policy without a condition of this type, IAM returns an error.

For more information about OIDC (web identity) federation keys, see [Available keys for AWS OIDC federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-wif).

The following are available OIDC federation condition keys for Amazon Cognito.

**`cognito-identity.amazonaws.com:aud`**  
Restricts the role to operations from one or more identity pools. Amazon Cognito indicates the source identity pool in the `aud` claim in the identity pool token.

**`cognito-identity.amazonaws.com:amr`**  
Restricts the role to either `authenticated` or `unauthenticated` (guest) users. Amazon Cognito indicates the authentication state in the `amr` claim in the identity pool token.

**`cognito-identity.amazonaws.com:sub`**  
Restricts the role to one or more users by [UUID](cognito-terms.md#terms-uuid). This UUID is the user's identity ID in the identity pool. This value isn’t the `sub` value from the user’s original identity provider. Amazon Cognito indicates this UUID in the `sub` claim in the identity pool token.

The following example role trust policy allows the federated service principal `cognito-identity.amazonaws.com` to call the AWS STS API `AssumeRoleWithWebIdentity`. The request will only succeed if the identity pool token in the API request has the following claims.

1. An `aud` claim of the identity pool ID `us-west-2:abcdefg-1234-5678-910a-0e8443553f95`.

1. An `amr` claim of `authenticated` that is added when the user has signed in and isn't a guest user.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "cognito-identity.amazonaws.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "cognito-identity.amazonaws.com:aud": "us-west-2:abcdefg-1234-5678-910a-0e8443553f95"
                },
                "ForAnyValue:StringLike": {
                    "cognito-identity.amazonaws.com:amr": "authenticated"
                }
            }
        }
    ]
}
```

------

### Trust policies for IAM roles in Basic (Classic) authentication
<a name="trust-policies-classic"></a>

**Summary**  
Identity pools can only assume roles on behalf of users in the [Basic authentication flow](authentication-flow.md#authentication-flow-basic) when the trust policy of the target role contains the `aud` condition.

Basic authentication has the same limitation on insecure role trust policies as enhanced authentication: you can't save a role trust policy that fails to limit supported identity pools with an `aud` condition. This limitation was not enforced when the service launched. Prior to the enforcement of this requirement, you could create role trust policies that had no additional security conditions. After the enforcement of this requirement, AWS STS permits web identities to assume roles that are not secured with conditions, but those roles **can't be modified** without introducing those conditions.

Enhanced-flow authentication requires that the IAM role be in the same AWS account as the identity pool. But in basic authentication, where your application composes the `AssumeRoleWithWebIdentity` request, your application can request to assume a role in a different account. Your [cross-account](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) assume role request will fail, though, if the destination role has a legacy trust policy that doesn't enforce the `aud` condition.

The token that an identity pool issues for an identity contains information about the originating AWS account of the identity pool. When you present an identity pool token in an [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API request, AWS STS checks to see if the originating identity pool is in the same AWS account as the IAM role. If AWS STS determines that the request is cross-account, it checks to see if the role trust policy has an `aud` condition. **The assume-role call fails** if no such condition is present in the role trust policy. If the request is not cross-account, AWS STS doesn’t enforce this restriction. As a best practice, always apply a condition of this type to the trust policies of your identity pool roles.

The following is an example trust policy that meets the *minimum* requirements for an IAM role for basic authentication with several identity pools. As a best practice, permit only authenticated identities with a `"cognito-identity.amazonaws.com:amr": "authenticated"` condition too.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "cognito-identity.amazonaws.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "cognito-identity.amazonaws.com:aud": [
                        "us-west-2:abcdefg-1234-5678-910a-0e8443553f95",
                        "us-west-2:hijklmo-5678-9101-112b-0e4221776g96",
                        "us-west-2:pqrstuv-9101-1121-314c-0e2110887h97"
                    ]
                }
            }
        }
    ]
}
```

------

### Additional trust policy conditions
<a name="trust-policies-examples"></a>

You can use the following trust policy conditions to define the source identity pools, identities, and providers that can assume IAM roles.

**Note**  
Don't implement the [aws:SourceIp](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceip) condition key in trust policies for IAM roles that identity pools assume in the [enhanced authentication flow](authentication-flow.md#authentication-flow-enhanced). Because the enhanced flow generates the [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) request on behalf of your application, the source IP of the request will not be the IP of your application client, and the condition will never be satisfied. Network-based condition keys are valid for roles that identity pools assume through *only* the [basic flow](authentication-flow.md#authentication-flow-basic), which lacks the service-side features of the enhanced flow.

**Reuse roles across identity pools**  
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"
    ]
}
```

**Limit access to specific identities**  
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"
    ]
}
```

**Limit access to specific providers**  
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": {
    "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
<a name="access-policies"></a>

The permissions that you attach to a role apply to all users who assume that role. To partition your users' access, use policy conditions and variables. For more information, see [IAM policy elements: Variables and tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html). You can use the `sub` condition to restrict actions to Amazon Cognito identity IDs in your access policies. Use this option with caution, particularly for unauthenticated identities, which lack a consistent user ID. For more information about the IAM policy variables for web federation with Amazon Cognito, see [IAM and AWS STS condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-wif) in the *AWS Identity and Access Management User Guide*.

For additional security protection, Amazon Cognito applies a scope-down policy to credentials that you assign your unauthenticated users in the [enhanced flow](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flow.html), using `GetCredentialsForIdentity`. The scope-down policy adds an [Inline session policy](#access-policies-inline-policy) and an [AWS managed session policy](#access-policies-managed-policy) to the IAM policies that you apply to your unauthenticated role. Because you must grant access in both the IAM policies for your role and the session policies, the scope-down policy limits users' access to services other than those in the list that follows.

**Note**  
In the basic (classic) flow, you make your own [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API request, and can apply these restrictions to the request. As a best security practice, don't assign any permissions above this scope-down policy to unauthenticated users.

Amazon Cognito also prevents authenticated and unauthenticated users from making API requests to Amazon Cognito identity pools and Amazon Cognito Sync. Other AWS services might place restrictions on service access from web identities.

In a successful request with the enhanced flow, Amazon Cognito makes an `AssumeRoleWithWebIdentity` API request in the background. Among the parameters in this request, Amazon Cognito includes the following.

1. Your user's identity ID.

1. The ARN of the IAM role that your user wants to assume.

1. A `policy` parameter that adds an *inline session policy*.

1. A `PolicyArns.member.N` parameter whose value is an *AWS managed policy* that grants additional permissions in Amazon CloudWatch.

### Services that unauthenticated users can access
<a name="access-policies-scope-down-services"></a>

When you use the enhanced flow, the scope-down policies that Amazon Cognito applies to your user's session prevent them from using any services other than those listed in the following table. For a subset of services, only specific actions are allowed.


| Category | Service | 
| --- | --- | 
|  Analytics  |  Amazon Data Firehose Amazon Managed Service for Apache Flink  | 
|  Application Integration  |  Amazon Simple Queue Service  | 
| AR & VR |  Amazon Sumerian¹  | 
| Business Applications |  Amazon Mobile Analytics Amazon Simple Email Service  | 
| Compute |  AWS Lambda  | 
| Cryptography & PKI |  AWS Key Management Service¹  | 
| Database |  Amazon DynamoDB Amazon SimpleDB  | 
| Front-end Web & Mobile |  AWS AppSync Amazon Location Service Amazon Simple Notification Service Amazon Pinpoint Amazon Location Service  | 
| Game Development |  Amazon GameLift Servers  | 
| Internet of Things (IoT) |  AWS IoT  | 
| Machine Learning |  Amazon CodeWhisperer Amazon Comprehend Amazon Lex Amazon Machine Learning Amazon Personalize Amazon Polly Amazon Rekognition Amazon SageMaker AI¹ Amazon Textract¹ Amazon Transcribe Amazon Translate  | 
| Management & Governance |  Amazon CloudWatch Amazon CloudWatch Logs  | 
| Networking & Content Delivery |  Amazon API Gateway  | 
| Security, Identity, & Compliance |  Amazon Cognito user pools  | 
| Storage |  Amazon Simple Storage Service  | 

¹ For the AWS services in the following table, the inline policy grants a subset of actions. The table displays the available actions in each.


| AWS service | Maximum permissions for unauthenticated enhanced flow users | 
| --- | --- | 
| AWS Key Management Service |  `Encrypt` `Decrypt` `ReEncryptTo` `ReEncryptFrom` `GenerateDataKey` `GenerateDataKeyPair` `GenerateDataKeyPair` `GenerateDataKeyPairWithoutPlaintext` `GenerateDataKeyWithoutPlaintext`  | 
| Amazon SageMaker AI |  `InvokeEndpoint`  | 
| Amazon Textract |  `DetectDocumentText` `AnalyzeDocument`  | 
| Amazon Sumerian |  `View*`  | 
| Amazon Location Service |  `SearchPlaceIndex*` `GetPlace` `CalculateRoute*` `*Geofence` `*Geofences` `*DevicePosition*`  | 

To grant access to AWS services beyond this list, activate the **basic (classic) authentication flow** in your identity pool. If your users see `NotAuthorizedException` errors from AWS services that are allowed by the policies assigned to the IAM role for unauthenticated users, evaluate whether you can remove that service from your use case. If you can't, switch to the basic flow.

### The inline session policy for guest users
<a name="access-policies-inline-policy"></a>

Amazon Cognito first applies an inline policy in the request for IAM credentials. The inline session policy restricts your user's effective permissions from including access to any AWS services outside those in the following list. You must also grant permissions to these AWS services in the policies that you apply to the user's IAM role. A user's effective permissions for an assumed-role session are the intersection of the policies assigned to their role, and their session policy. For more information, see [Session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) in the *AWS Identity and Access Management User Guide*.

Amazon Cognito adds the following inline policy to sessions for your users in AWS Regions that are enabled by default. For an overview of the net effect of the inline policy and other session policies, see [Services that unauthenticated users can access](#access-policies-scope-down-services).

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "cloudwatch:*",
                "logs:*",
                "dynamodb:*",
                "kinesis:*",
                "mobileanalytics:*",
                "s3:*",
                "ses:*",
                "sns:*",
                "sqs:*",
                "lambda:*",
                "machinelearning:*",
                "execute-api:*",
                "iot:*",
                "gamelift:*",
                "cognito-identity:*",
                "cognito-idp:*",
                "lex:*",
                "polly:*",
                "comprehend:*",
                "translate:*",
                "transcribe:*",
                "rekognition:*",
                "mobiletargeting:*",
                "firehose:*",
                "appsync:*",
                "personalize:*",
                "sagemaker:InvokeEndpoint",
                "cognito-sync:*",
                "codewhisperer:*",
                "textract:DetectDocumentText",
                "textract:AnalyzeDocument",
                "sdb:*"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

------

For all other Regions, the inline scope-down policy includes everything listed in the default Regions except for the following `Action` statements.

```
                "cognito-sync:*",
                "sumerian:View*",
                "codewhisperer:*",
                "textract:DetectDocumentText",
                "textract:AnalyzeDocument",
                "sdb:*"
```

### The AWS managed session policy for guests
<a name="access-policies-managed-policy"></a>

Amazon Cognito also applies an AWS managed policy as a session policy to the enhanced-flow sessions of unauthenticated guests. This policy limits the scope of unauthenticated users' permissions with the policy `AmazonCognitoUnAuthedIdentitiesSessionPolicy`.

You must also grant this permission in the policies that you attach to your unauthenticated IAM role. A user's effective permissions for an assumed-role session are the intersection of the IAM policies assigned to their role, and their session policies. For more information, see [Session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) in the *AWS Identity and Access Management User Guide*.

For an overview of the net effect of this AWS managed policy and other session policies, see [Services that unauthenticated users can access](#access-policies-scope-down-services).

The `AmazonCognitoUnAuthedIdentitiesSessionPolicy` managed policy has the following permissions.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
        "Effect": "Allow",
        "Action": [
            "rum:PutRumEvents",
            "polly:*",
            "comprehend:*",
            "translate:*",
            "transcribe:*",
            "rekognition:*",
            "mobiletargeting:*",
            "firehose:*",
            "personalize:*",
            "sagemaker:InvokeEndpoint",
            "geo:GetMap*",
            "geo:SearchPlaceIndex*",
            "geo:GetPlace",
            "geo:CalculateRoute*",
            "geo:*Geofence",
            "geo:*Geofences",
            "geo:*DevicePosition*",
            "kms:Encrypt",
            "kms:Decrypt",
            "kms:ReEncryptTo",
            "kms:ReEncryptFrom",
            "kms:GenerateDataKey",
            "kms:GenerateDataKeyPair",
            "kms:GenerateDataKeyPairWithoutPlaintext",
            "kms:GenerateDataKeyWithoutPlaintext"
        ],
        "Resource": "*"
    }]
}
```

------

### Access policy examples
<a name="access-policy-examples"></a>

In this section, you can find example Amazon Cognito access policies that grant your users the minimum permissions necessary to do specific operation. You can further limit the permissions for a given identity ID by using policy variables where possible. For example, using \$1\$1cognito-identity.amazonaws.com:sub\$1. For more information, see [Understanding Amazon Cognito Authentication Part 3: Roles and Policies](https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-authentication-part-3-roles-and-policies/) on the *AWS Mobile Blog*.

**Note**  
As a security best practice, policies should include only the permissions that users require to perform their tasks. This means that you should try to always scope access to an individual identity for objects whenever possible.

**Grant an identity read access to a single object in Amazon S3**  
The following access policy grants read permissions to an identity to retrieve a single object from a given S3 bucket.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::amzn-s3-demo-bucket/assets/my_picture.jpg"]
    }
  ]
}
```

------

**Grant an identity both read and write access to identity specific paths in Amazon 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.

With this policy, an identity such as `us-east-1:12345678-1234-1234-1234-123456790ab` inserted via `${cognito-identity.amazonaws.com:sub}` can get, put, and list objects into `arn:aws:s3:::amzn-s3-demo-bucket/us-east-1:12345678-1234-1234-1234-123456790ab`. However, the identity would not be granted access to other objects in `arn:aws:s3:::amzn-s3-demo-bucket`.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": ["s3:ListBucket"],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::amzn-s3-demo-bucket"],
      "Condition": {"StringLike": {"s3:prefix": ["${cognito-identity.amazonaws.com:sub}/*"]}}
    },
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::amzn-s3-demo-bucket/${cognito-identity.amazonaws.com:sub}/*"]
    }
  ]
}
```

------

A similar access model is achieved with [Amazon S3 Access Grants](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-grants.html).

**Assign identities fine-grained access to Amazon DynamoDB**  
The following access policy provides fine-grained access control to DynamoDB resources using Amazon Cognito environment variables. These variables grant access to items in DynamoDB by identity ID. For more information, see [Using IAM Policy Conditions for Fine-Grained Access Control](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/specifying-conditions.html) in the *Amazon DynamoDB Developer Guide*.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:BatchGetItem",
        "dynamodb:Query",
        "dynamodb:PutItem",
        "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}"]
        }
      }
    }
  ]
}
```

------

**Grant an identity permission to invoke a Lambda function**  
The following access policy grants an identity permission to invoke a Lambda function.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
         { 
             "Effect": "Allow",
             "Action": "lambda:InvokeFunction",
             "Resource": [
                 "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
             ]
         }
     ]
 }
```

------

**Grant an identity permission to publish records to Kinesis Data Streams**  
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](https://docs.aws.amazon.com/streams/latest/dev/controlling-access.html) in the *Amazon Kinesis Data Streams Developer Guide*.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "kinesis:PutRecord",
            "Resource": [
                "arn:aws:kinesis:us-east-1:111122223333:stream/stream1"
            ]
        }
    ]
}
```

------

**Grant an identity access to their data in the Amazon Cognito Sync store**  
The following access policy grants an identity permissions to access only their own data in the Amazon Cognito Sync store.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "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}/*"]
      }]
  }
```

------

## Role trust and permissions
<a name="role-trust-and-permissions"></a>

The way these roles differ is in their trust relationships. The following is an example trust policy for an unauthenticated role:

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

****  

```
{
  "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 grants federated users from `cognito-identity.amazonaws.com` (the issuer of the OpenID Connect token) permission 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 one of the array members of the multi-value `amr` claim of the token issued by the Amazon Cognito `GetOpenIdToken` API operation has the value `unauthenticated`.

When Amazon Cognito creates a token, it sets the `amr` of the token as either `unauthenticated` or `authenticated`. If `amr` is `authenticated`, the token includes any providers used during authentication. This means that you can create a role that trusts only users that logged in via Facebook by changing the `amr` condition as shown:

```
"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 you don't configure your role correctly to trust your identity pool, an exception from STS results, like the following:

```
AccessDenied -- Not authorized to perform sts:AssumeRoleWithWebIdentity
```

If you see this message, check that your identity pool and authentication type have an appropriate role.

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

Amazon Cognito identity pools provide temporary AWS credentials for your application. AWS accounts often contain both the resources that your application users need, and private back-end resources. The IAM roles and policies that make up AWS credentials can grant access to any of these resources.

The primary best practice of identity pool configuration is to ensure that your application can get the job done without excess or unintended privilege. To guard against security misconfiguration, review these recommendations before the launch of each application that you want to release to production.

**Topics**
+ [IAM configuration best practices](#identity-pools-security-best-practices-iam)
+ [Identity pool configuration best practices](#identity-pools-security-best-practices-cib)

## IAM configuration best practices
<a name="identity-pools-security-best-practices-iam"></a>

When a guest or authenticated user initiates a session in your application that requires identity pool credentials, your application retrieves temporary AWS credentials for an IAM role. The credentials might be for a default role, a role chosen by rules in your identity pool configuration, or for a custom role chosen by your app. With the permissions assigned to each role, your user gains access to your AWS resources.

For more information about general IAM best practices, see [IAM best practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the AWS Identity and Access Management User Guide.

### Use trust policy conditions in IAM roles
<a name="identity-pools-security-best-practices-iam-conditions"></a>

IAM requires that roles for identity pools have at least one trust policy condition. This condition can, for example, set the role’s scope to authenticated users only. AWS STS also requires that cross-account basic authentication requests have two specific conditions: `cognito-identity.amazonaws.com:aud` and `cognito-identity.amazonaws.com:amr`. As a best practice, apply both of these conditions in all IAM roles that trust the identity pools service principal `cognito-identity.amazonaws.com`.
+ `cognito-identity.amazonaws.com:aud`: The *aud* claim in the identity pool token must match a trusted identity pool ID.
+ `cognito-identity.amazonaws.com:amr`: The *amr* claim in the identity pool token must be either *authenticated* or *unauthenticated*. With this condition, you can reserve access to a role only to unauthenticated guests, or only to authenticated users. You can further refine the value of this condition to restrict the role to users from a specific provider, for example `graph.facebook.com`.

The following example role trust policy grants access to a role under the following conditions:

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

****  

```
{
  "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:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
        },
        "ForAnyValue:StringLike": {
          "cognito-identity.amazonaws.com:amr": "authenticated"
        }
      }
    }
  ]
}
```

------

**Elements that relate to identity pools**
+ `"Federated": "cognito-identity.amazonaws.com"`: Users must come from an identity pool.
+ `"cognito-identity.amazonaws.com:aud": "us-east-1:a1b2c3d4-5678-90ab-cdef-example11111"`: Users must come from the specific identity pool `us-east-1:a1b2c3d4-5678-90ab-cdef-example11111`.
+ `"cognito-identity.amazonaws.com:amr": "authenticated"`: Users must be authenticated. Guest users can’t assume the role.

### Apply least privilege permissions
<a name="identity-pools-security-best-practices-iam-least-privilege"></a>

When you set permissions with IAM policies for authenticated access or guest access, grant only the specific permissions required to perform specific tasks, or *least privilege* permissions. The following example IAM policy, when applied to a role, grants read-only access to a single image file in an Amazon S3 bucket.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::mybucket/assets/my_picture.jpg"]
    }
  ]
}
```

------

## Identity pool configuration best practices
<a name="identity-pools-security-best-practices-cib"></a>

Identity pools have flexible options for the generation of AWS credentials. Don’t take design shortcuts when your application can work with the most secure methods.

### Understand the effects of guest access
<a name="identity-pools-security-best-practices-cib-guest"></a>

Unauthenticated guest access permits users to retrieve data from your AWS account before they sign in. Anyone who knows your identity pool ID can request unauthenticated credentials. Your identity pool ID isn’t confidential information. When you activate guest access, the AWS permissions that you grant to unauthenticated sessions are available to everyone.

As a best practice, leave guest access deactivated and fetch required resources only after users authenticate. If your application requires access to resources before sign-in, take the following precautions.
+ Familiarize yourself with the [automatic limitations placed on unauthenticated roles](iam-roles.md#access-policies-scope-down-services).
+ Monitor and adjust the permissions of your unauthenticated IAM roles to match the specific needs of your application.
+ Grant access to specific resources.
+ Secure the trust policy of your default unauthenticated IAM role.
+ Activate guest access only when you are confident that you would grant the permissions in your IAM role to anyone on the internet.

### Use enhanced authentication by default
<a name="identity-pools-security-best-practices-cib-enhanced"></a>

With basic (classic) authentication, Amazon Cognito delegates selection of the IAM role to your app. In contrast, the enhanced flow uses the centralized logic in your identity pool to determine the IAM role. It also provides additional security for unauthenticated identities with a [scope-down policy](iam-roles.md#access-policies-scope-down-services) that sets an upper limit on IAM permissions. The enhanced flow is the most secure choice with the lowest level of developer effort. To learn more about these options, see [Identity pools authentication flow](authentication-flow.md) .

The basic flow can expose the client-side logic that goes into role selection and assembly of the AWS STS API request for credentials. The enhanced flow hides both the logic and the assume-role request behind identity pool automation.

When you configure basic authentication, apply [IAM best practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) to your IAM roles and their permissions.

### Use developer providers securely
<a name="identity-pools-security-best-practices-cib-developer"></a>

Developer authenticated identities are a feature of identity pools for server-side applications. The only evidence of authentication that identity pools require for developer authentication are the AWS credentials of an identity pool developer. Identity pools don’t enforce any restrictions on the validity of the developer-provider identifiers that you present in this authentication flow.

As a best practice, only implement developer providers under the following conditions:
+ To create accountability for the use of developer-authenticated credentials, design your developer provider name and identifiers to indicate the authentication source. For example: `"Logins" : {"MyCorp provider" : "[provider application ID]"}`.
+ Avoid long-lived user credentials. Configure your server-side client to request identities with service-linked roles like [EC2 instance profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) and [Lambda execution roles](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html).
+ Avoid mixing internal and external sources of trust in the same identity pool. Add your developer provider and your single sign-on (SSO) providers in separate identity pools.

# Using attributes for access control
<a name="attributes-for-access-control"></a>

Attributes for access control is the Amazon Cognito identity pools implementation of attribute-based access control (ABAC). You can use IAM policies to control access to AWS resources through Amazon Cognito identity pools based on user attributes. These attributes can be drawn from social and corporate identity providers. You can map attributes within providers’ access and ID tokens or SAML assertions to tags that can be referenced in the IAM permissions policies. 

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 a 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 the 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](#using-afac-with-cognito-identity-pools)
+ [Using attributes for access control policy example](#using-attributes-for-access-control-policy-example)
+ [Turn off attributes for access control (console)](#disable-afac)
+ [Default provider mappings](#provider-mappings)

Using attributes to control access has several benefits:
+ Permissions management is more efficient 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](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_abac-saml.html).
+ Attributes can be passed as principal tags to a policy that allows or denies permissions based on the values of those attributes.

## Using attributes for access control with Amazon Cognito identity pools
<a name="using-afac-with-cognito-identity-pools"></a>

Before you can use attributes for access control, ensure that you meet the following prerequisites:
+ [An AWS account](https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-with-identity-pools.html#aws-sign-up-identity-pools)
+ [User pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-as-user-directory.html)
+ [Identity pool](https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-with-identity-pools.html#create-identity-pools)
+ [Set up an SDK](getting-started-with-identity-pools.md#install-the-mobile-or-javascript-sdk)
+ [Integrated identity providers](https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-with-identity-pools.html##integrate-the-identity-providers)
+ [Credentials](https://docs.aws.amazon.com/cognito/latest/developerguide/getting-started-with-identity-pools.html#get-credentials)

To use attributes for access control, the **Claim** that you set as the source of data sets the value of the **Tag Key** that you choose. Amazon Cognito applies the tag key and value to your user's session. Your IAM policies can evaluate your user's access from the `${aws:PrincipalTag/tagkey}` condition. IAM evaluates the value of your user's tag against the policy.

You must prepare IAM roles whose credentials you want to pass to your users. The trust policy of these roles must permit Amazon Cognito to assume the role for your user. For attributes for access control, you must also allow Amazon Cognito to apply principal tags to your user's temporary session. Grant permission to assume the role with the action [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html). Grant permission to tag users' sessions with the [permission-only action](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssecuritytokenservice.html#awssecuritytokenservice-actions-as-permissions) `sts:TagSession`. For more information, see [Passing session tags in AWS Security Token Service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) in the *AWS Identity and Access Management User Guide*. For an example trust policy that grants `sts:AssumeRoleWithWebIdentity` and `sts:TagSession` permissions to the Amazon Cognito service principal `cognito-identity.amazonaws.com`, see [Using attributes for access control policy example](#using-attributes-for-access-control-policy-example).

**To configure attributes for access control in the console**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home) and select **Identity pools**. Select an identity pool.

1. Choose the **User access** tab.

1. Locate **Identity providers**. Choose the identity provider that you want to edit. If you want to add a new IdP, select **Add identity provider**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, choose **Edit** in **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

## Using attributes for access control policy example
<a name="using-attributes-for-access-control-policy-example"></a>

Consider a scenario where an employee from the legal department of a company needs to list all files in buckets that belong to their department and are classified with their security level. Assume the token that this employee gets from the identity provider contains the following claims. 

**Claims**

```
            { .
              .
            "sub" : "57e7b692-4f66-480d-98b8-45a6729b4c88",
            "department" : "legal",
            "clearance" : "confidential",
             .
             .
            }
```

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.

The following permissions policy does two things:
+ 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**

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

****  

```
   {
    "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 makes sure that it’s for an authenticated role.

**Trust policy**

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

****  

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

------

## Turn off attributes for access control (console)
<a name="disable-afac"></a>

Follow this procedure to deactivate attributes for access control.

**To deactivate attributes for access control in the console**

1. Sign in to the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home) and select **Identity pools**. Select an identity pool.

1. Choose the **User access** tab.

1. Locate **Identity providers**. Choose the identity provider that you want to edit.

1. Choose **Edit** in **Attributes for access control**.

1. To apply no principal tags, choose **Inactive**.

1. Select **Save changes**.

## Default provider mappings
<a name="provider-mappings"></a>

The following table has the default mapping information for the authentication providers that Amazon Cognito supports.


| Provider | Token type | Principal tag values | Example | 
| --- | --- | --- | --- | 
|  Amazon Cognito user pool  |  ID token  |  aud(client ID) and sub(user ID)  |  "6jk8ltokc7ac9es6jrtg9q572f", "57e7b692-4f66-480d-98b8-45a6729b4c88"   | 
|  Facebook  |  Access token  |  aud(app\$1id), sub(user\$1id)  |  "492844718097981", "112177216992379"  | 
|  Google  |  ID token  |  aud(client ID) and sub(user ID)  |  "620493171733-eebk7c0hcp5lj3e1tlqp1gntt3k0rncv.apps.googleusercontent.com", "109220063452404746097"  | 
|  SAML  |  Assertions  |  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" , "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"   |  "auth0\$15e28d196f8f55a0eaaa95de3", "user123@gmail.com"  | 
|  Apple  |  ID token  |  aud(client ID) and sub (user ID)  |  "com.amazonaws.ec2-54-80-172-243.compute-1.client", "001968.a6ca34e9c1e742458a26cf8005854be9.0733"  | 
|  Amazon  |  Access token  |  aud (Client ID on Amzn Dev Ac), user\$1id(user ID)  |  "amzn1.application-oa2-client.9d70d9382d3446108aaee3dd763a0fa6", "amzn1.account.AGHNIFJQMFSBG3G6XCPVB35ORQAA"  | 
|  Standard OIDC providers  |  ID and access tokens  |  aud (as client\$1id), sub (as user ID)  |  "620493171733-eebk7c0hcp5lj3e1tlqp1gntt3k0rncv.apps.googleusercontent.com", "109220063452404746097"  | 
|  Twitter  |  Access token  |  aud (app ID; app Secret), sub (user ID)  |  "DfwifTtKEX1FiIBRnOTlR0CFK;Xgj5xb8xIrIVCPjXgLIdkW7fXmwcJJrFvnoK9gwZkLexo1y5z1", "1269003884292222976"  | 
|  DevAuth  |  Map  |  Not applicable  |  "tag1", "tag2"  | 

**Note**  
The default attribute mappings option is automatically populated for the **Tag Key for Principal** and **Attribute** names. You can't change default mappings.

# Using role-based access control
<a name="role-based-access-control"></a>

Amazon Cognito identity pools assign your authenticated users a set of temporary, limited-privilege credentials to access your AWS resources. The permissions for each user are controlled through [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) that you create. You can define rules to choose the role for each user based on claims in the user's ID token. You can define a default role for authenticated users. You can also define a separate IAM role with limited permissions for guest users who are not authenticated.

## Creating roles for role mapping
<a name="creating-roles-for-role-mapping"></a>

It is important to add the appropriate trust policy for each role so that it can only be assumed by Amazon Cognito for authenticated users in your identity pool. Here is an example of such a trust policy:

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

****  

```
{
  "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 one of the array members of the multi-value `amr` claim of the token issued by the Amazon Cognito `GetOpenIdToken` API action has the value `authenticated`.

## Granting pass-role permission
<a name="granting-pass-role-permission"></a>

To allow a user to set roles with permissions in excess of the user's existing permissions on an identity pool, grant them `iam:PassRole` permission to pass the role to the `set-identity-pool-roles` API. For example, if the user cannot write to Amazon S3, but the IAM role that the user sets on the identity pool grants write permission to Amazon S3, the user can only set this role if `iam:PassRole` permission is granted for the role. The following example policy shows how to allow `iam:PassRole` permission.

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

****  

```
{
    "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 Amazon Resource Name (ARN). You must also attach this policy to your user. For more information, see [Working with Managed Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-using.html).

**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](https://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#intro-permission-model-access-policy).

## Using tokens to assign roles to users
<a name="using-tokens-to-assign-roles-to-users"></a>

For users who log in through Amazon Cognito user pools, roles can be passed in the ID token that was assigned by the user pool. The roles appear in the following claims in the ID token:
+ The `cognito:preferred_role` claim is the role ARN.
+ The `cognito:roles` claim is a comma-separated string containing a set of allowed role ARNs.

The claims are set as follows:
+ 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](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html) `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.
+ If the `cognito:preferred_role` claim is set, use it.
+ If the `cognito:preferred_role` claim is not set, the `cognito:roles` claim is set, and `CustomRoleArn` is not specified in the call to `GetCredentialsForIdentity`, then the **Role resolution** setting in the console or the `AmbiguousRoleResolution` field (in the `RoleMappings` parameter of the [SetIdentityPoolRoles](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_SetIdentityPoolRoles.html) API) is used to determine the role to be assigned.

## Using rule-based mapping to assign roles to users
<a name="using-rules-to-assign-roles-to-users"></a>

Rules allow you to map claims from an identity provider token to IAM roles.

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 [Working with user attributes](user-pool-settings-attributes.md).

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 request**.

In the API and CLI, you can specify the role to be assigned when no rules match in the `AmbiguousRoleResolution` field of the [RoleMapping](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_RoleMapping.html) type, which is specified in the `RoleMappings` parameter of the [SetIdentityPoolRoles](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_SetIdentityPoolRoles.html) API.

To add rule-based mapping to an identity provider in the Amazon Cognito console, add or update an IdP and select **Choose role with rules** under **Role selection**. From there, you can add rules that map provider claims to IAM roles.

You can set up rule-based mapping for identity providers in the AWS CLI or API with the `RulesConfiguration` field of the [RoleMapping](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_RoleMapping.html) type. You can specify this field in the `RoleMappings` parameter of the [SetIdentityPoolRoles](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_SetIdentityPoolRoles.html) API.

For example, the following AWS CLI command adds a rule that assigns the role `arn:aws:iam::123456789012:role/Sacramento_team_S3_admin` to users in your Sacramento location who were authenticated by OIDC IdP `arn:aws:iam::123456789012:oidc-provider/myOIDCIdP`:

```
aws cognito-identity set-identity-pool-roles --region us-east-1 --cli-input-json file://role-mapping.json
```

**Contents of `role-mapping.json`**:

```
{
    "IdentityPoolId": "us-east-1:12345678-corner-cafe-123456790ab",
    "Roles": {
        "authenticated": "arn:aws:iam::123456789012:role/myS3WriteAccessRole",
        "unauthenticated": "arn:aws:iam::123456789012:role/myS3ReadAccessRole"
    },
    "RoleMappings": {
        "arn:aws:iam::123456789012:oidc-provider/myOIDCIdP": {
            "Type": "Rules",
            "AmbiguousRoleResolution": "AuthenticatedRole",
            "RulesConfiguration": {
                "Rules": [
                    {
                        "Claim": "locale",
                        "MatchType": "Equals",
                        "Value": "Sacramento",
                        "RoleARN": "arn:aws:iam::123456789012:role/Sacramento_team_S3_admin"
                    }
                ]
            }
        }
    }
}
```

For each user pool or other authentication provider that you configure for an identity pool, you can create up to 25 rules. This limit is not adjustable. For more information, see [Quotas in Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/limits.html).

## Token claims to use in rule-based mapping
<a name="token-claims-for-role-based-access-control"></a>

**Amazon Cognito**

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](http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). 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
+ `sub`: `sub` from the Login with Amazon token

**Facebook**

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

**Google**

A Google token contains standard claims from the [OpenID Connect specification](http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). All of the claims in the OpenID token are available for rule-based mapping. See Google's [OpenID Connect](https://developers.google.com/identity/protocols/OpenIDConnect) site to learn about the claims available from the Google token.

**Apple**

An Apple token contains standard claims from the [OpenID Connect specification](http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). See [Authenticating Users with Sign in with Apple](https://developer.apple.com/documentation/signinwithapple/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](http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). 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.

## Best practices for role-based access control
<a name="best-practices-for-role-based-access-control"></a>

**Important**  
If the claim that you are mapping to a role can be modified by the end user, any end user can assume your role and set the policy accordingly. Only map claims that cannot be directly set by the end user to roles with elevated permissions. In an Amazon Cognito user pool, you can set per-app read and write permissions for each user attribute.

**Important**  
If you set roles for groups in an Amazon Cognito user pool, those roles are passed through the user's ID token. To use these roles, you must also set **Choose role from token** for the authenticated role selection for the identity pool.  
You can use the **Role resolution** setting in the console and the `RoleMappings` parameter of the [SetIdentityPoolRoles](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_SetIdentityPoolRoles.html) API to specify what the default behavior is when the correct role cannot be determined from the token.

# Getting credentials
<a name="getting-credentials"></a>

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.

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 must reassociate your roles with your identity pool to use the `AWS.CognitoIdentityCredentials` constructor without the roles as parameters. To do so, open the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home), choose **Manage identity pools**, select your identity pool, choose **Edit identity Pool**, specify your authenticated and unauthenticated roles, and save the changes. 

Web identity credentials providers are part of the default credential provider chain in AWS SDKs. To set your identity pool token in a local `config` file for an AWS SDK or the AWS CLI, add a `web_identity_token_file` profile entry. See [Assume role credential provider](https://docs.aws.amazon.com/sdkref/latest/guide/feature-assume-role-credentials.html) in the AWS SDKs and Tools Reference Guide.

To learn more about how to populate web identity credentials in your SDK, refer to the SDK developer guide. For best results, start your project with the identity pool integration that's built in to AWS Amplify.

**AWS SDK resources for getting and setting credentials with identity pools**
+ [Identity Pool Federation](https://docs.amplify.aws/lib/auth/advanced/q/platform/android/#identity-pool-federation) (Android) in the Amplify Dev Center
+ [Identity Pool Federation](https://docs.amplify.aws/lib/auth/advanced/q/platform/ios/#identity-pool-federation) (iOS) in the Amplify Dev Center
+ [Using Amazon Cognito Identity to authenticate users](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/loading-browser-credentials-cognito.html) in the AWS SDK for JavaScript Developer Guide
+ [Amazon Cognito credentials provider](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/cognito-creds-provider.html) in the AWS SDK for .NET Developer Guide
+ [Specify Credentials Programmatically](https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/#specify-credentials-programmatically) in the AWS SDK for Go Developer Guide
+ [Supply temporary credentials in code](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials-explicit.html) in the AWS SDK for Java 2.x Developer Guide
+ [assumeRoleWithWebIdentityCredentialProvider](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_provider.html#assume-role-with-web-identity-provider) provider in the AWS SDK for PHP Developer Guide
+ [Assume Role With Web Identity Provider](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#assume-role-with-web-identity-provider) in the AWS SDK for Python (Boto3) documentation
+ [Specifying your credentials and default region](https://docs.aws.amazon.com/sdk-for-rust/latest/dg/credentials.html) in the AWS SDK for Rust Developer Guide

The following sections provide example code in some legacy AWS SDKs.

## Android
<a name="getting-credentials-1.android"></a>

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.

To use a Amazon Cognito identity pool in an Android app, set up AWS Amplify. For more information, see [Authentication](https://docs.amplify.aws/lib/auth/getting-started/q/platform/android/) in the *Amplify Dev Center*.

**Retrieving an Amazon Cognito identity**

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:

```
String identityId = credentialsProvider.getIdentityId();
Log.d("LogTag", "my ID is " + identityId);
```

**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](https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html) if you perform network I/O on the main application thread. You must move your code to a background thread using `AsyncTask`. For more information, consult the [Android documentation](https://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask). 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
<a name="getting-credentials-1.ios-objc"></a>

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, complete the following steps. 

To use a Amazon Cognito identity pool in an iOS app, set up AWS Amplify. For more information, see [Swift Authentication](https://docs.amplify.aws/lib/auth/getting-started/q/platform/ios/) and [Flutter Authentication](https://docs.amplify.aws/lib/auth/getting-started/q/platform/flutter/) in the *Amplify Dev Center*.

**Retrieving an Amazon Cognito identity**

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:

```
// Retrieve your Amazon Cognito ID
[[credentialsProvider getIdentityId] continueWithBlock:^id(AWSTask *task) {
    if (task.error) {
        NSLog(@"Error: %@", task.error);
    }
    else {
        // the task result will contain the identity id
        NSString *cognitoId = task.result;
    }
    return nil;
}];
```

**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 [Amplify iOS SDK reference](https://github.com/aws-amplify/aws-sdk-ios). 

## iOS - Swift
<a name="getting-credentials-1.ios-swift"></a>

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. 

To use a Amazon Cognito identity pool in an iOS app, set up AWS Amplify. For more information, see [Swift Authentication](https://docs.amplify.aws/lib/auth/getting-started/q/platform/ios/) in the *Amplify Dev Center*.

**Retrieving an Amazon Cognito identity**

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:

```
// Retrieve your Amazon Cognito ID
credentialsProvider.getIdentityId().continueWith(block: { (task) -> AnyObject? in
    if (task.error != nil) {
        print("Error: " + task.error!.localizedDescription)
    }
    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 [Amplify iOS SDK reference](https://github.com/aws-amplify/aws-sdk-ios). 

## JavaScript
<a name="getting-credentials-1.javascript"></a>

If you have not yet created one, create an identity pool in the [Amazon Cognito console](https://console.aws.amazon.com/cognito) 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';

// Configure the credentials provider to use your identity pool
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'IDENTITY_POOL_ID',
    Logins: { // optional tokens, used for authenticated login
        'graph.facebook.com': 'FBTOKEN',
        'www.amazon.com': 'AMAZONTOKEN',
        'accounts.google.com': 'GOOGLETOKEN',
        'appleid.apple.com': 'APPLETOKEN'
    }
});

// Make the call to obtain credentials
AWS.config.credentials.get(function(){

    // Credentials will be available when this function is called.
    var accessKeyId = AWS.config.credentials.accessKeyId;
    var secretAccessKey = AWS.config.credentials.secretAccessKey;
    var sessionToken = AWS.config.credentials.sessionToken;

});
```

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](https://developers.facebook.com/docs/facebook-login/web) 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: {
            'graph.facebook.com': response.authResponse.accessToken
          }
        });

        console.log('You are now logged in.');
    } else {
        console.log('There was a problem logging you in.');
    }
});
```

**Retrieving an Amazon Cognito identity**

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:

```
var identityId = AWS.config.credentials.identityId;
```

## Unity
<a name="getting-credentials-1.unity"></a>

 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. 

The [AWS SDK for Unity](https://docs.aws.amazon.com/mobile/sdkforunity/developerguide/what-is-unity-plugin.html) is now part of the [SDK for .NET](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/welcome.html). To get started with Amazon Cognito in the SDK for .NET, see [Amazon Cognito credentials provider](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/cognito-creds-provider.html) in the AWS SDK for .NET Developer Guide. Or see [Amplify Dev Center](https://docs.amplify.aws/) for options for building an app with AWS Amplify.

**Retrieving an Amazon Cognito identity**

 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!
    }
    string identityId = result.Response;
});
```

## Xamarin
<a name="getting-credentials-1.xamarin"></a>

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.

The [AWS SDK for Xamarin](https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/Welcome.html) is now part of the [SDK for .NET](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/welcome.html). To get started with Amazon Cognito in the SDK for .NET, see [Amazon Cognito credentials provider](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/cognito-creds-provider.html) in the AWS SDK for .NET Developer Guide. Or see [Amplify Dev Center](https://docs.amplify.aws/) for options for building an app with AWS Amplify.

**Note**  
 **Note:** If you created your identity pool before February 2015, you must 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](https://console.aws.amazon.com/cognito/home), choose **Manage identity pools**, select your identity pool, choose **Edit identity Pool**, specify your authenticated and unauthenticated roles, and save the changes. 

**Retrieving an Amazon Cognito identity**

 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: 

```
var identityId = await credentials.GetIdentityIdAsync();
```

# Accessing AWS services with temporary credentials
<a name="accessing-aws-services"></a>

The result of a successful authentication with an identity pool is a set of AWS credentials. With these credentials, your application can make requests to AWS resources that are protected with IAM authentication. With the various AWS SDKs that you can add to your applications to access identity pools API operations, you can make unauthenticated API requests that produce temporary credentials. Then you can add SDKs for other AWS services to your client and sign requests with those temporary credentials. The IAM permissions granted to your temporary-credentials role must permit the operations that you request from other services.

After you configure your Amazon Cognito credentials provider and retrieve AWS credentials, create an AWS service client. The following are some examples from AWS SDK documentation.

**AWS SDK resources for creating a client**
+ [AWS Client configuration](https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/client-config.html) in the AWS SDK for C\$1\$1 Developer Guide
+ [Using the AWS SDK for Go V2 with AWS services](https://aws.github.io/aws-sdk-go-v2/docs/making-requests/) in the AWS SDK for Go Developer Guide
+ [Configuring HTTP clients](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/http-configuration.html) in the AWS SDK for Java 2.x Developer Guide
+ [Creating and calling service objects](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/creating-and-calling-service-objects.html) in the AWS SDK for JavaScript Developer Guide
+ [Creating clients](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/clients.html#creating-clients) in the AWS SDK for Python (Boto3) documentation
+ [Creating a service client](https://docs.aws.amazon.com/sdk-for-rust/latest/dg/client.html) in the AWS SDK for Rust Developer Guide
+ [Using clients](https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/using-client-services.html) in the AWS SDK for Swift Developer Guide

The following snippet initializes an Amazon DynamoDB client: 

## Android
<a name="accessing-aws-services-1.android"></a>

To use a Amazon Cognito identity pool in an Android app, set up AWS Amplify. For more information, see [Authentication](https://docs.amplify.aws/lib/auth/getting-started/q/platform/android/) in the *Amplify Dev Center*.

```
// Create a service client with the provider
AmazonDynamoDB client = new AmazonDynamoDBClient(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 - Objective-C
<a name="accessing-aws-services-1.ios-objc"></a>

To use a Amazon Cognito identity pool in an iOS app, set up AWS Amplify. For more information, see [Swift Authentication](https://docs.amplify.aws/lib/auth/getting-started/q/platform/ios/) and [Flutter Authentication](https://docs.amplify.aws/lib/auth/getting-started/q/platform/flutter/) in the *Amplify Dev Center*.

```
// create a configuration that uses the provider
AWSServiceConfiguration *configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSEast1 provider:credentialsProvider];
// get a client with the default service configuration
AWSDynamoDB *dynamoDB = [AWSDynamoDB defaultDynamoDB];
```

 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
<a name="accessing-aws-services-1.ios-swift"></a>

To use a Amazon Cognito identity pool in an iOS app, set up AWS Amplify. For more information, see [Swift Authentication](https://docs.amplify.aws/lib/auth/getting-started/q/platform/ios/) in the *Amplify Dev Center*.

```
// get a client with the default service configuration
let dynamoDB = AWSDynamoDB.default()

// get a client with a custom configuration
AWSDynamoDB.register(with: configuration!, forKey: "USWest2DynamoDB");
let dynamoDBCustom = AWSDynamoDB(forKey: "USWest2DynamoDB")
```

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
<a name="accessing-aws-services-1.javascript"></a>



```
// Create a service client with the provider
var dynamodb = new AWS.DynamoDB({region: 'us-west-2'});
```

 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
<a name="accessing-aws-services-1.unity"></a>

The [AWS SDK for Unity](https://docs.aws.amazon.com/mobile/sdkforunity/developerguide/what-is-unity-plugin.html) is now part of the [SDK for .NET](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/welcome.html). To get started with Amazon Cognito in the SDK for .NET, see [Amazon Cognito credentials provider](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/cognito-creds-provider.html) in the AWS SDK for .NET Developer Guide. Or see [Amplify Dev Center](https://docs.amplify.aws/) for options for building an app with AWS Amplify.

```
// create a service client that uses credentials provided by Cognito
AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials, REGION);
```

 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
<a name="accessing-aws-services-1.xamarin"></a>

The [AWS SDK for Xamarin](https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/Welcome.html) is now part of the [SDK for .NET](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/welcome.html). To get started with Amazon Cognito in the SDK for .NET, see [Amazon Cognito credentials provider](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/cognito-creds-provider.html) in the AWS SDK for .NET Developer Guide. Or see [Amplify Dev Center](https://docs.amplify.aws/) for options for building an app with AWS Amplify.

```
// create a service client that uses credentials provided by Cognito
var client = new AmazonDynamoDBClient(credentials, REGION)
```

 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. 

# Identity pools third-party identity providers
<a name="external-identity-providers"></a>

With Amazon Cognito identity pools, you can integrate with a variety of external identity providers (IdPs) to provide temporary AWS credentials through federated authentication in your application. By configuring your identity pool to work with these external IdPs, you can authorize access to back-end AWS resources for your users with authentication by Amazon Cognito user pools, social providers, OIDC providers, or SAML providers. This section covers the steps to set up and integrate IdPs with your Amazon Cognito identity pool.

Using the `logins` property, you can set credentials received from an identity provider (IdP). You can also associate an identity pool with multiple IdPs. For example, you can set both the Facebook and Google tokens in the `logins` property to associate the unique Amazon Cognito identity with both IdP logins. The user can authenticate with either account, but Amazon Cognito returns the same user identifier.

The following instructions guide you through authentication with the IdPs that Amazon Cognito identity pools support.

**Topics**
+ [Setting up Facebook as an identity pools IdP](facebook.md)
+ [Setting up Login with Amazon as an identity pools IdP](amazon.md)
+ [Setting up Google as an identity pool IdP](google.md)
+ [Setting up Sign in with Apple as an identity pool IdP](apple.md)
+ [Setting up an OIDC provider as an identity pool IdP](open-id.md)
+ [Setting up a SAML provider as an identity pool IdP](saml-identity-provider.md)

# Setting up Facebook as an identity pools IdP
<a name="facebook"></a>

Amazon Cognito identity pools work with Facebook to provide federated authentication for your application users. This section explains how to register and set up your application with Facebook as an IdP.

## Set up Facebook
<a name="set-up-facebook"></a>

Register your application with Facebook before you authenticate Facebook users and interact with Facebook APIs.

The [Facebook Developers portal](https://developers.facebook.com/) helps you to set up your application. Do this procedure before you integrate Facebook in your Amazon Cognito identity pool:

**Note**  
Amazon Cognito identity pools federation isn't compatible with [Facebook Limited Login](https://developers.facebook.com/docs/facebook-login/limited-login). For more information about how to set up Facebook Login for iOS without exceeding the permissions set for Limited Login, see [Facebook Login for iOS - Quickstart](https://developers.facebook.com/docs/facebook-login/ios) at *Meta for Developers*.

**Setting up Facebook**

1. At the [Facebook Developers portal](https://developers.facebook.com/), log in with your Facebook credentials.

1. From the **Apps** menu, select **Add a New App**.

1. Select a platform and complete the quick start process.

### Android
<a name="set-up-facebook-1.android"></a>

For more information about how to integrate Android apps with Facebook Login, see the [Facebook Getting Started Guide](https://developers.facebook.com/docs/android/getting-started).

### iOS - Objective-C
<a name="set-up-facebook-1.ios-objc"></a>

For more information about how to integrate iOS Objective-C apps with Facebook Login, see the [Facebook Getting Started Guide](https://developers.facebook.com/docs/ios/getting-started/).

### iOS - Swift
<a name="set-up-facebook-1.ios-swift"></a>

For more information about how to integrate iOS Swift apps with Facebook Login, see the [Facebook Getting Started Guide](https://developers.facebook.com/docs/ios/getting-started/).

### JavaScript
<a name="set-up-facebook-1.javascript"></a>

For more information about how to integrate JavaScript web apps with Facebook Login, see the [Facebook Getting Started Guide](https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.3).

## Configure an identity provider in the Amazon Cognito identity pools console
<a name="configure-the-external-provider-in-the-amazon-cognito-console"></a>

Use the following procedure to configure your identity provider.

**To add a Facebook identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Facebook**.

1. Enter the **App ID** of the OAuth project that you created at [Meta for Developers](https://developers.facebook.com/). For more information, see [Facebook Login](https://developers.facebook.com/docs/facebook-login/) in the *Meta for Developers Docs*.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**.

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

## Using Facebook
<a name="using-facebook"></a>

### Android
<a name="using-facebook-1.android"></a>

To add Facebook authentication, first follow the [Facebook guide](https://developers.facebook.com/docs/android) and integrate the Facebook SDK into your application. Then add a [**Login with Facebook** button](https://developers.facebook.com/docs/facebook-login/android) 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.

After you authenticate your user with the Facebook SDK, add the session token to the Amazon Cognito credentials provider.

Facebook SDK 4.0 or later:

```
Map<String, String> logins = new HashMap<String, String>();
logins.put("graph.facebook.com", AccessToken.getCurrentAccessToken().getToken());
credentialsProvider.setLogins(logins);
```

Facebook SDK before 4.0:

```
Map<String, String> logins = new HashMap<String, String>();
logins.put("graph.facebook.com", Session.getActiveSession().getAccessToken());
credentialsProvider.setLogins(logins);
```

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 that matches this particular Facebook identity. If the user already exists, the API returns the existing identifier. Otherwise, the API returns a new identifier. The client SDK automatically caches identifiers on the local device.

**Note**  
After you set the logins map, make a call to `refresh` or `get` to retrieve the AWS credentials.

### iOS - Objective-C
<a name="using-facebook-1.ios-objc"></a>

To add Facebook authentication, first follow the [Facebook guide](https://developers.facebook.com/docs/ios) and integrate the Facebook SDK into your application. Then add a [Login with Facebook button](https://developers.facebook.com/docs/facebook-login/ios) 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 [https://github.com/aws-amplify/aws-sdk-ios](https://github.com/aws-amplify/aws-sdk-ios) protocol.

When you implement the `logins` method, return a dictionary that contains `AWSIdentityProviderFacebook`. This dictionary acts as the key, and the current access token from the authenticated Facebook user acts as the value, as shown in the following code example.

```
- (AWSTask<NSDictionary<NSString *, NSString *> *> *)logins {
    FBSDKAccessToken* fbToken = [FBSDKAccessToken currentAccessToken];
    if(fbToken){
        NSString *token = fbToken.tokenString;
        return [AWSTask taskWithResult: @{ AWSIdentityProviderFacebook : token }];
    }else{
            return [AWSTask taskWithError:[NSError errorWithDomain:@"Facebook Login"
                                                          code:-1
                                                      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](https://github.com/aws-amplify/aws-sdk-ios) reference page and choose **initWithRegionType:identityPoolId:identityProviderManager**.

### iOS - Swift
<a name="using-facebook-1.ios-swift"></a>

To add Facebook authentication, first follow the [Facebook guide](https://developers.facebook.com/docs/ios) and integrate the Facebook SDK into your application. Then add a [Login with Facebook button](https://developers.facebook.com/docs/facebook-login/ios) 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).

**Note**  
Amazon Cognito identity pools federation isn't compatible with [Facebook Limited Login](https://developers.facebook.com/docs/facebook-login/limited-login). For more information about how to set up Facebook Login for iOS without exceeding the permissions set for Limited Login, see [Facebook Login for iOS - Quickstart](https://developers.facebook.com/docs/facebook-login/ios) at *Meta for Developers*.

To provide the Facebook access token to Amazon Cognito, implement the [https://github.com/aws-amplify/aws-sdk-ios](https://github.com/aws-amplify/aws-sdk-ios) protocol.

When you implement the `logins` method, return a dictionary containing `AWSIdentityProviderFacebook`. This dictionary acts as the key, and the current access token from the authenticated Facebook user acts as the value, as shown in the following code example.

```
class FacebookProvider: NSObject, AWSIdentityProviderManager {
    func logins() -> AWSTask<NSDictionary> {
        if let token = AccessToken.current?.authenticationToken {
            return AWSTask(result: [AWSIdentityProviderFacebook:token])
        }
        return AWSTask(error:NSError(domain: "Facebook Login", code: -1 , userInfo: ["Facebook" : "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 [https://github.com/aws-amplify/aws-sdk-ios](https://github.com/aws-amplify/aws-sdk-ios) reference page and choose **initWithRegionType:identityPoolId:identityProviderManager**.

### JavaScript
<a name="using-facebook-1.javascript"></a>

To add Facebook authentication, follow the [Facebook Login for the Web](https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.3) and 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.

After you authenticate your user with the Facebook SDK, add the session token to the Amazon Cognito credentials provider.

```
FB.login(function (response) {

  // Check if the user logged in successfully.
  if (response.authResponse) {

    console.log('You are now logged in.');

    // Add the Facebook access token to the Amazon Cognito credentials login map.
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: 'IDENTITY_POOL_ID',
      Logins: {
        'graph.facebook.com': response.authResponse.accessToken
      }
    });

    // Obtain AWS credentials
    AWS.config.credentials.get(function(){
        // Access AWS resources here.
    });

  } 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 you set the logins map, 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](https://github.com/amazon-archives/amazon-cognito-identity-js/blob/master/README.md).

### Unity
<a name="using-facebook-1.unity"></a>

To add Facebook authentication, first follow the [Facebook guide](https://developers.facebook.com/docs/unity) and integrate the Facebook SDK into 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.

After you authenticate 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 FacebookLoginCallback(FBResult result)
{
    if (FB.IsLoggedIn)
    {
        AddFacebookTokenToCognito();
    }
    else
    {
        Debug.Log("FB Login error");
    }
}

void AddFacebookTokenToCognito()
{
    credentials.AddLogin ("graph.facebook.com", AccessToken.CurrentAccessToken.TokenString);
}
```

Before you use `FB.AccessToken`, call `FB.Login()` and make sure `FB.IsLoggedIn` is true.

### Xamarin
<a name="using-facebook-1.xamarin"></a>

**Xamarin for Android:**

```
public void InitializeFacebook() {
    FacebookSdk.SdkInitialize(this.ApplicationContext);
    callbackManager = CallbackManagerFactory.Create();
    LoginManager.Instance.RegisterCallback(callbackManager, new FacebookCallback &lt; LoginResult &gt; () {
      HandleSuccess = loginResult = &gt; {
        var accessToken = loginResult.AccessToken;
        credentials.AddLogin("graph.facebook.com", accessToken.Token);
        //open new activity
      },
      HandleCancel = () = &gt; {
        //throw error message
      },
      HandleError = loginError = &gt; {
        //throw error message
      }
    });
    LoginManager.Instance.LogInWithReadPermissions(this, new List &lt; string &gt; {
      "public_profile"
    });
  }
```

**Xamarin for iOS:**

```
public void InitializeFacebook() {
  LoginManager login = new LoginManager();
  login.LogInWithReadPermissions(readPermissions.ToArray(), delegate(LoginManagerLoginResult result, NSError error) {
    if (error != null) {
      //throw error message
    } else if (result.IsCancelled) {
      //throw error message
    } else {
      var accessToken = loginResult.AccessToken;
      credentials.AddLogin("graph.facebook.com", accessToken.Token);
      //open new view controller
    }
  });
}
```

# Setting up Login with Amazon as an identity pools IdP
<a name="amazon"></a>

Amazon Cognito identity pools work with Login with Amazon to provide federated authentication for your mobile and web app users. This section explains how to register and set up your application with Login with Amazon as an identity provider (IdP).

Set up Login with Amazon to work with Amazon Cognito in the [Developer Portal](https://developer.amazon.com/login-with-amazon). For more information, see [Setting Up Login with Amazon](https://developer.amazon.com/docs/login-with-amazon/faq.html#setting-up-login-with-amazon) in the Login with Amazon FAQ.

**Note**  
To integrate Login with Amazon into a Xamarin application, follow the [Xamarin Getting Started Guide](https://developer.xamarin.com/guides/cross-platform/getting_started/).

**Note**  
You can't natively integrate Login with Amazon on the Unity platform. Instead, use a web view and go through the browser sign-in flow.

## Setting up Login with Amazon
<a name="login-with-amazon-setup"></a>

**Implement Login with Amazon **

In the [Amazon developer portal](https://developer.amazon.com/apps-and-games/login-with-amazon), you can set up an OAuth application to integrate with your identity pool, find Login with Amazon documentation, and download SDKs. Choose **Developer console**, then **Login with Amazon** in the developer portal. You can create a security profile for your application and then build Login with Amazon authentication mechanisms into your app. See [Getting credentials](getting-credentials.md) for more information about how to integrate Login with Amazon authentication with your app.

Amazon issues an OAuth 2.0 **client ID** for your new security profile. You can find the **client ID** on the security profile **Web Settings** tab. Enter the **Security Profile ID** in the **App ID** field of the Login with Amazon IdP in your identity pool.

**Note**  
You enter the **Security Profile ID** in the **App ID** field of the Login with Amazon IdP in your identity pool. This differs from user pools, which use **client ID**.

## Configure the external provider in the Amazon Cognito console
<a name="login-with-amazon-configure-provider"></a>

**To add a Login with Amazon identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Login with Amazon**.

1. Enter the **App ID** of the OAuth project that you created at [Login with Amazon](https://developer.amazon.com/apps-and-games/login-with-amazon). For more information, see [Login with Amazon Documentation](https://developer.amazon.com/docs/login-with-amazon/documentation-overview.html).

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**.

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

## Use Login with Amazon: Android
<a name="set-up-amazon-1.android"></a>

After you authenticate Amazon login, you can pass the token to the Amazon Cognito credentials provider in the onSuccess method of the TokenListener interface. The code looks like this:

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

## Use Login with Amazon: iOS - Objective-C
<a name="set-up-amazon-1.ios-objc"></a>

After you authenticate Amazon login, you can pass the token to the Amazon Cognito credentials provider in the requestDidSucceed method of the AMZNAccessTokenDelegate:

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

## Use Login with Amazon: iOS - Swift
<a name="set-up-amazon-1.ios-swift"></a>

After you authenticate Amazon login, you can pass the token to the Amazon Cognito credentials provider in the `requestDidSucceed` method of the `AMZNAccessTokenDelegate`:

```
func requestDidSucceed(apiResult: APIResult!) {
    if apiResult.api == API.AuthorizeUser {
        AIMobileLib.getAccessTokenForScopes(["profile"], withOverrideParams: nil, delegate: self)
    } else if apiResult.api == API.GetAccessToken {
        credentialsProvider.logins = [AWSCognitoLoginProviderKey.LoginWithAmazon.rawValue: apiResult.result]
    }
}
```

## Use Login with Amazon: JavaScript
<a name="set-up-amazon-1.javascript"></a>

After the user authenticates with Login with Amazon and is redirected back to your website, the Login with Amazon access\$1token is provided in the query string. Pass that token into the credentials login map.

```
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
   IdentityPoolId: 'IDENTITY_POOL_ID',
   Logins: {
       'www.amazon.com': 'Amazon Access Token'
   }
});
```

# Setting up Google as an identity pool IdP
<a name="google"></a>

Amazon Cognito identity pools work with Google to provide federated authentication for your mobile application users. This section explains how to register and set up your application with Google as an IdP.

## Android
<a name="set-up-google-1.android"></a>

**Note**  
If your app uses Google and is available on multiple mobile platforms, you should configure it as an [OpenID Connect Provider](open-id.md). Add all created client IDs as additional audience values for better integration. To learn more about Google's cross-client identity model, see [Cross-client Identity](https://developers.google.com/accounts/docs/CrossClientAuth).

**Setting up Google**

To activate Google Sign-in for Android, create a Google Developers console project for your application.

1. Go to the [Google Developers console](https://console.developers.google.com/) and create a new project.

1. Choose **APIs & Services**, then **OAuth consent screen**. Customize the information that Google shows to your users when Google asks for their consent to share their profile data with your app.

1. Choose **Credentials**, then **Create credentials**. Choose **OAuth client ID**. Select **Android** as the **Application type**. Create a separate client ID for each platform where you develop your app.

1. From **Credentials**, choose **Manage service accounts**. Choose **Create service account**. Enter your service account details, and then choose **Create and continue**.

1. Grant the service account access to your project. Grant users access to the service account as your app requires.

1. Choose your new service account, choose the **Keys** tab, and **Add key**. Create and download a new JSON key.

For more information about how to use the Google Developers console, see [Creating and managing projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects) in the Google Cloud documentation.

For more information about how to integrate Google into your Android app, see [Authenticate users with Sign in with Google](https://developer.android.com/identity/sign-in/credential-manager-siwg) in the Google Identity documentation.

**To add a Google identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Google**.

1. Enter the **Client ID** of the OAuth project you created at [Google Cloud Platform](https://console.cloud.google.com/). For more information, see [Setting up OAuth 2.0](https://support.google.com/cloud/answer/6158849) in *Google Cloud Platform Console Help*.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**.

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

**Use Google**

To enable login with Google in your application, follow the instructions in the [Google documentation for Android](https://developers.google.com/identity/sign-in/android/start). When a user signs in, they request an OpenID Connect authentication token from Google. Amazon Cognito then uses the token to authenticate the user and generate a unique identifier.

The following example 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>();
logins.put("accounts.google.com", token);
credentialsProvider.setLogins(logins);
```

## iOS - Objective-C
<a name="set-up-google-1.ios-objc"></a>

**Note**  
If your app uses Google and is available on multiple mobile platforms, configure Google as an [OpenID Connect Provider](open-id.md). Add all created client IDs as additional audience values for better integration. To learn more about Google's cross-client identity model, see [Cross-client Identity](https://developers.google.com/accounts/docs/CrossClientAuth).

**Setting up Google**

To enable Google Sign-in for iOS, create a Google Developers console project for your application.

1. Go to the [Google Developers console](https://console.developers.google.com/) and create a new project.

1. Choose **APIs & Services**, then **OAuth consent screen**. Customize the information that Google shows to your users when Google asks for their consent to share their profile data with your app.

1. Choose **Credentials**, then **Create credentials**. Choose **OAuth client ID**. Select **iOS** as the **Application type**. Create a separate client ID for each platform where you develop your app.

1. From **Credentials**, choose **Manage service accounts**. Choose **Create service account**. Enter your service account details, and choose **Create and continue**.

1. Grant the service account access to your project. Grant users access to the service account as your app requires.

1. Choose your new service account. Choose the **Keys** tab, and **Add key**. Create and download a new JSON key.

For more information about how to use the Google Developers console, see [Creating and managing projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects) in the Google Cloud documentation.

For more information about how to integrate Google into your iOS app, see [Google Sign-In for iOS](https://developers.google.com/identity/sign-in/ios/start-integrating) in the Google Identity documentation.

**To add a Google identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Google**.

1. Enter the **Client ID** of the OAuth project you created at [Google Cloud Platform](https://console.cloud.google.com/). For more information, see [Setting up OAuth 2.0](https://support.google.com/cloud/answer/6158849) in *Google Cloud Platform Console Help*.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**.

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

**Use Google**

To enable login with Google in your application, follow the [Google documentation for iOS](https://developers.google.com/identity/sign-in/ios/start/). Successful authentication results in an OpenID Connect authentication token, which Amazon Cognito uses to authenticate the user and generate a unique identifier.

Successful authentication results in a `GTMOAuth2Authentication` object, which contains an `id_token`, which Amazon Cognito uses to authenticate the user and generate a unique identifier:

```
- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth error: (NSError *) error {
        NSString *idToken = [auth.parameters objectForKey:@"id_token"];
        credentialsProvider.logins = @{ @(AWSCognitoLoginProviderKeyGoogle): idToken };
    }
```

## iOS - Swift
<a name="set-up-google-1.ios-swift"></a>

**Note**  
If your app uses Google and is available on multiple mobile platforms, configure Google as an [OpenID Connect Provider](open-id.md). Add all created client IDs as additional audience values for better integration. To learn more about Google's cross-client identity model, see [Cross-client Identity](https://developers.google.com/accounts/docs/CrossClientAuth).

**Setting up Google**

To enable Google Sign-in for iOS, create a Google Developers console project for your application.

1. Go to the [Google Developers console](https://console.developers.google.com/) and create a new project.

1. Choose **APIs & Services**, then **OAuth consent screen**. Customize the information that Google shows to your users when Google asks for their consent to share their profile data with your app.

1. Choose **Credentials**, then **Create credentials**. Choose **OAuth client ID**. Select **iOS** as the **Application type**. Create a separate client ID for each platform where you develop your app.

1. From **Credentials**, choose **Manage service accounts**. Choose **Create service account**. Enter your service account details, and choose **Create and continue**.

1. Grant the service account access to your project. Grant users access to the service account as your app requires.

1. Choose your new service account, choose the **Keys** tab, and **Add key**. Create and download a new JSON key.

For more information about how to use the Google Developers console, see [Creating and managing projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects) in the Google Cloud documentation.

For more information about how to integrate Google into your iOS app, see [Google Sign-In for iOS](https://developers.google.com/identity/sign-in/ios/start-integrating) in the Google Identity documentation.

Choose **Manage Identity Pools** from the [Amazon Cognito Console home page](https://console.aws.amazon.com/cognito/home):

**Configuring the external provider in the Amazon Cognito Console**

1. Choose the name of the identity pool where you want to enable Google as an external provider. The **Dashboard** page for your identity pool appears.

1. In the top-right corner of the **Dashboard** page, choose **Edit identity pool**. The Edit identity pool page appears.

1. Scroll down and choose **Authentication providers** to expand the section.

1. Choose the **Google** tab.

1. Choose **Unlock**.

1. Enter the Google Client ID that 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](https://developers.google.com/identity/sign-in/ios/start/). Successful authentication results in an OpenID Connect authentication token that Amazon Cognito uses to authenticate the user and generate a unique identifier.

Successful authentication results in a `GTMOAuth2Authentication` object that contains an `id_token`. Amazon Cognito uses this token to authenticate the user and generate a unique identifier:

```
func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) {
    if error != nil {
      print(error.localizedDescription)
    }
    else {
      let idToken = auth.parameters.objectForKey("id_token")
      credentialsProvider.logins = [AWSCognitoLoginProviderKey.Google.rawValue: idToken!]
    }
}
```

## JavaScript
<a name="set-up-google-1.javascript"></a>

**Note**  
If your app uses Google and is available on multiple mobile platforms, you should configure Google as an [OpenID Connect Provider](open-id.md). Add all created client IDs as additional audience values for better integration. To learn more about Google's cross-client identity model, see [Cross-client Identity](https://developers.google.com/accounts/docs/CrossClientAuth).

**Setting up Google**

To enable Google Sign-in for a JavaScript web app, create a Google Developers console project for your application.

1. Go to the [Google Developers console](https://console.developers.google.com/) and create a new project.

1. Choose **APIs & Services**, then **OAuth consent screen**. Customize the information that Google shows to your users when Google asks their consent to share their profile data with your app.

1. Choose **Credentials**, then **Create credentials**. Choose **OAuth client ID**. Select **Web application** as the **Application type**. Create a separate client ID for each platform where you develop your app.

1. From **Credentials**, choose **Manage service accounts**. Choose **Create service account**. Enter your service account details, and choose **Create and continue**.

1. Grant the service account access to your project. Grant users access to the service account as your app requires.

1. Choose your new service account, choose the **Keys** tab, and **Add key**. Create and download a new JSON key.

For more information about how to use the Google Developers console, see [Creating and managing projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects) in the Google Cloud documentation.

For more information about how to integrate Google into your web app, see [Sign in With Google](https://developers.google.com/identity/gsi/web/guides/overview) in the Google Identity documentation.

**Configure the External Provider in the Amazon Cognito Console**

**To add a Google identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Google**.

1. Enter the **Client ID** of the OAuth project you created at [Google Cloud Platform](https://console.cloud.google.com/). For more information, see [Setting up OAuth 2.0](https://support.google.com/cloud/answer/6158849) in *Google Cloud Platform Console Help*.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**.

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

**Use Google**

To enable login with Google in your application, follow the [Google documentation for Web](https://developers.google.com/identity/gsi/web/guides/overview).

Successful authentication results in a response object that contains an `id_token` that Amazon Cognito uses to authenticate the user and generate a unique identifier:

```
function signinCallback(authResult) {
  if (authResult['status']['signed_in']) {

     // 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']
        }
     });

     // Obtain AWS credentials
     AWS.config.credentials.get(function(){
        // Access AWS resources here.
     });
  }
}
```

# Setting up Sign in with Apple as an identity pool IdP
<a name="apple"></a>

Amazon Cognito identity pools work with Sign in with Apple to provide federated authentication for your mobile application and web application users. This section explains how to register and set up your application using Sign in with Apple as an identity provider (IdP).

To add Sign in with Apple as an authentication provider to an identity pool, you must complete two procedures. First, integrate Sign in with Apple in an application, and then configure Sign in with Apple in identity pools. For the most up-to-date information about setting up Sign in with Apple, see [Configuring Your Environment for Sign in with Apple](https://developer.apple.com/documentation/signinwithapple/configuring-your-environment-for-sign-in-with-apple) in the Apple Developer documentation.

## Set up Sign in with Apple
<a name="login-with-apple-setup"></a>

To configure Sign in with Apple as an IdP, register your application with the Apple to receive client ID.

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

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

1. In the left navigation pane, choose **Certificates, IDs & Profiles**.

1. In the left navigation pane, choose **Identifiers**.

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

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

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

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

   1. Under **Bundle ID,** type an identifier. Make a note of this **Bundle ID** as you need this value to configure Apple as a provider in the identity pool. 

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

   1. On the **Sign in with Apple: App ID Configuration** page, select the appropriate setting for your app. Then choose **Save**.

   1. Choose **Continue**.

1. On the **Confirm your App ID** page, choose **Register**.

1. Proceed to step 10 if you want to integrate Sign in with Apple with a native iOS application. Step 11 is for applications that you want to integrate with Sign in with Apple JS.

1. On the **Identifiers** page, choose the **App IDs** menu, then **Services IDs**. Choose the **\$1** icon.

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

1. On the **Register a Services ID** page, do the following:

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

   1. Under **Identifier**, type an identifier. Make a note of the services ID as you need this value to configure Apple as a provider in your identity pool. 

   1. Select **Sign In with Apple** and then choose **Configure**.

   1. On the **Web Authentication Configuration** page, choose a **Primary App ID**. Under **Website URLs**, choose the **\$1 **icon. For **Domains and Subdomains**, enter the domain name of your app. In **Return URLs,** enter the callback URL where the authorization redirects the user after they authenticate through Sign in with Apple. 

   1. Choose **Next**.

   1. Choose **Continue**, and then choose **Register**.

1. In the left navigation pane, choose **Keys**.

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

1. On the **Register a New Key** page, do the following:

   1. Under **Key Name**, type a key name. 

   1. Choose **Sign In with Apple**, and then choose **Configure**.

   1. On the **Configure Key** page, choose a **Primary App ID** and then choose **Save**.

   1. Choose **Continue**, and then choose **Register**.

**Note**  
To integrate Sign in with Apple with a native iOS application, see [Implementing User Authentication with Sign in with Apple. ](https://developer.apple.com/documentation/authenticationservices/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.](https://developer.apple.com/documentation/signinwithapplejs/) 

## Configure the external provider in the Amazon Cognito federated identities console
<a name="login-with-apple-configure-provider"></a>

Use the following procedure to configure your external provider.

**To add a Sign in with Apple identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Sign in with Apple**.

1. Enter the **Services ID** of the OAuth project you created with [Apple Developer](https://developer.apple.com). For more information, see [Authenticating users with Sign in with Apple](https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple) in *Sign in with Apple Documentation*.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**.

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

## Sign in with Apple as a provider in the Amazon Cognito federated identities CLI examples
<a name="sign-in-with-apple-cli-examples"></a>

This example creates an identity pool named `MyIdentityPool` with Sign in with Apple as an IdP.

`aws cognito-identity create-identity-pool --identity-pool-name MyIdentityPool --supported-login-providers appleid.apple.com="sameple.apple.clientid"`

 For more information, see [Create identity pool](https://docs.aws.amazon.com/cli/latest/reference/cognito-identity/create-identity-pool.html) 

**Generate an Amazon Cognito identity ID**  
 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.

`aws cognito-identity get-id --identity-pool-id SampleIdentityPoolId --logins appleid.apple.com="SignInWithAppleIdToken"`

For more information, see [get-id.](https://docs.aws.amazon.com/cli/latest/reference/cognito-identity/get-id.html) 

**Get credentials for an Amazon Cognito identity ID**  
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.

`aws cognito-identity get-credentials-for-identity --identity-id SampleIdentityId --logins appleid.apple.com="SignInWithAppleIdToken" `

For more information, see [get-credentials-for-identity](https://docs.aws.amazon.com/cli/latest/reference/cognito-identity/get-credentials-for-identity.html) 

## Use Sign in with Apple: Android
<a name="set-up-apple-1.android"></a>

Apple doesn't provide an SDK that supports Sign in with Apple for Android. You can use the web flow in a web view instead.
+ To configure Sign in with Apple in your application, follow [Configuring Your Web page for Sign In with Apple](https://developer.apple.com/documentation/signinwithapple/configuring-your-webpage-for-sign-in-with-apple) in the Apple documentation.
+ To add a **Sign in with Apple** button to your Android user interface, follow [Displaying Sign in with Apple buttons on the web](https://developer.apple.com/documentation/signinwithapple/displaying-sign-in-with-apple-buttons-on-the-web) in the Apple documentation.
+ To securely authenticate users with Sign in with Apple, follow [Authenticating Users with Sign in with Apple](https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-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);
}
```

## Use Sign in with Apple: iOS - Objective-C
<a name="set-up-apple-1.ios-objc"></a>

Apple provided SDK support for Sign in with Apple in native iOS applications. To implement user authentication with Sign in with Apple in native iOS devices, follow [Implementing User Authentication with Sign in with Apple](https://developer.apple.com/documentation/authenticationservices/implementing-user-authentication-with-sign-in-with-apple) in the Apple documentation.

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.

```
(void)finishedWithAuth: (ASAuthorizationAppleIDCredential *)auth error: (NSError *) error {
        NSString *idToken = [ASAuthorizationAppleIDCredential objectForKey:@"identityToken"];
        credentialsProvider.logins = @{ "appleid.apple.com": idToken };
    }
```

## Use Sign in with Apple: iOS - Swift
<a name="set-up-apple-1.ios-swift"></a>

Apple provided SDK support for Sign in with Apple in native iOS applications. To implement user authentication with Sign in with Apple in native iOS devices, follow [Implementing User Authentication with Sign in with Apple](https://developer.apple.com/documentation/authenticationservices/implementing-user-authentication-with-sign-in-with-apple) in the Apple documentation.

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 about how to set up Sign in with Apple in iOS, see [Set up Sign in with Apple](https://docs.amplify.aws/sdk/auth/federated-identities/q/platform/ios#set-up-sign-in-with-apple)

```
func finishedWithAuth(auth: ASAuthorizationAppleIDCredential!, error: NSError!) {
    if error != nil {
      print(error.localizedDescription)
    }
    else {
      let idToken = auth.identityToken,
      credentialsProvider.logins = ["appleid.apple.com": idToken!]
    }
}
```

## Use Sign in with Apple: JavaScript
<a name="set-up-apple-1.javascript"></a>

Apple doesn’t provide an SDK that supports Sign in with Apple for JavaScript. You can use the web flow in a web view instead.
+ To configure Sign in with Apple in your application, follow [Configuring Your Web page for Sign In with Apple](https://developer.apple.com/documentation/signinwithapple/configuring-your-webpage-for-sign-in-with-apple) in the Apple documentation.
+ To add a **Sign in with Apple** button to your JavaScript user interface, follow [Displaying Sign in with Apple buttons on the web](https://developer.apple.com/documentation/signinwithapple/displaying-sign-in-with-apple-buttons-on-the-web) in the Apple documentation.
+ To securely authenticate users with Sign in with Apple, follow [Authenticating Users with Sign in with Apple](https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-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']
        }
     });

     // Obtain AWS credentials
     AWS.config.credentials.get(function(){
        // Access AWS resources here.
     });
}
```

# Setting up an OIDC provider as an identity pool IdP
<a name="open-id"></a>

[OpenID Connect](http://openid.net/connect/) is an open standard for authentication that a number of login providers support. With Amazon Cognito, you can link identities with OpenID Connect providers that you configure through [AWS Identity and Access Management](http://aws.amazon.com/iam/).

**Adding an OpenID Connect provider**

For information about how to create an OpenID Connect provider, see [Creating OpenID Connect (OIDC) identity providers](https://docs.aws.amazon.com/IAM/latest/UserGuide/identity-providers-oidc.html) in the *AWS Identity and Access Management User Guide*.

**Associating a provider with Amazon Cognito**

**To add an OIDC identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **OpenID Connect (OIDC)**.

1. Choose an **OIDC identity provider** from the IAM IdPs in your AWS account. If you want to add a new SAML provider, choose **Create new provider** to navigate to the IAM console.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**.

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

You can associate multiple OpenID Connect providers with a single identity pool.

**Using OpenID Connect**

Refer to your provider's documentation for how to sign in and receive an ID token.

After you have a token, add the token to the logins map. Use the URI of your provider as the key.

**Validating an OpenID Connect token**

When you first integrate with Amazon Cognito, you might receive an `InvalidToken` exception. It is important to understand how Amazon Cognito validates OpenID Connect (OIDC) tokens.

**Note**  
As specified here ([https://tools.ietf.org/html/rfc7523](https://tools.ietf.org/html/rfc7523)), Amazon Cognito provides a grace period of 5 minutes to handle any clock skew between systems.

1. The `iss` parameter must match the key that the logins map uses (such as login.provider.com).

1. The signature must be valid. The signature must be verifiable via an RSA public key.
**Note**  
Identity pools maintain a cache of the OIDC IdP signing key for a brief period. If your provider changes their signing key, Amazon Cognito might return a `NoKeyFound` error until this cache refreshes. If you encounter this error, wait about ten minutes for your identity pool to refresh the signing key.

1. The fingerprint of the certificate public key matches the fingerprint that you set in IAM when you created your OIDC provider.

1. If the `azp` parameter is present, check this value against listed client IDs in your OIDC provider.

1. If the `azp` parameter isn't present, check the `aud` parameter against listed client IDs in your OIDC provider.

The website [jwt.io](http://jwt.io/) is a valuable resource that you can use to decode tokens and verify these values.

## Android
<a name="set-up-open-id-1.android"></a>

```
Map<String, String> logins = new HashMap<String, String>();
logins.put("login.provider.com", token);
credentialsProvider.setLogins(logins);
```

## iOS - Objective-C
<a name="set-up-open-id-1.ios-objc"></a>

```
credentialsProvider.logins = @{ "login.provider.com": token }
```

## JavaScript
<a name="set-up-open-id-1.javascript"></a>

```
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
 IdentityPoolId: 'IDENTITY_POOL_ID',
 Logins: {
    'login.provider.com': token
 }
});
```

# Setting up a SAML provider as an identity pool IdP
<a name="saml-identity-provider"></a>

With Amazon Cognito identity pools, you can authenticate users with identity providers (IdPs) through SAML 2.0. You can use an IdP that supports SAML with Amazon Cognito to provide a simple onboarding flow for your users. Your SAML-supporting IdP specifies the IAM roles that your users can assume. This way, different users can receive different sets of permissions.

## Configuring your identity pool for a SAML IdP
<a name="configure-identity-pool-saml-provider"></a>

The following steps describe how to configure your identity pool to use a SAML-based IdP.

**Note**  
Before you configure your identity pool to support a SAML provider, first configure the SAML IdP in the [IAM console](https://console.aws.amazon.com/iam). For more information, see [Integrating third-party SAML solution providers with AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml_3rd-party.html) in the *IAM User Guide*.

**To add a SAML identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **SAML**.

1. Choose a **SAML identity provider** from the IAM IdPs in your AWS account. If you want to add a new SAML provider, choose **Create new provider** to navigate to the IAM console.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can assign users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**.

     1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to compare the claim by, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

     1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.

   1. To apply no principal tags, choose **Inactive**.

   1. To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.

   1. To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

## Configuring your SAML IdP
<a name="configure-your-saml-identity-provider"></a>

After you create the SAML provider, configure your SAML IdP to add relying party trust between your IdP and AWS. With many IdPs, you can specify a URL that the IdP can use to read relying party information and certificates from an XML document. For AWS, you can use [https://signin.aws.amazon.com/static/saml-metadata.xml](https://signin.aws.amazon.com/static/saml-metadata.xml). The next step is to configure the SAML assertion response from your IdP to populate the claims that AWS needs. For details on the claim configuration, see [Configuring SAML assertions for authentication response](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_assertions.html).

When your SAML IdP includes more than one signing certificate in SAML metadata, at sign-in your identity pool determines that the SAML assertion is valid if it matches any certificate in the SAML metadata.

## Customizing your user role with SAML
<a name="role-customization-saml"></a>

When you use SAML with Amazon Cognito Identity, you can customize the role for the end user. Amazon Cognito only supports the [enhanced flow](authentication-flow.md) with the SAML-based IdP. You don't need to specify an authenticated or unauthenticated role for the identity pool to use a SAML-based IdP. The `https://aws.amazon.com/SAML/Attributes/Role` claim attribute specifies one or more pairs of comma -delimited role and provider ARN. These are the roles that the user can assume. You can configure the SAML IdP to populate the role attributes based on the user attribute information available from the IdP. If you receive multiple roles in the SAML assertion, populate the optional `customRoleArn` parameter when you call `getCredentialsForIdentity`. The user assumes this `customRoleArn` if the role matches one in the claim in the SAML assertion.

## Authenticating users with a SAML IdP
<a name="authenticate-user-with-saml"></a>

To federate with the SAML-based IdP, determine the URL where the user initiates the login. AWS federation uses IdP-initiated login. In AD FS 2.0, the URL takes the form of `https://<fqdn>/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices`.

To add support for your SAML IdP in Amazon Cognito, first authenticate users with your SAML identity provider from your iOS or Android application. The code that you use to integrate and authenticate with the SAML IdP is specific to SAML providers. After you authenticate your user, you can use Amazon Cognito APIs to provide the resulting SAML assertion to Amazon Cognito Identity .

You can't repeat, or *replay*, a SAML assertion in the `Logins` map of your identity pool API request. A replayed SAML assertion has an assertion ID that duplicates the ID of an earlier API request. API operations that can accept a SAML assertion in the `Logins` map include [GetId](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetId.html), [GetCredentialsForIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html), [GetOpenIdToken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html), and [GetOpenIDTokenForDeveloperIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html). You can replay a SAML assertion ID one time per API request in an identity pool authentication flow. For example, you can supply the same SAML assertion in a `GetId` request and a subsequent `GetCredentialsForIdentity` request, but not in a second `GetId` request.

# Developer-authenticated identities
<a name="developer-authenticated-identities"></a>

Amazon Cognito supports developer-authenticated identities, in addition to web identity federation through [Setting up Facebook as an identity pools IdP](facebook.md), [Setting up Google as an identity pool IdP](google.md), [Setting up Login with Amazon as an identity pools IdP](amazon.md), and [Setting up Sign in with Apple as an identity pool IdP](apple.md). With developer-authenticated identities, you can register and authenticate users through 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, see [Understanding Amazon Cognito Authentication Part 2: Developer Authenticated Identities](https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-authentication-part-2-developer-authenticated-identities/) in the AWS blog.

## Understanding the authentication flow
<a name="understanding-the-authentication-flow"></a>

The [GetOpenIdTokenForDeveloperIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html) API operation can initiate developer authentication for both enhanced and basic authentication. This API authenticates a request with administrative credentials. The `Logins` map is an identity pool developer provider name like `login.mydevprovider` paired with a custom identifier.

Example:

```
"Logins": {
        "login.mydevprovider": "my developer identifier"
    }
```

**Enhanced authentication**

Call the [GetCredentialsForIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html) API operation with a `Logins` map with the name `cognito-identity.amazonaws.com` and a value of the token from `GetOpenIdTokenForDeveloperIdentity`.

Example:

```
"Logins": {
        "cognito-identity.amazonaws.com": "eyJra12345EXAMPLE"
    }
```

`GetCredentialsForIdentity` with developer-authenticated identities returns temporary credentials for the default authenticated role of the identity pool.

**Basic authentication**

Call the [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API operation and request the `RoleArn` of any IAM role that has an appropriate [trust relationship defined](iam-roles.md#role-trust-and-permissions). Set the value of `WebIdentityToken` to the token obtained from `GetOpenIdTokenForDeveloperIdentity`.

For information on the developer-authenticated identities authflow and how they differ from external-provider identities, see [Identity pools authentication flow](authentication-flow.md).

## Define a developer provider name and associate it with an identity pool
<a name="associate-developer-provider"></a>

To use developer-authenticated identities, you'll need an identity pool associated with your developer provider. To do so, follow these steps:

**To add a custom developer provider**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Custom developer provider**.

1. Enter a **Developer provider name**. You can't change or delete your developer provider after you add it.

1. Select **Save changes**.

Note: Once the provider name has been set, it cannot be changed.

## Implement an identity provider
<a name="implement-an-identity-provider"></a>

### Android
<a name="implement-id-provider-1.android"></a>

To use developer-authenticated identities, implement your own identity provider class that extends `AWSAbstractCognitoIdentityProvider`. Your identity provider class should return a response object containing the token as an attribute.

Following is a basic example of an identity provider.

```
public class DeveloperAuthenticationProvider extends AWSAbstractCognitoDeveloperIdentityProvider {

  private static final String developerProvider = "<Developer_provider_name>";

  public DeveloperAuthenticationProvider(String accountId, String identityPoolId, Regions region) {
    super(accountId, identityPoolId, region);
    // Initialize any other objects needed here.
  }

  // Return the developer provider name which you choose while setting up the
  // identity pool in the &COG; Console

  @Override
  public String getProviderName() {
    return developerProvider;
  }

  // Use the refresh method to communicate with your backend to get an
  // identityId and token.

  @Override
  public String refresh() {

    // Override the existing token
    setToken(null);

    // Get the identityId and token by making a call to your backend
    // (Call to your backend)

    // 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() {

    // Load the identityId from the cache
    identityId = cachedIdentityId;

    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:

```
DeveloperAuthenticationProvider developerProvider = new DeveloperAuthenticationProvider( null, "IDENTITYPOOLID", context, Regions.USEAST1);
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider( context, developerProvider, Regions.USEAST1);
```

### iOS - objective-C
<a name="implement-id-provider-1.ios-objc"></a>

To use developer-authenticated identities, implement your own identity provider class that extends [AWSCognitoCredentialsProviderHelper](https://github.com/aws-amplify/aws-sdk-ios). 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.
 */

- (AWSTask <NSString*> *) token {
    //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

    // Set the identity id and return the token
    self.identityId = response.identityId;
    return [AWSTask taskWithResult:response.token];
}

@end
```

To use this identity provider, pass it into `AWSCognitoCredentialsProvider` as shown in the following example:

```
DeveloperAuthenticatedIdentityProvider * devAuth = [[DeveloperAuthenticatedIdentityProvider alloc] initWithRegionType:AWSRegionYOUR_IDENTITY_POOL_REGION 
                                         identityPoolId:@"YOUR_IDENTITY_POOL_ID"
                                        useEnhancedFlow:YES
                                identityProviderManager:nil];
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc]
                                                          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.

```
- (AWSTask<NSDictionary<NSString *, NSString *> *> *)logins {
    if(/*logic to determine if user is unauthenticated*/) {
        return [AWSTask taskWithResult:nil];
    }else{
        return [super logins];
    }
}
```

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

```
- (AWSTask<NSDictionary<NSString *, NSString *> *> *)logins {
    if(/*logic to determine if user is unauthenticated*/) {
        return [AWSTask taskWithResult:nil];
    }else if (/*logic to determine if user is Facebook*/){
        return [AWSTask taskWithResult: @{ AWSIdentityProviderFacebook : [FBSDKAccessToken currentAccessToken] }];
    }else {
        return [super logins];
    }
}
```

### iOS - swift
<a name="implement-id-provider-1.ios-swift"></a>

To use developer-authenticated identities, implement your own identity provider class that extends [AWSCognitoCredentialsProviderHelper](https://github.com/aws-amplify/aws-sdk-ios). Your identity provider class should return a response object containing the token as an attribute.

```
import AWSCore
/*
 * 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

    // Set the identity id and return the token
    self.identityId = resultFromAbove.identityId
    return AWSTask(result: resultFromAbove.token)
}
```

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.

```
override func logins () -> AWSTask<NSDictionary> {
    if(/*logic to determine if user is unauthenticated*/) {
        return AWSTask(result:nil)
    }else {
        return super.logins()
    }
}
```

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

```
override func logins () -> AWSTask<NSDictionary> {
    if(/*logic to determine if user is unauthenticated*/) {
        return AWSTask(result:nil)
    }else if (/*logic to determine if user is Facebook*/){
        if let token = AccessToken.current?.authenticationToken {
            return AWSTask(result: [AWSIdentityProviderFacebook:token])
        }
        return AWSTask(error:NSError(domain: "Facebook Login", code: -1 , userInfo: ["Facebook" : "No current Facebook access token"]))
    }else {
        return super.logins()
    }
}
```

### JavaScript
<a name="implement-id-provider-1.javascript"></a>

Once you obtain an identity ID and session token from your backend, you will pass them into the `AWS.CognitoIdentityCredentials` provider. Here's an example.

```
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
   IdentityPoolId: 'IDENTITY_POOL_ID',
   IdentityId: 'IDENTITY_ID_RETURNED_FROM_YOUR_PROVIDER',
   Logins: {
      'cognito-identity.amazonaws.com': 'TOKEN_RETURNED_FROM_YOUR_PROVIDER'
   }
});
```

### Unity
<a name="implement-id-provider-1.unity"></a>

To use developer-authenticated identities, you must extend `CognitoAWSCredentials` and override the `RefreshIdentity` method to retrieve the user identity id and token from your backend and return them. Following 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;

public class DeveloperAuthenticatedCredentials : CognitoAWSCredentials
{
    const string PROVIDER_NAME = "example.com";
    const string IDENTITY_POOL = "IDENTITY_POOL_ID";
    static readonly RegionEndpoint REGION = RegionEndpoint.USEast1;

    private string login = null;

    public DeveloperAuthenticatedCredentials(string loginAlias)
        : base(IDENTITY_POOL, REGION)
    {
        login = loginAlias;
    }

    protected override IdentityState RefreshIdentity()
    {
        IdentityState state = null;
        ManualResetEvent waitLock = new ManualResetEvent(false);
        MainThreadDispatcher.ExecuteCoroutineOnMainThread(ContactProvider((s) =>
        {
            state = s;
            waitLock.Set();
        }));
        waitLock.WaitOne();
        return state;
    }

    IEnumerator ContactProvider(Action<IdentityState> callback)
    {
        WWW www = new WWW("http://example.com/?username="+login);
        yield return www;
        string response = www.text;

        JsonData json = JsonMapper.ToObject(response);

        //The backend has to send us back an Identity and a OpenID token
        string identityId = json["IdentityId"].ToString();
        string token = json["Token"].ToString();

        IdentityState state = new IdentityState(identityId, PROVIDER_NAME, token, false);
        callback(state);
    }
}
```

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;

public class MainThreadDispatcher : MonoBehaviour
{
    static Queue<IEnumerator> _coroutineQueue = new Queue<IEnumerator>();
    static object _lock = new object();

    public void Update()
    {
        while (_coroutineQueue.Count > 0)
        {
            StartCoroutine(_coroutineQueue.Dequeue());
        }
    }

    public static void ExecuteCoroutineOnMainThread(IEnumerator coroutine)
    {
        lock (_lock) {
            _coroutineQueue.Enqueue(coroutine);
        }
    }
}
```

### Xamarin
<a name="implement-id-provider-1.xamarin"></a>

To use developer-authenticated identities, you must extend `CognitoAWSCredentials` and override the `RefreshIdentity` method to retrieve the user identity id and token from your backend and return them. Following is a basic example of an identity provider that would contact a hypothetical backend at 'example.com':

```
public class DeveloperAuthenticatedCredentials : CognitoAWSCredentials
{
    const string PROVIDER_NAME = "example.com";
    const string IDENTITY_POOL = "IDENTITY_POOL_ID";
    static readonly RegionEndpoint REGION = RegionEndpoint.USEast1;
    private string login = null;

    public DeveloperAuthenticatedCredentials(string loginAlias)
        : base(IDENTITY_POOL, REGION)
    {
        login = loginAlias;
    }

    protected override async Task<IdentityState> RefreshIdentityAsync()
    {
        IdentityState state = null;
        //get your identity and set the state
        return state;
    }
}
```

## Updating the logins map (Android and iOS only)
<a name="updating-the-logins-map"></a>

### Android
<a name="updating-logins-map-1.android"></a>

After successfully authenticating the user with your authentication system, update the logins map with the developer provider name and a developer user identifier. This is an alphanumeric string that uniquely identifies a user in your authentication system. Be sure to call the `refresh` method after updating the logins map as the `identityId` might have changed:

```
HashMap<String, String> loginsMap = new HashMap<String, String>();
loginsMap.put(developerAuthenticationProvider.getProviderName(), developerUserIdentifier);

credentialsProvider.setLogins(loginsMap);
credentialsProvider.refresh();
```

### iOS - objective-C
<a name="updating-logins-map-1.ios-objc"></a>

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 (for example, 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
<a name="updating-logins-map-1.ios-swift"></a>

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

## Getting a token (server side)
<a name="getting-a-token-server-side"></a>

You obtain a token by calling [GetOpenIdTokenForDeveloperIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html). This API must be invoked from your backend using AWS developer credentials. It must not be invoked from the client SDK. The API receives the Cognito identity pool ID; a logins map containing your identity provider name as the key and identifier as the value; and optionally a Cognito identity ID (for example, you are making an unauthenticated user authenticated). The identifier can be the username of your user, an email address, or a numerical value. The API responds to your call with a unique Cognito ID for your user and an OpenID Connect token for the end user.

A few things to keep in mind about the token returned by `GetOpenIdTokenForDeveloperIdentity`:
+ 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 that you can set is 24 hours.
+ 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.

```
// authenticate your end user as appropriate
// ....

// if authenticated, initialize a cognito client with your AWS developer credentials
AmazonCognitoIdentity identityClient = new AmazonCognitoIdentityClient(
  new BasicAWSCredentials("access_key_id", "secret_access_key")
);

// create a new request to retrieve the token for your end user
GetOpenIdTokenForDeveloperIdentityRequest request =
  new GetOpenIdTokenForDeveloperIdentityRequest();
request.setIdentityPoolId("YOUR_COGNITO_IDENTITY_POOL_ID");

request.setIdentityId("YOUR_COGNITO_IDENTITY_ID"); //optional, set this if your client has an
                                                   //identity ID that you want to link to this 
                                                   //developer account

// 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);

// optionally set token duration (in seconds)
request.setTokenDuration(60 * 15l);
GetOpenIdTokenForDeveloperIdentityResult response =
  identityClient.getOpenIdTokenForDeveloperIdentity(request);

// obtain identity id and token to return to your client
String identityId = response.getIdentityId();
String token = response.getToken();

//code to return identity id and token to client
//...
```

Following the preceding steps, 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](https://forums.aws.amazon.com/forum.jspa?forumID=173).

## Connect to an existing social identity
<a name="connect-to-an-existing-social-identity"></a>

All linking of providers when you are using developer-authenticated identities must be done from your backend. To connect a custom identity to a user's social identity (Login with Amazon, Sign in with Apple, Facebook, or Google), add the identity provider token to the logins map when you call [GetOpenIdTokenForDeveloperIdentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html). To make this possible, when you call your backend from your client SDK to authenticate your end user, additionally pass the end user's social provider token.

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

## Supporting transition between providers
<a name="supporting-transition-between-providers"></a>

### Android
<a name="support-transition-between-providers-1.android"></a>

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.

The `refresh` method checks the logins map. If the map is not empty and has a key with developer provider name, then call your backend. Otherwise, call the getIdentityId method and return null.

```
public String refresh() {

   setToken(null);

   // If the logins map is not empty make a call to your backend
   // to get the token and identityId
   if (getProviderName() != null &&
      !this.loginsMap.isEmpty() &&
      this.loginsMap.containsKey(getProviderName())) {

      /**
       * This is where you would call your backend
       **/

      // now set the returned identity id and token in the provider
      update(identityId, token);
      return token;

   } 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:

```
public String getIdentityId() {

   // Load the identityId from the cache
   identityId = cachedIdentityId;

   if (identityId == null) {

      // If the logins map is not empty make a call to your backend
      // to get the token and identityId

      if (getProviderName() != null && !this.loginsMap.isEmpty()
         && this.loginsMap.containsKey(getProviderName())) {

         /**
           * This is where you would call your backend
          **/

         // now set the returned identity id and token in the provider
         update(identityId, token);
         return token;

      } else {
         // Otherwise call &COG; using getIdentityId of super class
         return super.getIdentityId();
      }

   } else {
      return identityId;
   }

}
```

### iOS - objective-C
<a name="support-transition-between-providers-1.ios-objc"></a>

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](https://github.com/aws-amplify/aws-sdk-ios) `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.

```
- (AWSTask<NSDictionary<NSString *, NSString *> *> *)logins {
    if(/*logic to determine if user is unauthenticated*/) {
        return [AWSTask taskWithResult:nil];
    }else if (/*logic to determine if user is Facebook*/){
        return [AWSTask taskWithResult: @{ AWSIdentityProviderFacebook : [FBSDKAccessToken currentAccessToken] }];
    }else {
        return [super logins];
    }
}
```

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 (for example, you are not providing tokens for multiple providers in your logins dictionary), call `[credentialsProvider clearKeychain];`. This will clear both the credentials and identity and force the SDK to get new ones.

### iOS - swift
<a name="support-transition-between-providers-1.ios-swift"></a>

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](https://github.com/aws-amplify/aws-sdk-ios) `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.

```
override func logins () -> AWSTask<NSDictionary> {
    if(/*logic to determine if user is unauthenticated*/) {
        return AWSTask(result:nil)
    }else if (/*logic to determine if user is Facebook*/){
        if let token = AccessToken.current?.authenticationToken {
            return AWSTask(result: [AWSIdentityProviderFacebook:token])
        }
        return AWSTask(error:NSError(domain: "Facebook Login", code: -1 , userInfo: ["Facebook" : "No current Facebook access token"]))
    }else {
        return super.logins()
    }
}
```

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.

### Unity
<a name="support-transition-between-providers-1.unity"></a>

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

The recommended way to do it in Unity is to extend your identity provider from AmazonCognitoEnhancedIdentityProvide instead of AbstractCognitoIdentityProvider, and call the parent RefreshAsync method instead of your own in case the user is not authenticated with your own backend. If the user is authenticated, you can use the same flow explained before.

### Xamarin
<a name="support-transition-between-providers-1.xamarin"></a>

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

# Switching unauthenticated users to authenticated users
<a name="switching-identities"></a>

Amazon Cognito identity pools support both authenticated and unauthenticated users. Unauthenticated users receive access to your AWS resources even if they aren't logged in with any of your identity providers (IdPs). This degree of access is useful to display content to users before they log in. Each unauthenticated user has a unique identity in the identity pool, even though they haven't been individually logged in and authenticated.

This section describes the case where your user chooses to switch from logging in with an unauthenticated identity to using an authenticated identity.

## Android
<a name="switching-identities-1.android"></a>

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.

Your application is informed of a profile merge through the `IdentityChangedListener` interface. Implement the `identityChanged` method in the interface to receive these messages:

```
@override
public void identityChanged(String oldIdentityId, String newIdentityId) {
    // handle the change
}
```

## iOS - objective-C
<a name="switching-identities-1.ios-objc"></a>

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` informs your application of a profile merge:

```
[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(identityIdDidChange:)
                                      name:AWSCognitoIdentityIdChangedNotification
                                      object:nil];

-(void)identityDidChange:(NSNotification*)notification {
    NSDictionary *userInfo = notification.userInfo;
    NSLog(@"identity changed from %@ to %@",
        [userInfo objectForKey:AWSCognitoNotificationPreviousId],
        [userInfo objectForKey:AWSCognitoNotificationNewId]);
}
```

## iOS - swift
<a name="switching-identities-1.ios-swift"></a>

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` informs your application of a profile merge:

```
[NSNotificationCenter.defaultCenter().addObserver(observer: self
   selector:"identityDidChange"
   name:AWSCognitoIdentityIdChangedNotification
   object:nil)

func identityDidChange(notification: NSNotification!) {
  if let userInfo = notification.userInfo as? [String: AnyObject] {
    print("identity changed from: \(userInfo[AWSCognitoNotificationPreviousId])
    to: \(userInfo[AWSCognitoNotificationNewId])")
  }
}
```

## JavaScript
<a name="switching-identities-1.javascript"></a>

### Initially unauthenticated user
<a name="switching-identities-1.javascript-unauth"></a>

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:

```
// set the default config object
var creds = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030'
});
AWS.config.credentials = creds;
```

### Switch to authenticated user
<a name="switching-identities-1.javascript-auth"></a>

When an unauthenticated user logs in to an IdP and you have a token, you can switch the user from unauthenticated to authenticated by calling a custom function that updates the credentials object and adds the Logins token:

```
// Called when an identity provider has a token for a logged in user
function userLoggedIn(providerName, token) {
    creds.params.Logins = creds.params.Logins || {};
    creds.params.Logins[providerName] = token;

    // Expire credentials to refresh them on the next request
    creds.expired = true;
}
```

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](https://docs.aws.amazon.com/sdk-for-javascript/latest/developer-guide/global-config-object.html).

For more information about the `CognitoIdentityCredentials` object, see [AWS.CognitoIdentityCredentials](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityCredentials.html) in the AWS SDK for JavaScript API Reference.

## Unity
<a name="switching-identities-1.unity"></a>

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.

You can subscribe to the `IdentityChangedEvent` to be notified of profile merges:

```
credentialsProvider.IdentityChangedEvent += delegate(object sender, CognitoAWSCredentials.IdentityChangedArgs e)
{
    // handle the change
    Debug.log("Identity changed from " + e.OldIdentityId + " to " + e.NewIdentityId);
};
```

## Xamarin
<a name="switching-identities-1.xamarin"></a>

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.

```
credentialsProvider.IdentityChangedEvent += delegate(object sender, CognitoAWSCredentials.IdentityChangedArgs e){
    // handle the change
    Console.WriteLine("Identity changed from " + e.OldIdentityId + " to " + e.NewIdentityId);
};
```