beewest
beewest

Reputation: 4846

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 Identity pool cognito-identity-pool1:

IAM:

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

Upvotes: 4

Views: 4629

Answers (1)

beewest
beewest

Reputation: 4846

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

Upvotes: 5

Related Questions