Skip to content
v2.275.0

Amazon Cognito Identity Pool Construct Library ​

Amazon Cognito Identity Pools enable you to grant your users access to other AWS services.

Identity Pools are one of the two main components of Amazon Cognito, which provides authentication, authorization, and user management for your web and mobile apps. Your users can sign in through a trusted identity provider, like a user pool or a SAML 2.0 service, as well as with third party providers such as Facebook, Amazon, Google or Apple.

The other main component in Amazon Cognito is user pools. User Pools are user directories that provide sign-up and sign-in options for your app users.

This module is part of the AWS Cloud Development Kit project.

ts
import { IdentityPool, UserPoolAuthenticationProvider } from 'aws-cdk-lib/aws-cognito-identitypool';
python
from aws_cdk.aws_cognito_identitypool import IdentityPool, UserPoolAuthenticationProvider
java
import software.amazon.awscdk.services.cognito.identitypool.IdentityPool;
import software.amazon.awscdk.services.cognito.identitypool.UserPoolAuthenticationProvider;
csharp
using Amazon.CDK.AWS.Cognito.Identitypool;
go
import "github.com/aws/aws-cdk-go/awscdk"

Identity Pools ​

Identity pools provide temporary AWS credentials for users who are guests (unauthenticated) and for users who have authenticated by presenting a token from another identity provider. An identity pool is a store of user identity data specific to an account.

Identity pools can be used in conjunction with Cognito User Pools or by accessing external federated identity providers directly. Learn more at Amazon Cognito Identity Pools.

Authenticated and Unauthenticated Identities ​

Identity pools define two types of identities: authenticated(user) and unauthenticated (guest). Every identity in an identity pool is either authenticated or unauthenticated. Each identity pool has a default role for authenticated identities, and a default role for unauthenticated identities. Absent other overriding rules (see below), these are the roles that will be assumed by the corresponding users in the authentication process.

A basic Identity Pool with minimal configuration has no required props, with default authenticated (user) and unauthenticated (guest) roles applied to the identity pool:

ts
new IdentityPool(this, 'myIdentityPool');
python
IdentityPool(self, "myIdentityPool")
java
new IdentityPool(this, "myIdentityPool");
csharp
new IdentityPool(this, "myIdentityPool");
go
awscdk.NewIdentityPool(this, jsii.String("myIdentityPool"))

By default, both the authenticated and unauthenticated roles will have no permissions attached. When granting permissions, you should ensure that you are granting the least privileged permissions required for your use case. Grant permissions to roles using the public authenticatedRole and unauthenticatedRole properties:

ts
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';

const identityPool = new IdentityPool(this, 'myIdentityPool');
declare const table: dynamodb.Table;

// Grant permissions to authenticated users
table.grantReadWriteData(identityPool.authenticatedRole);
// Grant permissions to unauthenticated guest users
table.grantReadData(identityPool.unauthenticatedRole);

// Or add policy statements straight to the role
identityPool.authenticatedRole.addToPrincipalPolicy(new iam.PolicyStatement({
  effect: iam.Effect.ALLOW,
  actions: ['dynamodb:UpdateItem'],
  resources: [table.tableArn],
}));
python
import aws_cdk.aws_dynamodb as dynamodb
# table: dynamodb.Table


identity_pool = IdentityPool(self, "myIdentityPool")

# Grant permissions to authenticated users
table.grant_read_write_data(identity_pool.authenticated_role)
# Grant permissions to unauthenticated guest users
table.grant_read_data(identity_pool.unauthenticated_role)

# Or add policy statements straight to the role
identity_pool.authenticated_role.add_to_principal_policy(iam.PolicyStatement(
    effect=iam.Effect.ALLOW,
    actions=["dynamodb:UpdateItem"],
    resources=[table.table_arn]
))
java
import software.amazon.awscdk.services.dynamodb.*;
Table table;


IdentityPool identityPool = new IdentityPool(this, "myIdentityPool");

// Grant permissions to authenticated users
table.grantReadWriteData(identityPool.getAuthenticatedRole());
// Grant permissions to unauthenticated guest users
table.grantReadData(identityPool.getUnauthenticatedRole());

// Or add policy statements straight to the role
identityPool.authenticatedRole.addToPrincipalPolicy(PolicyStatement.Builder.create()
        .effect(Effect.ALLOW)
        .actions(List.of("dynamodb:UpdateItem"))
        .resources(List.of(table.getTableArn()))
        .build());
csharp
using Amazon.CDK.AWS.DynamoDB;
Table table;


var identityPool = new IdentityPool(this, "myIdentityPool");

// Grant permissions to authenticated users
table.GrantReadWriteData(identityPool.AuthenticatedRole);
// Grant permissions to unauthenticated guest users
table.GrantReadData(identityPool.UnauthenticatedRole);

// Or add policy statements straight to the role
identityPool.AuthenticatedRole.AddToPrincipalPolicy(new PolicyStatement(new PolicyStatementProps {
    Effect = Effect.ALLOW,
    Actions = new [] { "dynamodb:UpdateItem" },
    Resources = new [] { table.TableArn }
}));
go
import dynamodb "github.com/aws/aws-cdk-go/awscdk"
var table Table


identityPool := awscdk.NewIdentityPool(this, jsii.String("myIdentityPool"))

// Grant permissions to authenticated users
table.GrantReadWriteData(identityPool.AuthenticatedRole)
// Grant permissions to unauthenticated guest users
table.GrantReadData(identityPool.UnauthenticatedRole)

// Or add policy statements straight to the role
identityPool.AuthenticatedRole.AddToPrincipalPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Effect: iam.Effect_ALLOW,
	Actions: []*string{
		jsii.String("dynamodb:UpdateItem"),
	},
	Resources: []*string{
		table.tableArn,
	},
}))

The default roles can also be supplied in IdentityPoolProps:

ts
const stack = new Stack();
const authenticatedRole = new iam.Role(this, 'authRole', {
  assumedBy: new iam.ServicePrincipal('service.amazonaws.com'),
});
const unauthenticatedRole = new iam.Role(this, 'unauthRole', {
  assumedBy: new iam.ServicePrincipal('service.amazonaws.com'),
});
const identityPool = new IdentityPool(this, 'TestIdentityPoolActions', {
  authenticatedRole,
  unauthenticatedRole,
});
python
stack = Stack()
authenticated_role = iam.Role(self, "authRole",
    assumed_by=iam.ServicePrincipal("service.amazonaws.com")
)
unauthenticated_role = iam.Role(self, "unauthRole",
    assumed_by=iam.ServicePrincipal("service.amazonaws.com")
)
identity_pool = IdentityPool(self, "TestIdentityPoolActions",
    authenticated_role=authenticated_role,
    unauthenticated_role=unauthenticated_role
)
java
Stack stack = new Stack();
Role authenticatedRole = Role.Builder.create(this, "authRole")
        .assumedBy(new ServicePrincipal("service.amazonaws.com"))
        .build();
Role unauthenticatedRole = Role.Builder.create(this, "unauthRole")
        .assumedBy(new ServicePrincipal("service.amazonaws.com"))
        .build();
IdentityPool identityPool = IdentityPool.Builder.create(this, "TestIdentityPoolActions")
        .authenticatedRole(authenticatedRole)
        .unauthenticatedRole(unauthenticatedRole)
        .build();
csharp
var stack = new Stack();
var authenticatedRole = new Role(this, "authRole", new RoleProps {
    AssumedBy = new ServicePrincipal("service.amazonaws.com")
});
var unauthenticatedRole = new Role(this, "unauthRole", new RoleProps {
    AssumedBy = new ServicePrincipal("service.amazonaws.com")
});
var identityPool = new IdentityPool(this, "TestIdentityPoolActions", new IdentityPoolProps {
    AuthenticatedRole = authenticatedRole,
    UnauthenticatedRole = unauthenticatedRole
});
go
stack := awscdk.Newstack()
authenticatedRole := iam.NewRole(this, jsii.String("authRole"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("service.amazonaws.com")),
})
unauthenticatedRole := iam.NewRole(this, jsii.String("unauthRole"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("service.amazonaws.com")),
})
identityPool := awscdk.NewIdentityPool(this, jsii.String("TestIdentityPoolActions"), &IdentityPoolProps{
	AuthenticatedRole: AuthenticatedRole,
	UnauthenticatedRole: UnauthenticatedRole,
})

Authentication Providers ​

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

Authentication providers can be associated with an Identity Pool by first associating them with a Cognito User Pool or by associating the provider directly with the identity pool.

User Pool Authentication Provider ​

In order to attach a user pool to an identity pool as an authentication provider, the identity pool needs properties from both the user pool and the user pool client. For this reason identity pools use a UserPoolAuthenticationProvider to gather the necessary properties from the user pool constructs.

ts
const userPool = new cognito.UserPool(this, 'Pool');

new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  authenticationProviders: {
    userPools: [new UserPoolAuthenticationProvider({ userPool })],
  },
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolAuthenticationProviders
user_pool = cognito.UserPool(self, "Pool")

IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    authentication_providers=IdentityPoolAuthenticationProviders(
        user_pools=[UserPoolAuthenticationProvider(user_pool=user_pool)]
    )
)
java
UserPool userPool = new UserPool(this, "Pool");

IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .authenticationProviders(IdentityPoolAuthenticationProviders.builder()
                .userPools(List.of(UserPoolAuthenticationProvider.Builder.create().userPool(userPool).build()))
                .build())
        .build();
csharp
var userPool = new UserPool(this, "Pool");

new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    AuthenticationProviders = new IdentityPoolAuthenticationProviders {
        UserPools = new [] { new UserPoolAuthenticationProvider(new UserPoolAuthenticationProviderProps { UserPool = userPool }) }
    }
});
go
userPool := cognito.NewUserPool(this, jsii.String("Pool"))

awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	AuthenticationProviders: &IdentityPoolAuthenticationProviders{
		UserPools: []IUserPoolAuthenticationProvider{
			awscdk.NewUserPoolAuthenticationProvider(&UserPoolAuthenticationProviderProps{
				UserPool: *UserPool,
			}),
		},
	},
})

User pools can also be associated with an identity pool after instantiation. The Identity Pool's addUserPoolAuthentication method returns the User Pool Client that has been created:

ts
declare const identityPool: IdentityPool;
const userPool = new cognito.UserPool(this, 'Pool');
const userPoolClient = identityPool.addUserPoolAuthentication(new UserPoolAuthenticationProvider({
  userPool,
}));
python
# identity_pool: IdentityPool

user_pool = cognito.UserPool(self, "Pool")
user_pool_client = identity_pool.add_user_pool_authentication(UserPoolAuthenticationProvider(
    user_pool=user_pool
))
java
IdentityPool identityPool;

UserPool userPool = new UserPool(this, "Pool");
void userPoolClient = identityPool.addUserPoolAuthentication(UserPoolAuthenticationProvider.Builder.create()
        .userPool(userPool)
        .build());
csharp
IdentityPool identityPool;

var userPool = new UserPool(this, "Pool");
var userPoolClient = identityPool.AddUserPoolAuthentication(new UserPoolAuthenticationProvider(new UserPoolAuthenticationProviderProps {
    UserPool = userPool
}));
go
var identityPool IdentityPool

userPool := cognito.NewUserPool(this, jsii.String("Pool"))
userPoolClient := identityPool.AddUserPoolAuthentication(awscdk.NewUserPoolAuthenticationProvider(&UserPoolAuthenticationProviderProps{
	UserPool: UserPool,
}))

Server Side Token Check ​

With the IdentityPool CDK Construct, by default the pool is configured to check with the integrated user pools to make sure that the user has not been globally signed out or deleted before the identity pool provides an OIDC token or AWS credentials for the user.

If the user is signed out or deleted, the identity pool will return a 400 Not Authorized error. This setting can be disabled, however, in several ways.

Setting disableServerSideTokenCheck to true will change the default behavior to no server side token check. Learn more here:

ts
declare const identityPool: IdentityPool;
const userPool = new cognito.UserPool(this, 'Pool');
identityPool.addUserPoolAuthentication(new UserPoolAuthenticationProvider({
  userPool,
  disableServerSideTokenCheck: true,
}));
python
# identity_pool: IdentityPool

user_pool = cognito.UserPool(self, "Pool")
identity_pool.add_user_pool_authentication(UserPoolAuthenticationProvider(
    user_pool=user_pool,
    disable_server_side_token_check=True
))
java
IdentityPool identityPool;

UserPool userPool = new UserPool(this, "Pool");
identityPool.addUserPoolAuthentication(UserPoolAuthenticationProvider.Builder.create()
        .userPool(userPool)
        .disableServerSideTokenCheck(true)
        .build());
csharp
IdentityPool identityPool;

var userPool = new UserPool(this, "Pool");
identityPool.AddUserPoolAuthentication(new UserPoolAuthenticationProvider(new UserPoolAuthenticationProviderProps {
    UserPool = userPool,
    DisableServerSideTokenCheck = true
}));
go
var identityPool IdentityPool

userPool := cognito.NewUserPool(this, jsii.String("Pool"))
identityPool.AddUserPoolAuthentication(awscdk.NewUserPoolAuthenticationProvider(&UserPoolAuthenticationProviderProps{
	UserPool: UserPool,
	DisableServerSideTokenCheck: jsii.Boolean(true),
}))

Associating an External Provider Directly ​

One or more external identity providers can be associated with an identity pool directly using authenticationProviders:

ts
new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  authenticationProviders: {
    amazon: {
      appId: 'amzn1.application.12312k3j234j13rjiwuenf',
    },
    facebook: {
      appId: '1234567890123',
    },
    google: {
      clientId: '12345678012.apps.googleusercontent.com',
    },
    apple: {
      servicesId: 'com.myappleapp.auth',
    },
    twitter: {
      consumerKey: 'my-twitter-id',
      consumerSecret: 'my-twitter-secret',
    },
  },
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolAuthenticationProviders, IdentityPoolAmazonLoginProvider, IdentityPoolFacebookLoginProvider, IdentityPoolGoogleLoginProvider, IdentityPoolAppleLoginProvider, IdentityPoolTwitterLoginProvider
IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    authentication_providers=IdentityPoolAuthenticationProviders(
        amazon=IdentityPoolAmazonLoginProvider(
            app_id="amzn1.application.12312k3j234j13rjiwuenf"
        ),
        facebook=IdentityPoolFacebookLoginProvider(
            app_id="1234567890123"
        ),
        google=IdentityPoolGoogleLoginProvider(
            client_id="12345678012.apps.googleusercontent.com"
        ),
        apple=IdentityPoolAppleLoginProvider(
            services_id="com.myappleapp.auth"
        ),
        twitter=IdentityPoolTwitterLoginProvider(
            consumer_key="my-twitter-id",
            consumer_secret="my-twitter-secret"
        )
    )
)
java
IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .authenticationProviders(IdentityPoolAuthenticationProviders.builder()
                .amazon(IdentityPoolAmazonLoginProvider.builder()
                        .appId("amzn1.application.12312k3j234j13rjiwuenf")
                        .build())
                .facebook(IdentityPoolFacebookLoginProvider.builder()
                        .appId("1234567890123")
                        .build())
                .google(IdentityPoolGoogleLoginProvider.builder()
                        .clientId("12345678012.apps.googleusercontent.com")
                        .build())
                .apple(IdentityPoolAppleLoginProvider.builder()
                        .servicesId("com.myappleapp.auth")
                        .build())
                .twitter(IdentityPoolTwitterLoginProvider.builder()
                        .consumerKey("my-twitter-id")
                        .consumerSecret("my-twitter-secret")
                        .build())
                .build())
        .build();
csharp
new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    AuthenticationProviders = new IdentityPoolAuthenticationProviders {
        Amazon = new IdentityPoolAmazonLoginProvider {
            AppId = "amzn1.application.12312k3j234j13rjiwuenf"
        },
        Facebook = new IdentityPoolFacebookLoginProvider {
            AppId = "1234567890123"
        },
        Google = new IdentityPoolGoogleLoginProvider {
            ClientId = "12345678012.apps.googleusercontent.com"
        },
        Apple = new IdentityPoolAppleLoginProvider {
            ServicesId = "com.myappleapp.auth"
        },
        Twitter = new IdentityPoolTwitterLoginProvider {
            ConsumerKey = "my-twitter-id",
            ConsumerSecret = "my-twitter-secret"
        }
    }
});
go
awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	AuthenticationProviders: &IdentityPoolAuthenticationProviders{
		Amazon: &IdentityPoolAmazonLoginProvider{
			AppId: jsii.String("amzn1.application.12312k3j234j13rjiwuenf"),
		},
		Facebook: &IdentityPoolFacebookLoginProvider{
			AppId: jsii.String("1234567890123"),
		},
		Google: &IdentityPoolGoogleLoginProvider{
			ClientId: jsii.String("12345678012.apps.googleusercontent.com"),
		},
		Apple: &IdentityPoolAppleLoginProvider{
			ServicesId: jsii.String("com.myappleapp.auth"),
		},
		Twitter: &IdentityPoolTwitterLoginProvider{
			ConsumerKey: jsii.String("my-twitter-id"),
			ConsumerSecret: jsii.String("my-twitter-secret"),
		},
	},
})

To associate more than one provider of the same type with the identity pool, use User Pools, OpenIdConnect, or SAML. Only one provider per external service can be attached directly to the identity pool.

OpenId Connect and Saml ​

OpenID Connect is an open standard for authentication that is supported by a number of login providers. Amazon Cognito supports linking of identities with OpenID Connect providers that are configured through AWS Identity and Access Management.

An identity provider that supports Security Assertion Markup Language 2.0 (SAML 2.0) can be used to provide a simple onboarding flow for users. The SAML-supporting identity provider specifies the IAM roles that can be assumed by users so that different users can be granted different sets of permissions. Associating an OpenId Connect or Saml provider with an identity pool:

ts
declare const openIdConnectProvider: iam.OpenIdConnectProvider;
declare const samlProvider: iam.SamlProvider;

new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  authenticationProviders: {
    openIdConnectProviders: [openIdConnectProvider],
    samlProviders: [samlProvider],
  },
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolAuthenticationProviders
# open_id_connect_provider: iam.OpenIdConnectProvider
# saml_provider: iam.SamlProvider


IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    authentication_providers=IdentityPoolAuthenticationProviders(
        open_id_connect_providers=[open_id_connect_provider],
        saml_providers=[saml_provider]
    )
)
java
OpenIdConnectProvider openIdConnectProvider;
SamlProvider samlProvider;


IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .authenticationProviders(IdentityPoolAuthenticationProviders.builder()
                .openIdConnectProviders(List.of(openIdConnectProvider))
                .samlProviders(List.of(samlProvider))
                .build())
        .build();
csharp
OpenIdConnectProvider openIdConnectProvider;
SamlProvider samlProvider;


new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    AuthenticationProviders = new IdentityPoolAuthenticationProviders {
        OpenIdConnectProviders = new [] { openIdConnectProvider },
        SamlProviders = new [] { samlProvider }
    }
});
go
var openIdConnectProvider OpenIdConnectProvider
var samlProvider SamlProvider


awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	AuthenticationProviders: &IdentityPoolAuthenticationProviders{
		OpenIdConnectProviders: []IOIDCProviderRef{
			openIdConnectProvider,
		},
		SamlProviders: []ISAMLProviderRef{
			samlProvider,
		},
	},
})

Custom Providers ​

The identity pool's behavior can be customized further using custom developer authenticated identities. With developer authenticated identities, users can be registered and authenticated via an existing authentication process while still using Amazon Cognito to synchronize user data and access AWS resources.

Like the supported external providers, though, only one custom provider can be directly associated with the identity pool.

ts
declare const openIdConnectProvider: iam.OpenIdConnectProvider;
new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  authenticationProviders: {
    google: {
      clientId: '12345678012.apps.googleusercontent.com',
    },
    openIdConnectProviders: [openIdConnectProvider],
    customProvider: 'my-custom-provider.example.com',
  },
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolAuthenticationProviders, IdentityPoolGoogleLoginProvider
# open_id_connect_provider: iam.OpenIdConnectProvider

IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    authentication_providers=IdentityPoolAuthenticationProviders(
        google=IdentityPoolGoogleLoginProvider(
            client_id="12345678012.apps.googleusercontent.com"
        ),
        open_id_connect_providers=[open_id_connect_provider],
        custom_provider="my-custom-provider.example.com"
    )
)
java
OpenIdConnectProvider openIdConnectProvider;

IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .authenticationProviders(IdentityPoolAuthenticationProviders.builder()
                .google(IdentityPoolGoogleLoginProvider.builder()
                        .clientId("12345678012.apps.googleusercontent.com")
                        .build())
                .openIdConnectProviders(List.of(openIdConnectProvider))
                .customProvider("my-custom-provider.example.com")
                .build())
        .build();
csharp
OpenIdConnectProvider openIdConnectProvider;

new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    AuthenticationProviders = new IdentityPoolAuthenticationProviders {
        Google = new IdentityPoolGoogleLoginProvider {
            ClientId = "12345678012.apps.googleusercontent.com"
        },
        OpenIdConnectProviders = new [] { openIdConnectProvider },
        CustomProvider = "my-custom-provider.example.com"
    }
});
go
var openIdConnectProvider OpenIdConnectProvider

awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	AuthenticationProviders: &IdentityPoolAuthenticationProviders{
		Google: &IdentityPoolGoogleLoginProvider{
			ClientId: jsii.String("12345678012.apps.googleusercontent.com"),
		},
		OpenIdConnectProviders: []IOIDCProviderRef{
			openIdConnectProvider,
		},
		CustomProvider: jsii.String("my-custom-provider.example.com"),
	},
})

Role Mapping ​

In addition to setting default roles for authenticated and unauthenticated users, identity pools can also be used to define rules to choose the role for each user based on claims in the user's ID token by using Role Mapping. When using role mapping, it's important to be aware of some of the permissions the role will need, and that the least privileged roles necessary are given for your specific use case. An in depth review of roles and role mapping can be found here.

Using a token-based approach to role mapping will allow mapped roles to be passed through the cognito:roles or cognito:preferred_role claims from the identity provider:

ts
import { IdentityPoolProviderUrl } from 'aws-cdk-lib/aws-cognito-identitypool';

new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  roleMappings: [{
    providerUrl: IdentityPoolProviderUrl.AMAZON,
    useToken: true,
  }],
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolRoleMapping
from aws_cdk.aws_cognito_identitypool import IdentityPoolProviderUrl


IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    role_mappings=[IdentityPoolRoleMapping(
        provider_url=IdentityPoolProviderUrl.AMAZON,
        use_token=True
    )]
)
java
import software.amazon.awscdk.services.cognito.identitypool.IdentityPoolProviderUrl;


IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .roleMappings(List.of(IdentityPoolRoleMapping.builder()
                .providerUrl(IdentityPoolProviderUrl.AMAZON)
                .useToken(true)
                .build()))
        .build();
csharp
using Amazon.CDK.AWS.Cognito.Identitypool;


new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    RoleMappings = new [] { new IdentityPoolRoleMapping {
        ProviderUrl = IdentityPoolProviderUrl.AMAZON,
        UseToken = true
    } }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	RoleMappings: []IdentityPoolRoleMapping{
		&IdentityPoolRoleMapping{
			ProviderUrl: awscdk.IdentityPoolProviderUrl_AMAZON(),
			UseToken: jsii.Boolean(true),
		},
	},
})

Using a rule-based approach to role mapping allows roles to be assigned based on custom claims passed from the identity provider:

ts
import { IdentityPoolProviderUrl, RoleMappingMatchType } from 'aws-cdk-lib/aws-cognito-identitypool';

declare const adminRole: iam.Role;
declare const nonAdminRole: iam.Role;
new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  // Assign specific roles to users based on whether or not the custom admin claim is passed from the identity provider
  roleMappings: [{
    providerUrl: IdentityPoolProviderUrl.AMAZON,
    rules: [
      {
        claim: 'custom:admin',
        claimValue: 'admin',
        mappedRole: adminRole,
      },
      {
        claim: 'custom:admin',
        claimValue: 'admin',
        matchType: RoleMappingMatchType.NOTEQUAL,
        mappedRole: nonAdminRole,
      }
    ],
  }],
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolRoleMapping, RoleMappingRule, RoleMappingRule
from aws_cdk.aws_cognito_identitypool import IdentityPoolProviderUrl, RoleMappingMatchType

# admin_role: iam.Role
# non_admin_role: iam.Role

IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    # Assign specific roles to users based on whether or not the custom admin claim is passed from the identity provider
    role_mappings=[IdentityPoolRoleMapping(
        provider_url=IdentityPoolProviderUrl.AMAZON,
        rules=[RoleMappingRule(
            claim="custom:admin",
            claim_value="admin",
            mapped_role=admin_role
        ), RoleMappingRule(
            claim="custom:admin",
            claim_value="admin",
            match_type=RoleMappingMatchType.NOTEQUAL,
            mapped_role=non_admin_role
        )
        ]
    )]
)
java
import software.amazon.awscdk.services.cognito.identitypool.IdentityPoolProviderUrl;
import software.amazon.awscdk.services.cognito.identitypool.RoleMappingMatchType;

Role adminRole;
Role nonAdminRole;

IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        // Assign specific roles to users based on whether or not the custom admin claim is passed from the identity provider
        .roleMappings(List.of(IdentityPoolRoleMapping.builder()
                .providerUrl(IdentityPoolProviderUrl.AMAZON)
                .rules(List.of(RoleMappingRule.builder()
                        .claim("custom:admin")
                        .claimValue("admin")
                        .mappedRole(adminRole)
                        .build(), RoleMappingRule.builder()
                        .claim("custom:admin")
                        .claimValue("admin")
                        .matchType(RoleMappingMatchType.NOTEQUAL)
                        .mappedRole(nonAdminRole)
                        .build()))
                .build()))
        .build();
csharp
using Amazon.CDK.AWS.Cognito.Identitypool;

Role adminRole;
Role nonAdminRole;

new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    // Assign specific roles to users based on whether or not the custom admin claim is passed from the identity provider
    RoleMappings = new [] { new IdentityPoolRoleMapping {
        ProviderUrl = IdentityPoolProviderUrl.AMAZON,
        Rules = new [] { new RoleMappingRule {
            Claim = "custom:admin",
            ClaimValue = "admin",
            MappedRole = adminRole
        }, new RoleMappingRule {
            Claim = "custom:admin",
            ClaimValue = "admin",
            MatchType = RoleMappingMatchType.NOTEQUAL,
            MappedRole = nonAdminRole
        } }
    } }
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var adminRole Role
var nonAdminRole Role

awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	// Assign specific roles to users based on whether or not the custom admin claim is passed from the identity provider
	RoleMappings: []IdentityPoolRoleMapping{
		&IdentityPoolRoleMapping{
			ProviderUrl: awscdk.IdentityPoolProviderUrl_AMAZON(),
			Rules: []RoleMappingRule{
				&RoleMappingRule{
					Claim: jsii.String("custom:admin"),
					ClaimValue: jsii.String("admin"),
					MappedRole: adminRole,
				},
				&RoleMappingRule{
					Claim: jsii.String("custom:admin"),
					ClaimValue: jsii.String("admin"),
					MatchType: awscdk.RoleMappingMatchType_NOTEQUAL,
					MappedRole: nonAdminRole,
				},
			},
		},
	},
})

Provider Urls ​

Role mappings must be associated with the url of an Identity Provider which can be supplied IdentityPoolProviderUrl. Supported Providers have static Urls that can be used:

ts
import { IdentityPoolProviderUrl } from 'aws-cdk-lib/aws-cognito-identitypool';

new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  roleMappings: [{
    providerUrl: IdentityPoolProviderUrl.FACEBOOK,
    useToken: true,
  }],
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolRoleMapping
from aws_cdk.aws_cognito_identitypool import IdentityPoolProviderUrl


IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    role_mappings=[IdentityPoolRoleMapping(
        provider_url=IdentityPoolProviderUrl.FACEBOOK,
        use_token=True
    )]
)
java
import software.amazon.awscdk.services.cognito.identitypool.IdentityPoolProviderUrl;


IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .roleMappings(List.of(IdentityPoolRoleMapping.builder()
                .providerUrl(IdentityPoolProviderUrl.FACEBOOK)
                .useToken(true)
                .build()))
        .build();
csharp
using Amazon.CDK.AWS.Cognito.Identitypool;


new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    RoleMappings = new [] { new IdentityPoolRoleMapping {
        ProviderUrl = IdentityPoolProviderUrl.FACEBOOK,
        UseToken = true
    } }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	RoleMappings: []IdentityPoolRoleMapping{
		&IdentityPoolRoleMapping{
			ProviderUrl: awscdk.IdentityPoolProviderUrl_FACEBOOK(),
			UseToken: jsii.Boolean(true),
		},
	},
})

For identity providers that don't have static Urls, a custom Url can be supplied:

ts
import { IdentityPoolProviderUrl } from 'aws-cdk-lib/aws-cognito-identitypool';

new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  roleMappings: [
    {
      providerUrl: IdentityPoolProviderUrl.custom('my-custom-provider.com'),
      useToken: true,
    },
  ],
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolRoleMapping
from aws_cdk.aws_cognito_identitypool import IdentityPoolProviderUrl


IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    role_mappings=[IdentityPoolRoleMapping(
        provider_url=IdentityPoolProviderUrl.custom("my-custom-provider.com"),
        use_token=True
    )
    ]
)
java
import software.amazon.awscdk.services.cognito.identitypool.IdentityPoolProviderUrl;


IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .roleMappings(List.of(IdentityPoolRoleMapping.builder()
                .providerUrl(IdentityPoolProviderUrl.custom("my-custom-provider.com"))
                .useToken(true)
                .build()))
        .build();
csharp
using Amazon.CDK.AWS.Cognito.Identitypool;


new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    RoleMappings = new [] { new IdentityPoolRoleMapping {
        ProviderUrl = IdentityPoolProviderUrl.Custom("my-custom-provider.com"),
        UseToken = true
    } }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	RoleMappings: []IdentityPoolRoleMapping{
		&IdentityPoolRoleMapping{
			ProviderUrl: awscdk.IdentityPoolProviderUrl_Custom(jsii.String("my-custom-provider.com")),
			UseToken: jsii.Boolean(true),
		},
	},
})

If a provider URL is a CDK Token, as it will be if you are trying to use a previously defined Cognito User Pool, you will need to also provide a mappingKey. This is because by default, the key in the Cloudformation role mapping hash is the providerUrl, and Cloudformation map keys must be concrete strings, they cannot be references. For example:

ts
import { UserPool, UserPoolClient } from 'aws-cdk-lib/aws-cognito';
import { IdentityPoolProviderUrl } from 'aws-cdk-lib/aws-cognito-identitypool';

declare const userPool: UserPool;
declare const userPoolClient: UserPoolClient;
new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  roleMappings: [{
    mappingKey: 'cognito',
    providerUrl: IdentityPoolProviderUrl.userPool(userPool, userPoolClient),
    useToken: true,
  }],
});
python
from aws_cdk.aws_cognito_identitypool import IdentityPoolRoleMapping
from aws_cdk.aws_cognito import UserPool, UserPoolClient
from aws_cdk.aws_cognito_identitypool import IdentityPoolProviderUrl

# user_pool: UserPool
# user_pool_client: UserPoolClient

IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    role_mappings=[IdentityPoolRoleMapping(
        mapping_key="cognito",
        provider_url=IdentityPoolProviderUrl.user_pool(user_pool, user_pool_client),
        use_token=True
    )]
)
java
import software.amazon.awscdk.services.cognito.UserPool;
import software.amazon.awscdk.services.cognito.UserPoolClient;
import software.amazon.awscdk.services.cognito.identitypool.IdentityPoolProviderUrl;

UserPool userPool;
UserPoolClient userPoolClient;

IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .roleMappings(List.of(IdentityPoolRoleMapping.builder()
                .mappingKey("cognito")
                .providerUrl(IdentityPoolProviderUrl.userPool(userPool, userPoolClient))
                .useToken(true)
                .build()))
        .build();
csharp
using Amazon.CDK.AWS.Cognito;
using Amazon.CDK.AWS.Cognito.Identitypool;

UserPool userPool;
UserPoolClient userPoolClient;

new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    RoleMappings = new [] { new IdentityPoolRoleMapping {
        MappingKey = "cognito",
        ProviderUrl = IdentityPoolProviderUrl.UserPool(userPool, userPoolClient),
        UseToken = true
    } }
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var userPool UserPool
var userPoolClient UserPoolClient

awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	RoleMappings: []IdentityPoolRoleMapping{
		&IdentityPoolRoleMapping{
			MappingKey: jsii.String("cognito"),
			ProviderUrl: awscdk.IdentityPoolProviderUrl_UserPool(userPool, userPoolClient),
			UseToken: jsii.Boolean(true),
		},
	},
})

See here for more information.

Authentication Flow ​

Identity Pool Authentication Flow defaults to the enhanced, simplified flow. The Classic (basic) Authentication Flow can also be implemented using allowClassicFlow:

ts
new IdentityPool(this, 'myidentitypool', {
  identityPoolName: 'myidentitypool',
  allowClassicFlow: true,
});
python
IdentityPool(self, "myidentitypool",
    identity_pool_name="myidentitypool",
    allow_classic_flow=True
)
java
IdentityPool.Builder.create(this, "myidentitypool")
        .identityPoolName("myidentitypool")
        .allowClassicFlow(true)
        .build();
csharp
new IdentityPool(this, "myidentitypool", new IdentityPoolProps {
    IdentityPoolName = "myidentitypool",
    AllowClassicFlow = true
});
go
awscdk.NewIdentityPool(this, jsii.String("myidentitypool"), &IdentityPoolProps{
	IdentityPoolName: jsii.String("myidentitypool"),
	AllowClassicFlow: jsii.Boolean(true),
})

Cognito Sync ​

It's now recommended to integrate AWS AppSync for synchronizing app data across devices, so Cognito Sync features like PushSync, CognitoEvents, and CognitoStreams are not a part of IdentityPool. More information can be found here.

Importing Identity Pools ​

You can import existing identity pools into your stack using Identity Pool static methods with the Identity Pool Id or Arn:

ts
IdentityPool.fromIdentityPoolId(this, 'my-imported-identity-pool',
  'us-east-1:dj2823ryiwuhef937');
IdentityPool.fromIdentityPoolArn(this, 'my-imported-identity-pool',
  'arn:aws:cognito-identity:us-east-1:123456789012:identitypool/us-east-1:dj2823ryiwuhef937');
python
IdentityPool.from_identity_pool_id(self, "my-imported-identity-pool", "us-east-1:dj2823ryiwuhef937")
IdentityPool.from_identity_pool_arn(self, "my-imported-identity-pool", "arn:aws:cognito-identity:us-east-1:123456789012:identitypool/us-east-1:dj2823ryiwuhef937")
java
IdentityPool.fromIdentityPoolId(this, "my-imported-identity-pool", "us-east-1:dj2823ryiwuhef937");
IdentityPool.fromIdentityPoolArn(this, "my-imported-identity-pool", "arn:aws:cognito-identity:us-east-1:123456789012:identitypool/us-east-1:dj2823ryiwuhef937");
csharp
IdentityPool.FromIdentityPoolId(this, "my-imported-identity-pool", "us-east-1:dj2823ryiwuhef937");
IdentityPool.FromIdentityPoolArn(this, "my-imported-identity-pool", "arn:aws:cognito-identity:us-east-1:123456789012:identitypool/us-east-1:dj2823ryiwuhef937");
go
awscdk.IdentityPool_FromIdentityPoolId(this, jsii.String("my-imported-identity-pool"), jsii.String("us-east-1:dj2823ryiwuhef937"))
awscdk.IdentityPool_FromIdentityPoolArn(this, jsii.String("my-imported-identity-pool"), jsii.String("arn:aws:cognito-identity:us-east-1:123456789012:identitypool/us-east-1:dj2823ryiwuhef937"))

Types ​

NameKindSummary
IdentityPoolConstruct (L2)Define a Cognito Identity Pool.
IdentityPoolAmazonLoginProviderStructLogin Provider for identity federation using Amazon credentials.
IdentityPoolAppleLoginProviderStructLogin Provider for identity federation using Apple credentials.
IdentityPoolAuthenticationProvidersStructExternal Authentication Providers for usage in Identity Pool.
IdentityPoolFacebookLoginProviderStructLogin Provider for identity federation using Facebook credentials.
IdentityPoolGoogleLoginProviderStructLogin Provider for identity federation using Google credentials.
IdentityPoolPropsStructProps for the Identity Pool construct.
IdentityPoolProviderTypeEnumTypes of Identity Pool Login Providers.
IdentityPoolProviderUrlClassKeys for Login Providers - each correspond to the client IDs of their respective federation Identity Providers.
IdentityPoolRoleMappingStructMap roles to users in the Identity Pool based on claims from the Identity Provider.
IdentityPoolTwitterLoginProviderStructLogin Provider for identity federation using Twitter credentials.
IIdentityPoolInterfaceRepresents a Cognito Identity Pool.
IUserPoolAuthenticationProviderInterfaceRepresents the concept of a User Pool Authentication Provider.
RoleMappingMatchTypeEnumTypes of matches allowed for role mapping.
RoleMappingRuleStructRepresents an Identity Pool Role Attachment role mapping rule.
UserPoolAuthenticationProviderClassDefines a User Pool Authentication Provider.
UserPoolAuthenticationProviderBindConfigStructRepresents a UserPoolAuthenticationProvider Bind Configuration.
UserPoolAuthenticationProviderBindOptionsStructRepresents UserPoolAuthenticationProvider Bind Options.
UserPoolAuthenticationProviderPropsStructProps for the User Pool Authentication Provider.