如何为属于多个用户池组的 AWS Cognito 用户切换 IAM 角色?

How to switch IAM roles for AWS Cognito User belonging to multiple User Pool groups?

我有一个使用 AWS Amplify 和 Cognito 构建的 Web 应用程序用于 authentication/authorization。 Cognito 用户池是身份提供者。

根据用户应具有的权限将用户分组到 Cognito 用户池组中。

我希望一些用户成为多个组(例如管理员用户)的一部分,这些组应该具有这些用户的总和 组的权限。但由于用户只能承担一个角色,我需要能够在应用程序中切换角色。

我尝试使用 getCredentialsForIdentity 完成此操作:

  const cognito_identity = new AWS.CognitoIdentity({ apiVersion: '2014-06-30', region: 'eu-central-1' });
  var params = {
    IdentityId: 'some_identity',
    CustomRoleArn: 'arn:aws:iam::<account_id>:role/editors',
  };
  cognito_identity.getCredentialsForIdentity(params, function(err, data) {
    if (err) console.log(err, err.stack);
    else     console.log(data);
  });

当调用上面的代码时,它失败了 NotAuthorizedException:禁止访问身份“some_identity”。

我需要做什么才能让它发挥作用?

getCredentialsForIdentity 的参数中包含 Logins 属性 后,它起作用了:

async function switchRoles(region, identityId, roleArn, cognitoArn) {
  const user = await Auth.currentUserPoolUser();
  const cognitoidentity = new AWS.CognitoIdentity({ apiVersion: '2014-06-30', region });
  const params = {
    IdentityId: identityId,
    CustomRoleArn: roleArn,
    Logins: {
      [cognitoArn]: user
        .getSignInUserSession()
        .getIdToken()
        .getJwtToken(),
    },
  };
  return cognitoidentity
    .getCredentialsForIdentity(params)
    .promise()
    .then(data => {
      return {
        accessKeyId: data.Credentials.AccessKeyId,
        sessionToken: data.Credentials.SessionToken,
        secretAccessKey: data.Credentials.SecretKey,
        expireTime: data.Credentials.Expiration,
        expired: false,
      };
    })
    .catch(err => {
      console.log(err, err.stack);
      return null;
    });
}