如何使用身份令牌获取AWS的临时凭证?

时间:2018-08-17 18:04:18

标签: amazon-cognito aws-cognito

用例:我想使用联合标识来限制对我的API网关路径的访问。

为此,我需要使用我的ID令牌获取AWS临时凭证。我获得了我的Id令牌,但我不知道如何使用Id令牌获得临时证书。

这是将ID令牌传递到认知凭证映射

  var data = {
      UserPoolId: config.cognito.USER_POOL_ID,
      ClientId: config.cognito.APP_CLIENT_ID,
    };
    var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
    var cognitoUser = userPool.getCurrentUser();
    if (cognitoUser != null) {
      cognitoUser.getSession(function(err, result) {
          if (result) {
              console.log('You are now logged in.');

              // Add the User's Id Token to the Cognito credentials login map.
              AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                  IdentityPoolId: config.cognito.IDENTITY_POOL_ID,
                  Logins: {
                    'cognito-idp.ap-south-1.amazonaws.com/ap-south-1_G7YbVxxxx': result.getIdToken().getJwtToken()
                  }
              });
          }
      });
  }

如何获取临时凭证?

谢谢

1 个答案:

答案 0 :(得分:0)

使用以下代码段获取临时凭据

 AWS.config.credentials.get(function(err,data) {
      if (!err) {
        var id = AWS.config.credentials.identityId;
        var key = AWS.config.credentials.accessKeyId;
        var secretkey = AWS.config.credentials.secretAccessKey;
        var sessionToken = AWS.config.credentials.sessionToken;
        console.log('Cognito Identity ID '+ id);
        console.log('Cognito Key '+ key);
        console.log('Cognito Secret Key '+ secretkey);
        console.log('Cognito SessionToken '+ sessionToken);
      }
    });