簡體   English   中英

如何為屬於多個用戶池組的 AWS Cognito 用戶切換 IAM 角色?

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

我有一個使用 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: Access to Identity '`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;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM