AWS Cognito Identity Pool with attached IAM Roles in CloudFormation

Here’s a quick note on how to create an AWS::Cognito::IdentityPool with attached AWS::IAM::Role for Authenticated and Unauthenticated users, which are attached to the Identity Pool using AWS::Cognito::IdentityPoolRoleAttachment

---

Description: Cognito Identity Pool & Attached IAM Roles
AWSTemplateFormatVersion: '2010-09-09'

Resources:
  IdentityPool:
    Type: AWS::Cognito::IdentityPool
    Properties:
      AllowUnauthenticatedIdentities: True
      IdentityPoolName: cloudright_test

  IdentityPoolAuthenticatedIamRole:
    DependsOn: IdentityPool
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Federated: cognito-identity.amazonaws.com
          Action: sts:AssumeRoleWithWebIdentity
          Condition:
            StringEquals:
              cognito-identity.amazonaws.com:aud:
                Ref: IdentityPool
            ForAnyValue:StringLike:
              cognito-identity.amazonaws.com:amr: authenticated
      Policies:
      - PolicyName: IdentityPoolAuthenticatedUser
        PolicyDocument:
          Version: '2012-10-17'
          Statement:
          - Effect: Allow
            Action:
            - cognito-identity:*
            Resource:
            - "*"

  IdentityPoolUnauthenticatedIamRole:
    DependsOn: IdentityPool
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Federated: cognito-identity.amazonaws.com
          Action: sts:AssumeRoleWithWebIdentity
          Condition:
            StringEquals:
              cognito-identity.amazonaws.com:aud:
                Ref: IdentityPool
            ForAnyValue:StringLike:
              cognito-identity.amazonaws.com:amr: unauthenticated

  IdentityPoolAttachment:
    DependsOn:
      - IdentityPool
      - IdentityPoolAuthenticatedIamRole
      - IdentityPoolUnauthenticatedIamRole
    Type: AWS::Cognito::IdentityPoolRoleAttachment
    Properties:
      IdentityPoolId:
        Ref: IdentityPool
      Roles:
        authenticated:
          !GetAtt IdentityPoolAuthenticatedIamRole.Arn
        unauthenticated:
          !GetAtt IdentityPoolUnauthenticatedIamRole.Arn

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.