4

I'm having a hard time figuring out how to use this library: https://github.com/aws-amplify/amplify-js/tree/master/packages/amazon-cognito-identity-js

where it says Use case 27. Selecting the MFA method and authenticating using TOTP.

I have already successfully got username & password login done and SMS code done but I am unable to get the secret token given in the associateSecretCode function to be scanned using google authenticator qr scanner. Keeps giving me an invalid code error

Here's my code:

cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function(result) {
    const accessToken = result.getAccessToken().getJwtToken();
    cognitoUser.associateSoftwareToken(this);
  },

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

  mfaSetup: function(challengeName, challengeParameters) {
    console.log("MFA SETUP");
    cognitoUser.associateSoftwareToken(this);
  },

  associateSecretCode: async secretCode => {
    console.log("SECRET CODE: ", secretCode);
    await this.setState({ QRCode: secretCode, showQRCode: true });
    setTimeout(() => {
      const challengeAnswer = prompt("Please input the TOTP code.", "");
      cognitoUser.verifySoftwareToken(challengeAnswer, "My TOTP device", {
        onSuccess: session => console.log("SUCCESS TOTP: ", session),
        onFailure: err => console.error("ERROR TOTP: ", err)
      });
    }, 2000);
  },

  selectMFAType: function(challengeName, challengeParameters) {
    var mfaType = prompt("Please select the MFA method.", ""); // valid values for mfaType is "SMS_MFA", "SOFTWARE_TOKEN_MFA"
    cognitoUser.sendMFASelectionAnswer(mfaType, this);
  },

  totpRequired: function(secretCode) {
    var challengeAnswer = prompt("Please input the TOTP code.", "");
    cognitoUser.sendMFACode(challengeAnswer, this, "SOFTWARE_TOKEN_MFA");
  },

  mfaRequired: function(codeDeliveryDetails) {
    var verificationCode = prompt("Please input verification code", "");
    cognitoUser.sendMFACode(verificationCode, this);
  },
  newPasswordRequired: userAttributes => {
    this.setState({
      user: userAttributes,
      showNewPassword: true
    });
  }
});

The QR code gets generated but when scanning it, google authenticator gives me this error: enter image description here

What am I doing wrong here?

Johhan Santana
  • 2,336
  • 5
  • 33
  • 61

1 Answers1

3

You need to format the qr code for google authenticator. See here: https://github.com/google/google-authenticator/wiki/Key-Uri-Format

Try using this npm library to generate the proper format: https://www.npmjs.com/package/otpauth