【问题标题】:How to switch IAM roles for AWS Cognito User belonging to multiple User Pool groups?如何为属于多个用户池组的 AWS Cognito 用户切换 IAM 角色?
【发布时间】:2020-05-27 21:40:39
【问题描述】:

我有一个使用 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);
  });

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

我需要做什么才能让它工作?

【问题讨论】:

    标签: javascript amazon-web-services amazon-cognito amazon-iam aws-amplify


    【解决方案1】:

    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;
        });
    }
    

    【讨论】:

    • 您如何利用此输出,以便新的 JWT 成为任何 AWS 将发送的内容?
    猜你喜欢
    • 2021-10-28
    • 2021-08-11
    • 2019-10-06
    • 2019-08-15
    • 2018-09-08
    • 2018-03-25
    • 2019-05-10
    • 2020-09-19
    • 2021-05-30
    相关资源
    最近更新 更多