AWS cognito:getCredentials无法正常工作

时间:2018-06-02 10:17:12

标签: node.js amazon-web-services amazon-cognito federated-identity

我正在学习使用AWS Cognito。我已经设置了一个用户池和一个身份池。

代码(简化):

cognitoUser.authenticateUser(authenticationDetails, {
      onSuccess: (result) => {
        let cognitoGetUser = userPool.getCurrentUser();
        if (cognitoGetUser != null) {
          cognitoGetUser.getSession((err, result) => {
            if (result) {
              console.log ("Authenticated to Cognito User and Identity Pools!");
              let token = result.getIdToken().getJwtToken();
              let cognitoParams = {
                IdentityPoolId: this.identityPool,
                Logins: {}
              };
              cognitoParams.Logins["cognito-idp.eu-west-1.amazonaws.com/"+this.poolData.UserPoolId] = token;
              AWS.config.credentials = new AWS.CognitoIdentityCredentials(cognitoParams);

              AWS.config.getCredentials(() => {
                  console.log(AWS.config.credentials.accessKeyId)
                  console.log(AWS.config.credentials.secretAccessKey)
                  console.log(AWS.config.credentials.sessionToken)  
              }
            }
          }
        }
      },
      onFailure: function(err) {
        console.log('error');
        console.log(err)
      }
    }
  }

大多数代码按预期工作:authenticateUser触发onSuccess,我可以看到jwt令牌等

问题:我无法让AWS.config.getCredentials工作。它执行时没有任何错误,但accessKeyIdsecretAccessKeySessionToken都是undefined

对我做错的任何建议?

1 个答案:

答案 0 :(得分:1)

  

我无法使AWS.config.getCredentials工作。 执行时没有任何错误,但是,

这可能是一个错误的假设。您的缩写代码缺少几个右括号,但在没有任何有意义的调整的情况下运行正常。

调用getCredentials时,会通过error对象“静默”报告任何错误。我认为你会在某处看到400响应(网络选项卡或控制台或两者),但getCredentials()并不真正以可见的方式报告错误。

要查看出现了什么问题,您应该在传递给getCredentials()的回调中添加一个参数:

AWS.config.getCredentials((err) => {
    if (err) {
        console.log(err);
    } else {
        console.log(AWS.config.credentials.accessKeyId)
        console.log(AWS.config.credentials.secretAccessKey)
        console.log(AWS.config.credentials.sessionToken)
    }
});

作为参考,一个常见的错误对象如下所示。请注意,有用的消息位于originalError.message

{
    "message": "Could not load credentials from CognitoIdentityCredentials",
    "code": "CredentialsError",
    "time": "2018-06-03T15:19:02.078Z",
    "requestId": "71b03b4a-6741-11e8-98af-b70a114474f8",
    "statusCode": 400,
    "retryable": false,
    "retryDelay": 94.28032122526344,
    "originalError": {
        "message": "Invalid login token. Issuer doesn't match providerName",
        "code": "NotAuthorizedException",
        "time": "2018-06-03T15:19:02.078Z",
        "requestId": "71b03b4a-6741-11e8-98af-b70a114474f8",
        "statusCode": 400,
        "retryable": false,
        "retryDelay": 94.28032122526344
    }
}

“网络”标签中的相应400包含此响应:

{"__type":"NotAuthorizedException","message":"Invalid login token. Issuer doesn't match providerName"}