Amazon Cognito Identity Pools: Temporary AWS Credentials, Federation, IAM Roles and Fine-Grained Access

AWS Developer Associate 45 min min read Updated: Nov 17, 2026 Advanced
Amazon Cognito Identity Pools: Temporary AWS Credentials, Federation, IAM Roles and Fine-Grained Access
Advanced Topic 2 of 3

The Problem It Solves

A mobile or browser app wants to upload a photo straight to S3 or read its own DynamoDB items. You must not embed AWS access keys in the app. An identity pool gives each signed-in user short-lived credentials tied to an IAM role you control.

text 1. User signs in with Cognito user pool (or Google, Apple, SAML, OIDC) → gets a token 2. App sends the token to the Cognito Identity Pool 3. Identity pool calls AWS STS and returns temporary credentials (AccessKeyId, SecretKey, SessionToken) 4. App calls S3 / DynamoDB / other services directly with those credentials, limited by the IAM role

Authenticated and Unauthenticated Roles

RoleForTypical permissions
Authenticated roleUsers who signed in through a trusted providerRead/write their own S3 prefix and DynamoDB items
Unauthenticated (guest) roleVisitors with no sign-in (optional, off by default)Very limited: read public content, send anonymous analytics
  • Both roles have a trust policy for cognito-identity.amazonaws.com with conditions on the identity pool id and amr (authenticated or unauthenticated)
  • You can use **rules or token claims (groups, cognito:preferred_role)** to choose different roles for admins and normal users
json { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"Federated": "cognito-identity.amazonaws.com"}, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": {"cognito-identity.amazonaws.com:aud": "ap-south-1:11111111-2222-3333-4444-555555555555"}, "ForAnyValue:StringLike": {"cognito-identity.amazonaws.com:amr": "authenticated"} } }] }

Fine-Grained Access with Policy Variables

One policy can give each user access only to their own data by using the identity id variable.

json { "Version": "2012-10-17", "Statement": [ {"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], "Resource": "arn:aws:s3:::my-app-private/${cognito-identity.amazonaws.com:sub}/*"}, {"Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::my-app-private", "Condition": {"StringLike": {"s3:prefix": "${cognito-identity.amazonaws.com:sub}/*"}}}, {"Effect": "Allow", "Action": ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:UpdateItem", "dynamodb:DeleteItem"], "Resource": "arn:aws:dynamodb:ap-south-1:111111111111:table/Notes", "Condition": {"ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["${cognito-identity.amazonaws.com:sub}"]}}} ] }
  • ${cognito-identity.amazonaws.com:sub} is the user's identity id (a value like ap-south-1:uuid)
  • S3: each user only sees my-app-private/IDENTITY_ID/...
  • DynamoDB: dynamodb:LeadingKeys forces the partition key to equal the identity id, so users can touch only their own rows

Using It in Code

javascript import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers"; import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; const region = "ap-south-1"; const userPoolId = "ap-south-1_AbCdEfGhI"; const idToken = "..."; // from the user pool sign-in const credentials = fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region }), identityPoolId: "ap-south-1:11111111-2222-3333-4444-555555555555", logins: { [`cognito-idp.${region}.amazonaws.com/${userPoolId}`]: idToken }, }); const s3 = new S3Client({ region, credentials }); await s3.send(new PutObjectCommand({ Bucket: "my-app-private", Key: "ap-south-1:xxxx/photo.jpg", Body: file }));
python ci = boto3.client("cognito-identity", region_name="ap-south-1") ident = ci.get_id(IdentityPoolId=POOL, Logins={f"cognito-idp.ap-south-1.amazonaws.com/{USER_POOL}": id_token}) creds = ci.get_credentials_for_identity(IdentityId=ident["IdentityId"], Logins={f"cognito-idp.ap-south-1.amazonaws.com/{USER_POOL}": id_token})["Credentials"] # creds: AccessKeyId, SecretKey, SessionToken, Expiration (about 1 hour)

Supported Identity Providers

  • Cognito user pools
  • OIDC providers and SAML providers
  • Social: Google, Facebook, Apple, Amazon
  • Developer authenticated identities (your own backend vouches for the user)

Enhanced (Simplified) vs Basic Flow

FlowStepsNote
Enhanced (recommended)GetId then GetCredentialsForIdentity. Cognito assumes the role for youSimpler and more secure. Role choice stays in Cognito
Basic (classic)GetId, GetOpenIdToken, then your app calls AssumeRoleWithWebIdentity itselfMore control, you can choose the role and session policy

User Pool vs Identity Pool Summary

User poolIdentity pool
PurposeAuthentication (sign-up and sign-in)Authorization to AWS resources
OutputJWT tokensTemporary AWS credentials
Used withAPI Gateway authorizers, your own APIsS3, DynamoDB, IoT, AppSync with IAM, direct SDK calls
Needs the other?No, can work aloneOften uses a user pool as a login provider

Security Best Practices

  • Keep permissions minimal. These credentials live in the client, so assume a user can call any allowed API directly and write policies for that
  • Use per-user prefixes and leading keys
  • Disable the guest role unless you really need it
  • Prefer API Gateway + Lambda with token validation when the backend must apply business rules (validation, quotas, auditing)
  • For uploads, prefer presigned URLs created by your backend when you need size and type checks

Practice Tasks

  1. Create an identity pool with a user pool as provider and set an authenticated role
  2. Write the per-user S3 prefix policy and test that user A cannot read user B files
  3. Upload a file from a small web page with the SDK and the Cognito credentials
  4. Compare the same upload through a presigned URL
  5. Remove permissions and observe the AccessDenied message

Conclusion

Identity pools exchange tokens from user pools, social or SAML providers for temporary AWS credentials with authenticated and guest roles. Use IAM policy variables and LeadingKeys for per-user isolation, prefer the enhanced flow, keep roles minimal, and use a backend when business logic is needed.

Quick Summary: problem; flow; roles; policy variables; code; providers; flows; summary; best practices.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators