Amplify-js: cognitoUser.authenticateUser() -> Unknown error, the response body from fetch is: undefined

Created on 2 Sep 2018  路  6Comments  路  Source: aws-amplify/amplify-js

Do you want to request a feature or report a bug?
BUG

What is the current behavior?
When trying to loggin with the amazon-cognito-identity.js API, using the autenticateUser() function form the CognitoUser class, I receive the following error

`Unknown error, the response body from fetch is: undefined`

When setting a breakpoint in the onFailure event, and checking the trace, you can see 2 calls done to the cognito-idp endpoint. The response is empty in this moment, but after releasing the breakpoint and checking the calls again you can see the response body, with the tokens and all the information I need. But due to this error, the onSuccess event doesn't execute.

Here my code

userSignIn(email, password) {
    var username = email.split("@")[0]
    var userPool = this.getUserPool();
    var authenticationData = {
      Username: username,
      Password: password,
    };
    var authenticationDetails = new AuthenticationDetails(authenticationData);

    var userData = {
      Username: username,
      Pool: userPool
    };
    var cognitoUser = new CognitoUser(userData);

    cognitoUser.authenticateUser(authenticationDetails, {
      onSuccess: function (result) {
        var accessToken = result.getAccessToken().getJwtToken();

        //POTENTIAL: Region needs to be set if not already set previously elsewhere.
        AWS.config.region = this.getRegion();

        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
          IdentityPoolId: this.getIdentityPoolId(), // your identity pool id here
          Logins: {
            // Change the key below according to the specific region your user pool is in.
            [this.getCognitoIdpEndpoint()]: result.getIdToken().getJwtToken()
          }
        });

        console.log(AWS.config.credentials);
        debugger;

        // //refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
        // AWS.config.credentials.refresh((error) => {
        //   if (error) {
        //     console.error(error);
        //   } else {
        //     // Instantiate aws sdk service objects now that the credentials have been updated.
        //     // example: var s3 = new AWS.S3();
        //     console.log('Successfully logged!');
        //   }
        // });
      },

      onFailure: function (err) {
        debugger
        alert(err.message || JSON.stringify(err));
      }

    });
  }

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than AWS Amplify.

What is the expected behavior?
request should be successful, returning the tokens and firing the "onSuccess" event

Which versions of Amplify, and which browser / OS are affected by this issue? Did this work in previous versions?
Using: "amazon-cognito-identity-js": "^2.0.23"
Browser: Chrome 68.0.3440.106
OS: Same error on Win10 and mac OSX

You can turn on the debug mode to provide more info for us by setting window.LOG_LEVEL = 'DEBUG'; in your app.

Auth Cognito bug

Most helpful comment

All right I found the problem. I didn't pass the 'this' context to the 'onSuccess' event, so it failed when doing this.getRegion().

However, instead of trowin the "getRegion is not defined" error, it falls back to a previous catch() in Client.js file line 75, which forces the error to be "Unknown error, the response body from fetch is: undefined".

Please, you need to improve this error handling, as it makes debugging a imposible task. At least print the original error in the console before forcing a new error message. Or even better, check only for a set of errors you know and if it's none of them, just console.error() the error and stop the execution.

https://github.com/aws-amplify/amplify-js/blob/05cbe5913d3f8583ac5dfeab514f0f1af2e3c012/packages/amazon-cognito-identity-js/es/Client.js#L74

All 6 comments

All right I found the problem. I didn't pass the 'this' context to the 'onSuccess' event, so it failed when doing this.getRegion().

However, instead of trowin the "getRegion is not defined" error, it falls back to a previous catch() in Client.js file line 75, which forces the error to be "Unknown error, the response body from fetch is: undefined".

Please, you need to improve this error handling, as it makes debugging a imposible task. At least print the original error in the console before forcing a new error message. Or even better, check only for a set of errors you know and if it's none of them, just console.error() the error and stop the execution.

https://github.com/aws-amplify/amplify-js/blob/05cbe5913d3f8583ac5dfeab514f0f1af2e3c012/packages/amazon-cognito-identity-js/es/Client.js#L74

I search everywhere for help on this same error and rafachurre's comment helped me the most. Here is exactly how I had to pass 'this' into the cognitoUser.authenticateUser method to be able to change state after successful login.

This was the critical line for me (inside the button component):
clicked={this.loginHandler.bind(this, this)}

and the following lines in the authenticateUser method:

loginHandler (self) {
 var poolData = { UserPoolId  : UserPoolId,
ClientId : ClientId
};

var authenticationData = {
        Username : username,
        Password : password,
    };

    var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);

    var userData = {
        Username : username,
        Pool : userPool
    };
    var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);

cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
            var accessToken = result.getAccessToken().getJwtToken();

            /* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer*/
            var idToken = result.idToken.jwtToken;
            console.log('Success');
            self.setState({ isLoggedIn: true });
        },

All right I found the problem. I didn't pass the 'this' context to the 'onSuccess' event, so it failed when doing this.getRegion().

However, instead of trowin the "getRegion is not defined" error, it falls back to a previous catch() in Client.js file line 75, which forces the error to be "Unknown error, the response body from fetch is: undefined".

Please, you need to improve this error handling, as it makes debugging a imposible task. At least print the original error in the console before forcing a new error message. Or even better, check only for a set of errors you know and if it's none of them, just console.error() the error and stop the execution.

amplify-js/packages/amazon-cognito-identity-js/es/Client.js

Line 74 in 05cbe59

var error = { code: 'UnknownError', message: 'Unknown error' };

Could you please be more specific about how you fixed the error? How would you pass 'this' into the callback?

thanks

Closing the issue as you will no longer receive unknown error in the latest version.

All right I found the problem. I didn't pass the 'this' context to the 'onSuccess' event, so it failed when doing this.getRegion().
However, instead of trowin the "getRegion is not defined" error, it falls back to a previous catch() in Client.js file line 75, which forces the error to be "Unknown error, the response body from fetch is: undefined".
Please, you need to improve this error handling, as it makes debugging a imposible task. At least print the original error in the console before forcing a new error message. Or even better, check only for a set of errors you know and if it's none of them, just console.error() the error and stop the execution.
amplify-js/packages/amazon-cognito-identity-js/es/Client.js
Line 74 in 05cbe59
var error = { code: 'UnknownError', message: 'Unknown error' };

Could you please be more specific about how you fixed the error? How would you pass 'this' into the callback?

thanks

Did you get the answer @ToddHoff

Did you get the answer @ToddHoff

Ironically on a new project I found myself right back here with the same error. This time the error was generated when logging in for a user that doesn't exist. The other problem was a while ago. I think i got rid of it by using self as in:

async login(email, password) {

  this.authenticate_data = {
     Username : email,
     Password : password
  };

  this.authentication_details = new AmazonCognitoIdentity.AuthenticationDetails(this.authenticate_data);

  this.user_data = {
     Username : email,
     Pool     : this.user_pool
  }; 

  this.cognito_user = new AmazonCognitoIdentity.CognitoUser(this.user_data);

  var self = this;

     self.cognito_user.authenticateUser(self.authentication_details, {

        onSuccess: function (result) {
           console.log("login:success:result:", result);

           self.access_token  = result.getAccessToken().getJwtToken();
           self.refresh_token = result.getRefreshToken().getToken();
           self.id_token      = result.getIdToken().getJwtToken();

           resolve(null);
        },

        onFailure: function(error) {
           console.log("login:error:", error);
           reject(error);
        }
     })
  })

One of the comments mentions a fix, but the new stuff has moved so much towards amplify I can't readily see how to integrate it back into my project.

Was this page helpful?
0 / 5 - 0 ratings