Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assume IAM role from Cognito group

Is it possible to assume the IAM role iam-role1 linked to Cognito group cognito-group1 of cognito user cognito-user1 in Cognito User Pool cognito-user-pool1?

My configuration:

Cognito User pool cognito-user-pool1:

  • Cognito user cognito-user1 belongs to cognito-group1
  • Cognito group cognito-group1 has assigned to iam-role1 .

Cognito Identity pool cognito-identity-pool1:

  • Authentication providers: cognito-user-pool1
  • authenticated role = iam-role1

IAM:

  • IAM role iam-role1 has policy to access S3 ReadOnly

This code allows me to authenticate to Cognito User Pool:

AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient();
            CognitoUserPool userPool = new CognitoUserPool("user-pool-id", "client-id", provider);
            CognitoUser user = new CognitoUser("cognito-user1", "client-id", userPool, provider);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = "cognito-password1"
            };

            AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest);

Then get the credentials from cognito identity pool cognito-identity-pool1 linked to cognito user pool cognito-user-pool1:

CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials("identity-pool-arn", RegionEndpoint.USEast1); 
using (var client = new AmazonS3Client(credentials))
...
like image 255
beewest Avatar asked Sep 16 '25 07:09

beewest


1 Answers

When a user is authenticated with Cognito User Pool cognito-user-pool1, the id token includes cognito groups and iam roles:

"cognito:groups": [
    "cognito-group1"
  ],
"cognito:roles": [
    "arn:aws:iam::xxx:role/iam-role1"
  ],

We need configure Cognito Identity Pool to choose role from token when user is authenticated: enter image description here

We also need to allow Cognito Identity Pool to assume this role by editing trust relationship in IAM role iam-role1:

{
  "Version": "2012-10-17",
  "Statement": [
    ...
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity"
    }
  ]
}

enter image description here

like image 55
beewest Avatar answered Sep 19 '25 09:09

beewest