Cognito with MFA and Flutter -> Flow

Viewed 419

I am trying to log into AWS Cognito and have configured the user pool to have MFA via email. I have it 99% working, but am experiencing a weird error at the end. I am using Flutter and the amazon_cognito_identity_dart_2 flutter package. My users are created by an admin and users are not allowed to sign up in the app itself. My flow goes like such:

//global var
final userPool = new CognitoUserPool(
    CognitoConstants.poolID,
    CognitoConstants.appClientID,
  );
...
///in login function
final authDetails = new AuthenticationDetails(
      username: email,
      password: password,
    );
final cognitoUser = new CognitoUser(email, userPool);
try {
      session = await cognitoUser.authenticateUser(authDetails);
    } catch (e) {}

The above try catches a CognitoUserNewPasswordRequiredException exception the first time the user logs in because they must change their password as a temp password was mailed to them on account creation. So then I call the below function to reset the password:

try {
      session = await user.sendNewPasswordRequiredAnswer(newPassword);
    } catch (e) {}

The above throws a CognitoUserMfaSetupException exception because MFA is enabled but the device is not known. However, this password definitely works and I can log in (but not proceed). So now I am kind of stuck on what to do. I have tried a few different things, but none seem to work. Here is what I have tried and am the closest:

user.resendConfirmationCode(); //sends code to email
///await modal to grab MFA response and store it in token variable.
try {
   print('Username: ${user.username}');
   session = await user.sendMFACode(token, 'SOFTWARE_TOKEN_MFA');
} catch (e) {}

The above try/catch always catches an error and says "CognitoClientException{statusCode: 400, code: CodeMismatchException, name: CodeMismatchException, message: Invalid code or auth state for the user.}" However, I know the code is correct, so it must be the auth state of the user. But how can I ensure the auth state is good here? I think I am missing another step, and have tried the documents in: https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-create-user-accounts.html and also all the examples in the pub.dev package, but none seem that great for dealing with MFA. If I print the user.username out, as in this example above, the email is in fact printed out so it knows the details on the user. Any ideas? Thanks in advance!

0 Answers
Related