关于 c#:Assume IAM 角色来自 Cognito 组

Assume IAM role from Cognito group

是否可以假设 IAM 角色 iam-role1 链接到 Cognito 用户池 cognito-user-pool1 中 cognito 用户 cognito-user1 的 Cognito 组 cognito-group1

我的配置:

Cognito 用户池 cognito-user-pool1:

  • Cognito 用户 cognito-user1 属于 cognito-group1
  • Cognito 组 cognito-group1 已分配给 iam-role1

Cognito 身份池 cognito-identity-pool1:

  • 身份验证提供程序:cognito-user-pool1
  • 认证角色 = iam-role1

IAM:

  • IAM 角色 iam-role1 具有访问 S3 只读的策略

此代码允许我向 Cognito 用户池进行身份验证:

1
2
3
4
5
6
7
8
9
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);

然后从连接到 cognito 用户池 cognito-user-pool1 的 cognito 身份池 cognito-identity-pool1 获取凭据:

1
2
3
CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials("identity-pool-arn", RegionEndpoint.USEast1);
using (var client = new AmazonS3Client(credentials))
...

当用户通过 Cognito 用户池 cognito-user-pool1 进行身份验证时,id 令牌包括 cognito 组和 iam 角色:

1
2
3
4
5
6
"cognito:groups": [
   "cognito-group1"
  ],
"cognito:roles": [
   "arn:aws:iam::xxx:role/iam-role1"
  ],

我们需要配置 Cognito 身份池以在用户通过身份验证时从令牌中选择角色:
enter

1
2
3
4
5
6
7
8
9
10
11
12
13
{
 "Version":"2012-10-17",
 "Statement": [
    ...
    {
     "Effect":"Allow",
     "Principal": {
       "Federated":"cognito-identity.amazonaws.com"
      },
     "Action":"sts:AssumeRoleWithWebIdentity"
    }
  ]
}

enter