Sample code for 30+ languages & platforms
Delphi DLL 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 Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
app: HCkJsonObject;
clientId: PWideChar;
endpoint: HCkStringBuilder;
http: HCkHttp;
resp: HCkHttpResponse;
body: HCkJsonObject;
result: HCkJsonObject;
action: PWideChar;
mode: PWideChar;
username: PWideChar;
credential: HCkJsonObject;
newEnrollment: HCkJsonObject;
newEnrollmentTOTPenrollment: HCkFileAccess;
enrollment: HCkJsonObject;
input: HCkJsonObject;
removeEnrollment: HCkFileAccess;
token: HCkJsonObject;
obtained: HCkDateTime;
tokenusertokens: HCkFileAccess;
cleanup: HCkFileAccess;
resultauthenticationchallenge: HCkFileAccess;

begin
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.
app := CkJsonObject_Create();
CkJsonObject_putStrict(app,True);
success := CkJsonObject_LoadFile(app,'qa_data/cognito/app.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load Cognito app settings.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(app,'region') <> 1) or (CkJsonObject__stringOf(app,'region') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid region.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(app,'user_pool_id') <> 1) or (CkJsonObject__stringOf(app,'user_pool_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid user_pool_id.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(app,'client_id') <> 1) or (CkJsonObject__stringOf(app,'client_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(app,'account_key') <> 1) or (CkJsonObject__stringOf(app,'account_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid account_key.');
    Exit;
  end;
clientId := CkJsonObject__stringOf(app,'client_id');
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'https://cognito-idp.');
CkStringBuilder_Append(endpoint,CkJsonObject__stringOf(app,'region'));
CkStringBuilder_Append(endpoint,'.amazonaws.com/');
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,20);
CkHttp_putReadTimeout(http,60);
resp := CkHttpResponse_Create();
body := CkJsonObject_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
action := 'begin';
mode := 'signed_in';
if ((action <> 'begin') and (action <> 'verify')) then
  begin
    Memo1.Lines.Add('Choose begin or verify.');
    Exit;
  end;
if ((mode <> 'signed_in') and (mode <> 'challenge')) then
  begin
    Memo1.Lines.Add('Choose signed_in or challenge.');
    Exit;
  end;
username := '';
credential := CkJsonObject_Create();
if (mode = 'signed_in') then
  begin
    success := CkJsonObject_LoadFile(credential,'qa_data/tokens/cognito-user.json');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not load user tokens.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'client_id') <> 1) or (CkJsonObject__stringOf(credential,'client_id') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid client_id.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credential,'client_id') <> CkJsonObject__stringOf(app,'client_id')) then
      begin
        Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'user_pool_id') <> 1) or (CkJsonObject__stringOf(credential,'user_pool_id') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid user_pool_id.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credential,'user_pool_id') <> CkJsonObject__stringOf(app,'user_pool_id')) then
      begin
        Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'account_key') <> 1) or (CkJsonObject__stringOf(credential,'account_key') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid account_key.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credential,'account_key') <> CkJsonObject__stringOf(app,'account_key')) then
      begin
        Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'access_token') <> 1) or (CkJsonObject__stringOf(credential,'access_token') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid access_token.');
        Exit;
      end;
  end
else
  begin
    success := CkJsonObject_LoadFile(credential,'qa_data/tokens/cognito-challenge.json');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not load the MFA_SETUP challenge.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'client_id') <> 1) or (CkJsonObject__stringOf(credential,'client_id') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid client_id.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credential,'client_id') <> CkJsonObject__stringOf(app,'client_id')) then
      begin
        Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'user_pool_id') <> 1) or (CkJsonObject__stringOf(credential,'user_pool_id') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid user_pool_id.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credential,'user_pool_id') <> CkJsonObject__stringOf(app,'user_pool_id')) then
      begin
        Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'account_key') <> 1) or (CkJsonObject__stringOf(credential,'account_key') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid account_key.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credential,'account_key') <> CkJsonObject__stringOf(app,'account_key')) then
      begin
        Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'Session') <> 1) or (CkJsonObject__stringOf(credential,'Session') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid Session.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(credential,'username') <> 1) or (CkJsonObject__stringOf(credential,'username') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid username.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credential,'ChallengeName') <> 'MFA_SETUP') then
      begin
        Memo1.Lines.Add('Expected an MFA_SETUP challenge.');
        Exit;
      end;
    username := CkJsonObject__stringOf(credential,'username');
  end;
if (action = 'begin') then
  begin
    if (mode = 'signed_in') then
      begin
        CkJsonObject_UpdateString(body,'AccessToken',CkJsonObject__stringOf(credential,'access_token'));
      end
    else
      begin
        CkJsonObject_UpdateString(body,'Session',CkJsonObject__stringOf(credential,'Session'));
      end;
    CkHttp_SetRequestHeader(http,'X-Amz-Target','AWSCognitoIdentityProviderService.AssociateSoftwareToken');
    success := CkHttp_HttpJson(http,'POST',CkStringBuilder__getAsString(endpoint),body,'application/x-amz-json-1.0',resp);
    if (CkHttpResponse_getStatusCode(resp) <> 200) then
      begin
        Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
        success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
        if (success = True) then
          begin
            Memo1.Lines.Add('Error type: ' + CkJsonObject__stringOf(result,'__type'));
            Memo1.Lines.Add('OAuth error: ' + CkJsonObject__stringOf(result,'error'));
          end;
        //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        Exit;
      end;
    if (success <> True) then
      begin
        Memo1.Lines.Add('The HTTP exchange did not complete.');
        Exit;
      end;
    success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected a JSON response.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(result,'SecretCode') <> 1) or (CkJsonObject__stringOf(result,'SecretCode') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid SecretCode.');
        Exit;
      end;
    newEnrollment := CkJsonObject_Create();
    CkJsonObject_UpdateString(newEnrollment,'secret_code',CkJsonObject__stringOf(result,'SecretCode'));
    CkJsonObject_UpdateString(newEnrollment,'mode',mode);
    CkJsonObject_UpdateString(newEnrollment,'username',username);
    if (mode = 'challenge') then
      begin
        if ((CkJsonObject_JsonTypeOf(result,'Session') <> 1) or (CkJsonObject__stringOf(result,'Session') = '')) then
          begin
            Memo1.Lines.Add('Missing or invalid Session.');
            Exit;
          end;
        CkJsonObject_UpdateString(newEnrollment,'session',CkJsonObject__stringOf(result,'Session'));
        //  Bind enrollment to this precise challenge, not just the account.
        CkJsonObject_UpdateString(newEnrollment,'original_session',CkJsonObject__stringOf(credential,'Session'));
      end;
    CkJsonObject_UpdateString(newEnrollment,'client_id',CkJsonObject__stringOf(app,'client_id'));
    CkJsonObject_UpdateString(newEnrollment,'user_pool_id',CkJsonObject__stringOf(app,'user_pool_id'));
    CkJsonObject_UpdateString(newEnrollment,'account_key',CkJsonObject__stringOf(app,'account_key'));
    newEnrollmentTOTPenrollment := CkFileAccess_Create();
    success := CkFileAccess_DirEnsureExists(newEnrollmentTOTPenrollment,'qa_data/tokens');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not create the private cache directory.');
        Exit;
      end;
    if (CkFileAccess_FileExists(newEnrollmentTOTPenrollment,'qa_data/tokens/cognito-totp.json') = True) then
      begin
        success := CkFileAccess_FileCopy(newEnrollmentTOTPenrollment,'qa_data/tokens/cognito-totp.json','qa_data/tokens/cognito-totp.json.bak',False);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not back up the existing cache.');
            Exit;
          end;
      end;
    success := CkJsonObject_WriteFile(newEnrollment,'qa_data/tokens/cognito-totp.json');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not save TOTP enrollment; preserve any previous backup.');
        Exit;
      end;
    Memo1.Lines.Add('Enrollment saved. Present secret_code privately in your authenticator setup UI.');
    //  This secret can generate future OTPs. Never log it or email it.
    Exit;
  end;
enrollment := CkJsonObject_Create();
CkJsonObject_putStrict(enrollment,True);
success := CkJsonObject_LoadFile(enrollment,'qa_data/tokens/cognito-totp.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load qa_data/tokens/cognito-totp.json.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(enrollment,'client_id') <> 1) or (CkJsonObject__stringOf(enrollment,'client_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
if (CkJsonObject__stringOf(enrollment,'client_id') <> CkJsonObject__stringOf(app,'client_id')) then
  begin
    Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(enrollment,'user_pool_id') <> 1) or (CkJsonObject__stringOf(enrollment,'user_pool_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid user_pool_id.');
    Exit;
  end;
if (CkJsonObject__stringOf(enrollment,'user_pool_id') <> CkJsonObject__stringOf(app,'user_pool_id')) then
  begin
    Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(enrollment,'account_key') <> 1) or (CkJsonObject__stringOf(enrollment,'account_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid account_key.');
    Exit;
  end;
if (CkJsonObject__stringOf(enrollment,'account_key') <> CkJsonObject__stringOf(app,'account_key')) then
  begin
    Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
    Exit;
  end;
if (CkJsonObject__stringOf(enrollment,'mode') <> mode) then
  begin
    Memo1.Lines.Add('Enrollment mode mismatch.');
    Exit;
  end;
input := CkJsonObject_Create();
CkJsonObject_putStrict(input,True);
success := CkJsonObject_LoadFile(input,'qa_data/cognito/totp-input.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load qa_data/cognito/totp-input.json.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(input,'code') <> 1) or (CkJsonObject__stringOf(input,'code') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid code.');
    Exit;
  end;
//  Enter a fresh six-digit code from the authenticator; preserve leading zeroes.
CkJsonObject_UpdateString(body,'UserCode',CkJsonObject__stringOf(input,'code'));
CkJsonObject_UpdateString(body,'FriendlyDeviceName','Authenticator');
if (mode = 'signed_in') then
  begin
    CkJsonObject_UpdateString(body,'AccessToken',CkJsonObject__stringOf(credential,'access_token'));
  end
else
  begin
    if ((CkJsonObject_JsonTypeOf(enrollment,'session') <> 1) or (CkJsonObject__stringOf(enrollment,'session') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid session.');
        Exit;
      end;
    if (CkJsonObject__stringOf(enrollment,'original_session') <> CkJsonObject__stringOf(credential,'Session')) then
      begin
        Memo1.Lines.Add('Enrollment belongs to another sign-in challenge.');
        Exit;
      end;
    CkJsonObject_UpdateString(body,'Session',CkJsonObject__stringOf(enrollment,'session'));
  end;
CkHttp_SetRequestHeader(http,'X-Amz-Target','AWSCognitoIdentityProviderService.VerifySoftwareToken');
success := CkHttp_HttpJson(http,'POST',CkStringBuilder__getAsString(endpoint),body,'application/x-amz-json-1.0',resp);
if (CkHttpResponse_getStatusCode(resp) <> 200) then
  begin
    Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
    success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
    if (success = True) then
      begin
        Memo1.Lines.Add('Error type: ' + CkJsonObject__stringOf(result,'__type'));
        Memo1.Lines.Add('OAuth error: ' + CkJsonObject__stringOf(result,'error'));
      end;
    //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Exit;
  end;
if (success <> True) then
  begin
    Memo1.Lines.Add('The HTTP exchange did not complete.');
    Exit;
  end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected a JSON response.');
    Exit;
  end;
if (CkJsonObject__stringOf(result,'Status') <> 'SUCCESS') then
  begin
    Memo1.Lines.Add('Authenticator verification did not succeed; do not enable it.');
    Exit;
  end;
//  Verification succeeded. Discard the enrollment secret and its backup.
removeEnrollment := CkFileAccess_Create();
CkFileAccess_FileDelete(removeEnrollment,'qa_data/tokens/cognito-totp.json');
if (CkFileAccess_FileExists(removeEnrollment,'qa_data/tokens/cognito-totp.json.bak') = True) then
  begin
    CkFileAccess_FileDelete(removeEnrollment,'qa_data/tokens/cognito-totp.json.bak');
  end;
success := CkJsonObject_Load(body,'{}');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not reset the request body.');
    Exit;
  end;
if (mode = 'signed_in') then
  begin
    CkJsonObject_UpdateString(body,'AccessToken',CkJsonObject__stringOf(credential,'access_token'));
    CkJsonObject_UpdateBool(body,'SoftwareTokenMfaSettings.Enabled',True);
    CkJsonObject_UpdateBool(body,'SoftwareTokenMfaSettings.PreferredMfa',True);
    CkHttp_SetRequestHeader(http,'X-Amz-Target','AWSCognitoIdentityProviderService.SetUserMFAPreference');
    success := CkHttp_HttpJson(http,'POST',CkStringBuilder__getAsString(endpoint),body,'application/x-amz-json-1.0',resp);
    if (CkHttpResponse_getStatusCode(resp) <> 200) then
      begin
        Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
        success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
        if (success = True) then
          begin
            Memo1.Lines.Add('Error type: ' + CkJsonObject__stringOf(result,'__type'));
            Memo1.Lines.Add('OAuth error: ' + CkJsonObject__stringOf(result,'error'));
          end;
        //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        Exit;
      end;
    if (success <> True) then
      begin
        Memo1.Lines.Add('The HTTP exchange did not complete.');
        Exit;
      end;
    Memo1.Lines.Add('Authenticator verified and set as the preferred MFA method.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(result,'Session') <> 1) or (CkJsonObject__stringOf(result,'Session') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid Session.');
    Exit;
  end;
//  Submit the NEW Session returned by VerifySoftwareToken, not the earlier one.
CkJsonObject_UpdateString(body,'ClientId',clientId);
CkJsonObject_UpdateString(body,'ChallengeName','MFA_SETUP');
CkJsonObject_UpdateString(body,'Session',CkJsonObject__stringOf(result,'Session'));
CkJsonObject_UpdateString(body,'ChallengeResponses.USERNAME',username);
CkHttp_SetRequestHeader(http,'X-Amz-Target','AWSCognitoIdentityProviderService.RespondToAuthChallenge');
success := CkHttp_HttpJson(http,'POST',CkStringBuilder__getAsString(endpoint),body,'application/x-amz-json-1.0',resp);
if (CkHttpResponse_getStatusCode(resp) <> 200) then
  begin
    Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
    success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
    if (success = True) then
      begin
        Memo1.Lines.Add('Error type: ' + CkJsonObject__stringOf(result,'__type'));
        Memo1.Lines.Add('OAuth error: ' + CkJsonObject__stringOf(result,'error'));
      end;
    //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Exit;
  end;
if (success <> True) then
  begin
    Memo1.Lines.Add('The HTTP exchange did not complete.');
    Exit;
  end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected a JSON response.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(result,'AuthenticationResult') = 3) then
  begin
    token := CkJsonObject_Create();
    CkJsonObject_UpdateString(token,'access_token',CkJsonObject__stringOf(result,'AuthenticationResult.AccessToken'));
    CkJsonObject_UpdateString(token,'id_token',CkJsonObject__stringOf(result,'AuthenticationResult.IdToken'));
    CkJsonObject_UpdateString(token,'token_type',CkJsonObject__stringOf(result,'AuthenticationResult.TokenType'));
    CkJsonObject_UpdateInt(token,'expires_in',CkJsonObject_IntOf(result,'AuthenticationResult.ExpiresIn'));
    if (CkJsonObject_HasMember(result,'AuthenticationResult.RefreshToken') = True) then
      begin
        CkJsonObject_UpdateString(token,'refresh_token',CkJsonObject__stringOf(result,'AuthenticationResult.RefreshToken'));
      end;
    if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (CkJsonObject__stringOf(token,'access_token') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid access_token.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(token,'id_token') <> 1) or (CkJsonObject__stringOf(token,'id_token') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid id_token.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(token,'expires_in') <> 2) or (CkJsonObject_IntOf(token,'expires_in') <= 0)) then
      begin
        Memo1.Lines.Add('Expected a positive token lifetime.');
        Exit;
      end;
    if (CkJsonObject__stringOf(token,'token_type') <> 'Bearer') then
      begin
        Memo1.Lines.Add('Expected Bearer tokens.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(token,'refresh_token') <> 1) or (CkJsonObject__stringOf(token,'refresh_token') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid refresh_token.');
        Exit;
      end;
    CkJsonObject_UpdateString(token,'client_id',CkJsonObject__stringOf(app,'client_id'));
    CkJsonObject_UpdateString(token,'user_pool_id',CkJsonObject__stringOf(app,'user_pool_id'));
    CkJsonObject_UpdateString(token,'account_key',CkJsonObject__stringOf(app,'account_key'));
    obtained := CkDateTime_Create();
    success := CkDateTime_SetFromCurrentSystemTime(obtained);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not get the acquisition time.');
        Exit;
      end;
    CkJsonObject_UpdateString(token,'obtained_at',CkDateTime__getAsTimestamp(obtained,False));
    tokenusertokens := CkFileAccess_Create();
    success := CkFileAccess_DirEnsureExists(tokenusertokens,'qa_data/tokens');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not create the private cache directory.');
        Exit;
      end;
    if (CkFileAccess_FileExists(tokenusertokens,'qa_data/tokens/cognito-user.json') = True) then
      begin
        success := CkFileAccess_FileCopy(tokenusertokens,'qa_data/tokens/cognito-user.json','qa_data/tokens/cognito-user.json.bak',False);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not back up the existing cache.');
            Exit;
          end;
      end;
    success := CkJsonObject_WriteFile(token,'qa_data/tokens/cognito-user.json');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not save user tokens; preserve any previous backup.');
        Exit;
      end;
    //  A completed flow no longer needs its short-lived challenge session.
    cleanup := CkFileAccess_Create();
    if (CkFileAccess_FileExists(cleanup,'qa_data/tokens/cognito-challenge.json') = True) then
      begin
        CkFileAccess_FileDelete(cleanup,'qa_data/tokens/cognito-challenge.json');
      end;
    Memo1.Lines.Add('Sign-in completed; private token cache saved.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(result,'ChallengeName') <> 1) or (CkJsonObject__stringOf(result,'ChallengeName') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid ChallengeName.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(result,'Session') <> 1) or (CkJsonObject__stringOf(result,'Session') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid Session.');
    Exit;
  end;
//  ChallengeParameters may provide the canonical username after alias-based sign-in.
if ((CkJsonObject_JsonTypeOf(result,'ChallengeParameters.USER_ID_FOR_SRP') = 1) and (CkJsonObject__stringOf(result,'ChallengeParameters.USER_ID_FOR_SRP') <> '')) then
  begin
    username := CkJsonObject__stringOf(result,'ChallengeParameters.USER_ID_FOR_SRP');
  end;
if ((CkJsonObject_JsonTypeOf(result,'ChallengeParameters.USERNAME') = 1) and (CkJsonObject__stringOf(result,'ChallengeParameters.USERNAME') <> '')) then
  begin
    username := CkJsonObject__stringOf(result,'ChallengeParameters.USERNAME');
  end;
CkJsonObject_UpdateString(result,'username',username);
CkJsonObject_UpdateString(result,'client_id',CkJsonObject__stringOf(app,'client_id'));
CkJsonObject_UpdateString(result,'user_pool_id',CkJsonObject__stringOf(app,'user_pool_id'));
CkJsonObject_UpdateString(result,'account_key',CkJsonObject__stringOf(app,'account_key'));
resultauthenticationchallenge := CkFileAccess_Create();
success := CkFileAccess_DirEnsureExists(resultauthenticationchallenge,'qa_data/tokens');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not create the private cache directory.');
    Exit;
  end;
if (CkFileAccess_FileExists(resultauthenticationchallenge,'qa_data/tokens/cognito-challenge.json') = True) then
  begin
    success := CkFileAccess_FileCopy(resultauthenticationchallenge,'qa_data/tokens/cognito-challenge.json','qa_data/tokens/cognito-challenge.json.bak',False);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not back up the existing cache.');
        Exit;
      end;
  end;
success := CkJsonObject_WriteFile(result,'qa_data/tokens/cognito-challenge.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save authentication challenge; preserve any previous backup.');
    Exit;
  end;
Memo1.Lines.Add('Further authentication required: ' + CkJsonObject__stringOf(result,'ChallengeName'));
//  Collect the requested input in your application's UI; never print the Session value.

CkJsonObject_Dispose(app);
CkStringBuilder_Dispose(endpoint);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(credential);
    CkJsonObject_Dispose(newEnrollment);
    CkFileAccess_Dispose(newEnrollmentTOTPenrollment);
CkJsonObject_Dispose(enrollment);
CkJsonObject_Dispose(input);
CkFileAccess_Dispose(removeEnrollment);
    CkJsonObject_Dispose(token);
    CkDateTime_Dispose(obtained);
    CkFileAccess_Dispose(tokenusertokens);
    CkFileAccess_Dispose(cleanup);
CkFileAccess_Dispose(resultauthenticationchallenge);