Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.6.0+

Amazon Cognito: Enroll an Authenticator for TOTP MFA

See more Amazon Cognito Examples

Enable software-token MFA in the pool first. Choose mode=signed_in to enroll with a user access token containing aws.cognito.signin.user.admin, or mode=challenge to continue the MFA_SETUP saved by the sign-in example. Begin obtains a secret and saves it in private cognito-totp.json. Present secret_code securely to the user for manual entry or an otpauth QR code; never place it in ordinary logs. Then set action=verify with the authenticator's code in private totp-input.json.

Checks VerifySoftwareToken.Status=SUCCESS before activating the preference or finishing sign-in. A signed-in enrollment sets SoftwareTokenMfaSettings.Enabled and PreferredMfa. Challenge enrollment uses the successive Session values from AssociateSoftwareToken and VerifySoftwareToken, then RespondToAuthChallenge(MFA_SETUP). Verifying a replacement authenticator can disassociate the old one. If a later step fails after successful verification, inspect the user's MFA/sign-in state rather than repeatedly beginning enrollment.

Uses direct Chilkat.Http requests to the regional Cognito User Pools JSON API. Public app-client operations do not use IAM signing. These examples use a public app client without a client secret; do not add administrative AWS credentials. For a confidential app client, implement the operation-specific SecretHash/SECRET_HASH or ClientSecret requirements on a trusted system.

Create qa_data/cognito/app.json with string fields region (for example us-west-2), user_pool_id, client_id, and account_key (your local account identifier). OAuth examples also require domain, the trusted HTTPS base URL of your Cognito domain, without a trailing slash. The region and user pool must match the app client. These examples use commercial AWS endpoints.

Sample cache/input files contain secrets. Use an access-controlled directory outside web content and source control, separate each local user/account, and serialize operations that modify the same cache. In a real application obtain passwords and codes through private UI instead of leaving them in files. Cache writes retain a .bak copy; protect and remove obsolete backups and challenge files after the flow. Production storage should provide atomic replacement and OS-backed secret protection. Never restore an old refresh token automatically after rotation. These examples do not require a hosted web server.

Checks transport completion, HTTP status, and required response fields before using results. Cognito often reports throttling, invalid codes, and authentication failures as HTTP 400. Present generic sign-in/recovery errors to users; keep detailed diagnostics private. Retry throttled reads with bounded backoff, but reconcile uncertain writes and refresh rotations before repeating them.

AWS documentation 1 | AWS documentation 2 | AWS documentation 3

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  success = false;
  // App settings are trusted configuration. Keep a separate account_key/cache per local user.
  final app = CkJsonObject();
  app.strict = true;
  try {
    app.loadFile('qa_data/cognito/app.json');
  } on ChilkatException {
    print('Could not load Cognito app settings.');
    return;
  }

  if ((app.jsonTypeOf('region') != 1) || (app.stringOf('region') == '')) {
    print('Missing or invalid region.');
    return;
  }

  if ((app.jsonTypeOf('user_pool_id') != 1) || (app.stringOf('user_pool_id') == '')) {
    print('Missing or invalid user_pool_id.');
    return;
  }

  if ((app.jsonTypeOf('client_id') != 1) || (app.stringOf('client_id') == '')) {
    print('Missing or invalid client_id.');
    return;
  }

  if ((app.jsonTypeOf('account_key') != 1) || (app.stringOf('account_key') == '')) {
    print('Missing or invalid account_key.');
    return;
  }

  final clientId = app.stringOf('client_id');
  final endpoint = CkStringBuilder();
  endpoint.append('https://cognito-idp.');
  endpoint.append(app.stringOf('region'));
  endpoint.append('.amazonaws.com/');
  final http = CkHttp();
  http.requireSslCertVerify = true;
  http.followRedirects = false;
  http.connectTimeout = 20;
  http.readTimeout = 60;
  final resp = CkHttpResponse();
  final body = CkJsonObject();
  final result = CkJsonObject();
  result.strict = true;
  final action = 'begin';
  final mode = 'signed_in';
  if ((action != 'begin') && (action != 'verify')) {
    print('Choose begin or verify.');
    return;
  }

  if ((mode != 'signed_in') && (mode != 'challenge')) {
    print('Choose signed_in or challenge.');
    return;
  }

  var username = '';
  final credential = CkJsonObject();
  if (mode == 'signed_in') {
    try {
      credential.loadFile('qa_data/tokens/cognito-user.json');
    } on ChilkatException {
      print('Could not load user tokens.');
      return;
    }

    if ((credential.jsonTypeOf('client_id') != 1) || (credential.stringOf('client_id') == '')) {
      print('Missing or invalid client_id.');
      return;
    }

    if (credential.stringOf('client_id') != app.stringOf('client_id')) {
      print('Saved data belongs to another client, pool, or local account.');
      return;
    }

    if ((credential.jsonTypeOf('user_pool_id') != 1) || (credential.stringOf('user_pool_id') == '')) {
      print('Missing or invalid user_pool_id.');
      return;
    }

    if (credential.stringOf('user_pool_id') != app.stringOf('user_pool_id')) {
      print('Saved data belongs to another client, pool, or local account.');
      return;
    }

    if ((credential.jsonTypeOf('account_key') != 1) || (credential.stringOf('account_key') == '')) {
      print('Missing or invalid account_key.');
      return;
    }

    if (credential.stringOf('account_key') != app.stringOf('account_key')) {
      print('Saved data belongs to another client, pool, or local account.');
      return;
    }

    if ((credential.jsonTypeOf('access_token') != 1) || (credential.stringOf('access_token') == '')) {
      print('Missing or invalid access_token.');
      return;
    }
  } else {
    try {
      credential.loadFile('qa_data/tokens/cognito-challenge.json');
    } on ChilkatException {
      print('Could not load the MFA_SETUP challenge.');
      return;
    }

    if ((credential.jsonTypeOf('client_id') != 1) || (credential.stringOf('client_id') == '')) {
      print('Missing or invalid client_id.');
      return;
    }

    if (credential.stringOf('client_id') != app.stringOf('client_id')) {
      print('Saved data belongs to another client, pool, or local account.');
      return;
    }

    if ((credential.jsonTypeOf('user_pool_id') != 1) || (credential.stringOf('user_pool_id') == '')) {
      print('Missing or invalid user_pool_id.');
      return;
    }

    if (credential.stringOf('user_pool_id') != app.stringOf('user_pool_id')) {
      print('Saved data belongs to another client, pool, or local account.');
      return;
    }

    if ((credential.jsonTypeOf('account_key') != 1) || (credential.stringOf('account_key') == '')) {
      print('Missing or invalid account_key.');
      return;
    }

    if (credential.stringOf('account_key') != app.stringOf('account_key')) {
      print('Saved data belongs to another client, pool, or local account.');
      return;
    }

    if ((credential.jsonTypeOf('Session') != 1) || (credential.stringOf('Session') == '')) {
      print('Missing or invalid Session.');
      return;
    }

    if ((credential.jsonTypeOf('username') != 1) || (credential.stringOf('username') == '')) {
      print('Missing or invalid username.');
      return;
    }

    if (credential.stringOf('ChallengeName') != 'MFA_SETUP') {
      print('Expected an MFA_SETUP challenge.');
      return;
    }

    username = credential.stringOf('username');
  }

  if (action == 'begin') {
    if (mode == 'signed_in') {
      body.updateString('AccessToken', credential.stringOf('access_token'));
    } else {
      body.updateString('Session', credential.stringOf('Session'));
    }

    http.setRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.AssociateSoftwareToken');
    success = true;
    try {
      http.httpJson('POST', endpoint.getAsString(), body, 'application/x-amz-json-1.0', resp);
    } on ChilkatException {
      success = false;
    }
    if (resp.statusCode != 200) {
      print('HTTP status: ${resp.statusCode}');
      try {
        result.load(resp.bodyStr);
        print('Error type: ${result.stringOf('__type')}');
        print('OAuth error: ${result.stringOf('error')}');
      } on ChilkatException {
        // result.load() failed; continue anyway.
      }

      // Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
      return;
    }

    if (!success) {
      print('The HTTP exchange did not complete.');
      return;
    }

    try {
      result.load(resp.bodyStr);
    } on ChilkatException {
      print('Expected a JSON response.');
      return;
    }

    if ((result.jsonTypeOf('SecretCode') != 1) || (result.stringOf('SecretCode') == '')) {
      print('Missing or invalid SecretCode.');
      return;
    }

    final newEnrollment = CkJsonObject();
    newEnrollment.updateString('secret_code', result.stringOf('SecretCode'));
    newEnrollment.updateString('mode', mode);
    newEnrollment.updateString('username', username);
    if (mode == 'challenge') {
      if ((result.jsonTypeOf('Session') != 1) || (result.stringOf('Session') == '')) {
        print('Missing or invalid Session.');
        return;
      }

      newEnrollment.updateString('session', result.stringOf('Session'));
      // Bind enrollment to this precise challenge, not just the account.
      newEnrollment.updateString('original_session', credential.stringOf('Session'));
    }

    newEnrollment.updateString('client_id', app.stringOf('client_id'));
    newEnrollment.updateString('user_pool_id', app.stringOf('user_pool_id'));
    newEnrollment.updateString('account_key', app.stringOf('account_key'));
    final newEnrollmentTOTPenrollment = CkFileAccess();
    try {
      newEnrollmentTOTPenrollment.dirEnsureExists('qa_data/tokens');
    } on ChilkatException {
      print('Could not create the private cache directory.');
      return;
    }

    if (newEnrollmentTOTPenrollment.fileExists('qa_data/tokens/cognito-totp.json')) {
      try {
        newEnrollmentTOTPenrollment.fileCopy('qa_data/tokens/cognito-totp.json', 'qa_data/tokens/cognito-totp.json.bak', false);
      } on ChilkatException {
        print('Could not back up the existing cache.');
        return;
      }
    }

    try {
      newEnrollment.writeFile('qa_data/tokens/cognito-totp.json');
    } on ChilkatException {
      print('Could not save TOTP enrollment; preserve any previous backup.');
      return;
    }

    print('Enrollment saved. Present secret_code privately in your authenticator setup UI.');
    // This secret can generate future OTPs. Never log it or email it.
    return;
  }

  final enrollment = CkJsonObject();
  enrollment.strict = true;
  try {
    enrollment.loadFile('qa_data/tokens/cognito-totp.json');
  } on ChilkatException {
    print('Could not load qa_data/tokens/cognito-totp.json.');
    return;
  }

  if ((enrollment.jsonTypeOf('client_id') != 1) || (enrollment.stringOf('client_id') == '')) {
    print('Missing or invalid client_id.');
    return;
  }

  if (enrollment.stringOf('client_id') != app.stringOf('client_id')) {
    print('Saved data belongs to another client, pool, or local account.');
    return;
  }

  if ((enrollment.jsonTypeOf('user_pool_id') != 1) || (enrollment.stringOf('user_pool_id') == '')) {
    print('Missing or invalid user_pool_id.');
    return;
  }

  if (enrollment.stringOf('user_pool_id') != app.stringOf('user_pool_id')) {
    print('Saved data belongs to another client, pool, or local account.');
    return;
  }

  if ((enrollment.jsonTypeOf('account_key') != 1) || (enrollment.stringOf('account_key') == '')) {
    print('Missing or invalid account_key.');
    return;
  }

  if (enrollment.stringOf('account_key') != app.stringOf('account_key')) {
    print('Saved data belongs to another client, pool, or local account.');
    return;
  }

  if (enrollment.stringOf('mode') != mode) {
    print('Enrollment mode mismatch.');
    return;
  }

  final input = CkJsonObject();
  input.strict = true;
  try {
    input.loadFile('qa_data/cognito/totp-input.json');
  } on ChilkatException {
    print('Could not load qa_data/cognito/totp-input.json.');
    return;
  }

  if ((input.jsonTypeOf('code') != 1) || (input.stringOf('code') == '')) {
    print('Missing or invalid code.');
    return;
  }

  // Enter a fresh six-digit code from the authenticator; preserve leading zeroes.
  body.updateString('UserCode', input.stringOf('code'));
  body.updateString('FriendlyDeviceName', 'Authenticator');
  if (mode == 'signed_in') {
    body.updateString('AccessToken', credential.stringOf('access_token'));
  } else {
    if ((enrollment.jsonTypeOf('session') != 1) || (enrollment.stringOf('session') == '')) {
      print('Missing or invalid session.');
      return;
    }

    if (enrollment.stringOf('original_session') != credential.stringOf('Session')) {
      print('Enrollment belongs to another sign-in challenge.');
      return;
    }

    body.updateString('Session', enrollment.stringOf('session'));
  }

  http.setRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.VerifySoftwareToken');
  success = true;
  try {
    http.httpJson('POST', endpoint.getAsString(), body, 'application/x-amz-json-1.0', resp);
  } on ChilkatException {
    success = false;
  }
  if (resp.statusCode != 200) {
    print('HTTP status: ${resp.statusCode}');
    try {
      result.load(resp.bodyStr);
      print('Error type: ${result.stringOf('__type')}');
      print('OAuth error: ${result.stringOf('error')}');
    } on ChilkatException {
      // result.load() failed; continue anyway.
    }

    // Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    return;
  }

  if (!success) {
    print('The HTTP exchange did not complete.');
    return;
  }

  try {
    result.load(resp.bodyStr);
  } on ChilkatException {
    print('Expected a JSON response.');
    return;
  }

  if (result.stringOf('Status') != 'SUCCESS') {
    print('Authenticator verification did not succeed; do not enable it.');
    return;
  }

  // Verification succeeded. Discard the enrollment secret and its backup.
  final removeEnrollment = CkFileAccess();
  removeEnrollment.fileDelete('qa_data/tokens/cognito-totp.json');
  if (removeEnrollment.fileExists('qa_data/tokens/cognito-totp.json.bak')) {
    removeEnrollment.fileDelete('qa_data/tokens/cognito-totp.json.bak');
  }

  try {
    body.load('{}');
  } on ChilkatException {
    print('Could not reset the request body.');
    return;
  }

  if (mode == 'signed_in') {
    body.updateString('AccessToken', credential.stringOf('access_token'));
    body.updateBool('SoftwareTokenMfaSettings.Enabled', true);
    body.updateBool('SoftwareTokenMfaSettings.PreferredMfa', true);
    http.setRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.SetUserMFAPreference');
    success = true;
    try {
      http.httpJson('POST', endpoint.getAsString(), body, 'application/x-amz-json-1.0', resp);
    } on ChilkatException {
      success = false;
    }
    if (resp.statusCode != 200) {
      print('HTTP status: ${resp.statusCode}');
      try {
        result.load(resp.bodyStr);
        print('Error type: ${result.stringOf('__type')}');
        print('OAuth error: ${result.stringOf('error')}');
      } on ChilkatException {
        // result.load() failed; continue anyway.
      }

      // Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
      return;
    }

    if (!success) {
      print('The HTTP exchange did not complete.');
      return;
    }

    print('Authenticator verified and set as the preferred MFA method.');
    return;
  }

  if ((result.jsonTypeOf('Session') != 1) || (result.stringOf('Session') == '')) {
    print('Missing or invalid Session.');
    return;
  }

  // Submit the NEW Session returned by VerifySoftwareToken, not the earlier one.
  body.updateString('ClientId', clientId);
  body.updateString('ChallengeName', 'MFA_SETUP');
  body.updateString('Session', result.stringOf('Session'));
  body.updateString('ChallengeResponses.USERNAME', username);
  http.setRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.RespondToAuthChallenge');
  success = true;
  try {
    http.httpJson('POST', endpoint.getAsString(), body, 'application/x-amz-json-1.0', resp);
  } on ChilkatException {
    success = false;
  }
  if (resp.statusCode != 200) {
    print('HTTP status: ${resp.statusCode}');
    try {
      result.load(resp.bodyStr);
      print('Error type: ${result.stringOf('__type')}');
      print('OAuth error: ${result.stringOf('error')}');
    } on ChilkatException {
      // result.load() failed; continue anyway.
    }

    // Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    return;
  }

  if (!success) {
    print('The HTTP exchange did not complete.');
    return;
  }

  try {
    result.load(resp.bodyStr);
  } on ChilkatException {
    print('Expected a JSON response.');
    return;
  }

  if (result.jsonTypeOf('AuthenticationResult') == 3) {
    final token = CkJsonObject();
    token.updateString('access_token', result.stringOf('AuthenticationResult.AccessToken'));
    token.updateString('id_token', result.stringOf('AuthenticationResult.IdToken'));
    token.updateString('token_type', result.stringOf('AuthenticationResult.TokenType'));
    token.updateInt('expires_in', result.intOf('AuthenticationResult.ExpiresIn'));
    if (result.hasMember('AuthenticationResult.RefreshToken')) {
      token.updateString('refresh_token', result.stringOf('AuthenticationResult.RefreshToken'));
    }

    if ((token.jsonTypeOf('access_token') != 1) || (token.stringOf('access_token') == '')) {
      print('Missing or invalid access_token.');
      return;
    }

    if ((token.jsonTypeOf('id_token') != 1) || (token.stringOf('id_token') == '')) {
      print('Missing or invalid id_token.');
      return;
    }

    if ((token.jsonTypeOf('expires_in') != 2) || (token.intOf('expires_in') <= 0)) {
      print('Expected a positive token lifetime.');
      return;
    }

    if (token.stringOf('token_type') != 'Bearer') {
      print('Expected Bearer tokens.');
      return;
    }

    if ((token.jsonTypeOf('refresh_token') != 1) || (token.stringOf('refresh_token') == '')) {
      print('Missing or invalid refresh_token.');
      return;
    }

    token.updateString('client_id', app.stringOf('client_id'));
    token.updateString('user_pool_id', app.stringOf('user_pool_id'));
    token.updateString('account_key', app.stringOf('account_key'));
    final obtained = CkDateTime();
    try {
      obtained.setFromCurrentSystemTime();
    } on ChilkatException {
      print('Could not get the acquisition time.');
      return;
    }

    token.updateString('obtained_at', obtained.getAsTimestamp(false));
    final tokenusertokens = CkFileAccess();
    try {
      tokenusertokens.dirEnsureExists('qa_data/tokens');
    } on ChilkatException {
      print('Could not create the private cache directory.');
      return;
    }

    if (tokenusertokens.fileExists('qa_data/tokens/cognito-user.json')) {
      try {
        tokenusertokens.fileCopy('qa_data/tokens/cognito-user.json', 'qa_data/tokens/cognito-user.json.bak', false);
      } on ChilkatException {
        print('Could not back up the existing cache.');
        return;
      }
    }

    try {
      token.writeFile('qa_data/tokens/cognito-user.json');
    } on ChilkatException {
      print('Could not save user tokens; preserve any previous backup.');
      return;
    }

    // A completed flow no longer needs its short-lived challenge session.
    final cleanup = CkFileAccess();
    if (cleanup.fileExists('qa_data/tokens/cognito-challenge.json')) {
      cleanup.fileDelete('qa_data/tokens/cognito-challenge.json');
    }

    print('Sign-in completed; private token cache saved.');
    return;
  }

  if ((result.jsonTypeOf('ChallengeName') != 1) || (result.stringOf('ChallengeName') == '')) {
    print('Missing or invalid ChallengeName.');
    return;
  }

  if ((result.jsonTypeOf('Session') != 1) || (result.stringOf('Session') == '')) {
    print('Missing or invalid Session.');
    return;
  }

  // ChallengeParameters may provide the canonical username after alias-based sign-in.
  if ((result.jsonTypeOf('ChallengeParameters.USER_ID_FOR_SRP') == 1) && (result.stringOf('ChallengeParameters.USER_ID_FOR_SRP') != '')) {
    username = result.stringOf('ChallengeParameters.USER_ID_FOR_SRP');
  }

  if ((result.jsonTypeOf('ChallengeParameters.USERNAME') == 1) && (result.stringOf('ChallengeParameters.USERNAME') != '')) {
    username = result.stringOf('ChallengeParameters.USERNAME');
  }

  result.updateString('username', username);
  result.updateString('client_id', app.stringOf('client_id'));
  result.updateString('user_pool_id', app.stringOf('user_pool_id'));
  result.updateString('account_key', app.stringOf('account_key'));
  final resultauthenticationchallenge = CkFileAccess();
  try {
    resultauthenticationchallenge.dirEnsureExists('qa_data/tokens');
  } on ChilkatException {
    print('Could not create the private cache directory.');
    return;
  }

  if (resultauthenticationchallenge.fileExists('qa_data/tokens/cognito-challenge.json')) {
    try {
      resultauthenticationchallenge.fileCopy('qa_data/tokens/cognito-challenge.json', 'qa_data/tokens/cognito-challenge.json.bak', false);
    } on ChilkatException {
      print('Could not back up the existing cache.');
      return;
    }
  }

  try {
    result.writeFile('qa_data/tokens/cognito-challenge.json');
  } on ChilkatException {
    print('Could not save authentication challenge; preserve any previous backup.');
    return;
  }

  print('Further authentication required: ${result.stringOf('ChallengeName')}');
  // Collect the requested input in your application's UI; never print the Session value.
}