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

Amazon Cognito: Sign In and Respond to Password or MFA Challenges

See more Amazon Cognito Examples

Enable ALLOW_USER_PASSWORD_AUTH on a public app client without a secret; use a password-based pool with device remembering disabled. Managed login with PKCE is preferable when your application need not handle passwords. This example illustrates the JSON API directly: start with username/password, then respond to each returned challenge with its latest Session. It does not implement SRP, remembered-device authentication, passkeys, custom challenges, or every possible challenge.

Set action=start with a private signin-input.json containing username and password. For respond, supply username plus new_password or code. NEW_PASSWORD_REQUIRED can also require a required_attributes object keyed by the names in ChallengeParameters.requiredAttributes, for example "userAttributes.email". Supply only requested missing attributes; existing required attributes cannot be changed during this challenge. Handles NEW_PASSWORD_REQUIRED, SMS_MFA, SOFTWARE_TOKEN_MFA and EMAIL_OTP. MFA_SETUP is handed to TOTP enrollment. Other challenges stop explicitly.

The latest challenge is saved privately with the canonical username and app/account binding. Only AuthenticationResult constitutes completed sign-in; a Session is not an access token. Confirmation codes remain strings, preserving leading zeroes. On timeout/expired session start again; do not reuse a session across users or parallel flows.

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

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;
input: HCkJsonObject;
username: PWideChar;
challenge: HCkJsonObject;
challengeName: PWideChar;
requiredAttributes: HCkJsonArray;
requiredJson: PWideChar;
answers: HCkJsonObject;
i: Integer;
count: Integer;
attribute: PWideChar;
attributeValue: PWideChar;
supplied: HCkJsonObject;
attributePath: HCkStringBuilder;
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);
//  "start" begins sign-in. "respond" submits input for the most recent saved challenge.
action := 'start';
if ((action <> 'start') and (action <> 'respond')) then
  begin
    Memo1.Lines.Add('Choose start or respond.');
    Exit;
  end;
input := CkJsonObject_Create();
CkJsonObject_putStrict(input,True);
success := CkJsonObject_LoadFile(input,'qa_data/cognito/signin-input.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load qa_data/cognito/signin-input.json.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(input,'username') <> 1) or (CkJsonObject__stringOf(input,'username') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid username.');
    Exit;
  end;
username := CkJsonObject__stringOf(input,'username');
CkJsonObject_UpdateString(body,'ClientId',clientId);
if (action = 'start') then
  begin
    if ((CkJsonObject_JsonTypeOf(input,'password') <> 1) or (CkJsonObject__stringOf(input,'password') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid password.');
        Exit;
      end;
    CkJsonObject_UpdateString(body,'AuthFlow','USER_PASSWORD_AUTH');
    CkJsonObject_UpdateString(body,'AuthParameters.USERNAME',username);
    CkJsonObject_UpdateString(body,'AuthParameters.PASSWORD',CkJsonObject__stringOf(input,'password'));
    CkHttp_SetRequestHeader(http,'X-Amz-Target','AWSCognitoIdentityProviderService.InitiateAuth');
    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;
  end
else
  begin
    challenge := CkJsonObject_Create();
    CkJsonObject_putStrict(challenge,True);
    success := CkJsonObject_LoadFile(challenge,'qa_data/tokens/cognito-challenge.json');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not load qa_data/tokens/cognito-challenge.json.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(challenge,'client_id') <> 1) or (CkJsonObject__stringOf(challenge,'client_id') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid client_id.');
        Exit;
      end;
    if (CkJsonObject__stringOf(challenge,'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(challenge,'user_pool_id') <> 1) or (CkJsonObject__stringOf(challenge,'user_pool_id') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid user_pool_id.');
        Exit;
      end;
    if (CkJsonObject__stringOf(challenge,'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(challenge,'account_key') <> 1) or (CkJsonObject__stringOf(challenge,'account_key') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid account_key.');
        Exit;
      end;
    if (CkJsonObject__stringOf(challenge,'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(challenge,'Session') <> 1) or (CkJsonObject__stringOf(challenge,'Session') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid Session.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(challenge,'ChallengeName') <> 1) or (CkJsonObject__stringOf(challenge,'ChallengeName') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid ChallengeName.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(challenge,'username') <> 1) or (CkJsonObject__stringOf(challenge,'username') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid username.');
        Exit;
      end;
    //  Use the bound canonical username from the previous response, not a new alias.
    username := CkJsonObject__stringOf(challenge,'username');
    challengeName := CkJsonObject__stringOf(challenge,'ChallengeName');
    CkJsonObject_UpdateString(body,'Session',CkJsonObject__stringOf(challenge,'Session'));
    CkJsonObject_UpdateString(body,'ChallengeName',challengeName);
    CkJsonObject_UpdateString(body,'ChallengeResponses.USERNAME',username);
    if (challengeName = 'NEW_PASSWORD_REQUIRED') then
      begin
        if ((CkJsonObject_JsonTypeOf(input,'new_password') <> 1) or (CkJsonObject__stringOf(input,'new_password') = '')) then
          begin
            Memo1.Lines.Add('Missing or invalid new_password.');
            Exit;
          end;
        CkJsonObject_UpdateString(body,'ChallengeResponses.NEW_PASSWORD',CkJsonObject__stringOf(input,'new_password'));
        //  requiredAttributes is a JSON array encoded inside a JSON string.
        requiredAttributes := CkJsonArray_Create();
        requiredJson := CkJsonObject__stringOf(challenge,'ChallengeParameters.requiredAttributes');
        if (CkJsonObject_HasMember(challenge,'ChallengeParameters.requiredAttributes') <> True) then
          begin
            requiredJson := '[]';
          end;
        success := CkJsonArray_Load(requiredAttributes,requiredJson);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Invalid required-attributes list.');
            Exit;
          end;
        answers := CkJsonObject_Create();
        success := CkJsonObject_ObjectOf2(body,'ChallengeResponses',answers);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not access challenge responses.');
            Exit;
          end;
        i := 0;
        count := CkJsonArray_getSize(requiredAttributes);

        supplied := CkJsonObject_Create();
        if (count > 0) then
          begin
            success := CkJsonObject_ObjectOf2(input,'required_attributes',supplied);
            if (success <> True) then
              begin
                Memo1.Lines.Add('Supply all required attributes in required_attributes.');
                Exit;
              end;
          end;
        while i < count do
          begin
            attribute := CkJsonArray__stringAt(requiredAttributes,i);
            //  Keys are returned as userAttributes.email, userAttributes.name, etc.
            //  StringOf with a quoted path treats the whole key literally.
            attributePath := CkStringBuilder_Create();
            CkStringBuilder_Append(attributePath,'"');
            CkStringBuilder_Append(attributePath,attribute);
            CkStringBuilder_Append(attributePath,'"');
            attributeValue := CkJsonObject__stringOf(supplied,CkStringBuilder__getAsString(attributePath));
            if ((CkJsonObject_JsonTypeOf(supplied,CkStringBuilder__getAsString(attributePath)) <> 1) or (attributeValue = '')) then
              begin
                Memo1.Lines.Add('A required user attribute is missing.');
                Exit;
              end;
            CkJsonObject_AppendString(answers,attribute,attributeValue);
            i := i + 1;
          end;

      end
    else
      begin
        if ((challengeName <> 'SMS_MFA') and (challengeName <> 'SOFTWARE_TOKEN_MFA') and (challengeName <> 'EMAIL_OTP')) then
          begin
            Memo1.Lines.Add('This challenge needs a different handler: ' + challengeName);
            //  MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
            Exit;
          end;
        if ((CkJsonObject_JsonTypeOf(input,'code') <> 1) or (CkJsonObject__stringOf(input,'code') = '')) then
          begin
            Memo1.Lines.Add('Missing or invalid code.');
            Exit;
          end;
        if (challengeName = 'SMS_MFA') then
          begin
            CkJsonObject_UpdateString(body,'ChallengeResponses.SMS_MFA_CODE',CkJsonObject__stringOf(input,'code'));
          end;
        if (challengeName = 'SOFTWARE_TOKEN_MFA') then
          begin
            CkJsonObject_UpdateString(body,'ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE',CkJsonObject__stringOf(input,'code'));
          end;
        if (challengeName = 'EMAIL_OTP') then
          begin
            CkJsonObject_UpdateString(body,'ChallengeResponses.EMAIL_OTP_CODE',CkJsonObject__stringOf(input,'code'));
          end;
      end;
    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;
  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(input);
    CkJsonObject_Dispose(challenge);
        CkJsonArray_Dispose(requiredAttributes);
        CkJsonObject_Dispose(answers);
        CkJsonObject_Dispose(supplied);
            CkStringBuilder_Dispose(attributePath);
    CkJsonObject_Dispose(token);
    CkDateTime_Dispose(obtained);
    CkFileAccess_Dispose(tokenusertokens);
    CkFileAccess_Dispose(cleanup);
CkFileAccess_Dispose(resultauthenticationchallenge);