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

Chr*_*ian 3 javascript amazon-web-services amazon-iam amazon-cognito aws-amplify

我有一个使用 AWS Amplify 和 Cognito 构建的 Web 应用程序,用于身份验证/授权。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);
  });
Run Code Online (Sandbox Code Playgroud)

调用上述代码时,它会失败并出现 NotAuthorizedException:禁止访问身份“some_identity”。

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

Chr*_*ian 5

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

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;
    });
}
Run Code Online (Sandbox Code Playgroud)