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

Amazon Cognito: Sign In with Managed Login and PKCE

See more Amazon Cognito Examples

Configure a User Pool domain and a public app client with no secret. Enable the authorization-code grant, the Cognito identity provider (or your configured IdP), and the requested openid, email, and aws.cognito.signin.user.admin scopes. Register http://localhost:3017/ exactly as an allowed callback URL. Chilkat receives the local callback and manages state and S256 PKCE; no hosted callback service is needed. Use the system browser, not a password form embedded in your application.

The self-service admin scope permits user operations such as TOTP enrollment; it does not grant IAM administration. Cognito code flow returns refresh tokens without offline_access. A public desktop client must not contain a client secret. Web/mobile applications need their own appropriate callback handling. Tokens are saved privately; decoding their claims is not validation.

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;
tokenEndpoint: HCkStringBuilder;
oauth: HCkOAuth2;
authorizeEndpoint: HCkStringBuilder;
authUrl: PWideChar;
waited: Integer;
token: HCkJsonObject;
obtained: HCkDateTime;
tokenusertokens: 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/');
if ((CkJsonObject_JsonTypeOf(app,'domain') <> 1) or (CkJsonObject__stringOf(app,'domain') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid domain.');
    Exit;
  end;
//  This URL comes from trusted configuration, never from a token or user-supplied URL.
tokenEndpoint := CkStringBuilder_Create();
CkStringBuilder_Append(tokenEndpoint,CkJsonObject__stringOf(app,'domain'));
CkStringBuilder_Append(tokenEndpoint,'/oauth2/token');
oauth := CkOAuth2_Create();
authorizeEndpoint := CkStringBuilder_Create();
CkStringBuilder_Append(authorizeEndpoint,CkJsonObject__stringOf(app,'domain'));
CkStringBuilder_Append(authorizeEndpoint,'/oauth2/authorize');
CkOAuth2_putAuthorizationEndpoint(oauth,CkStringBuilder__getAsString(authorizeEndpoint));
CkOAuth2_putTokenEndpoint(oauth,CkStringBuilder__getAsString(tokenEndpoint));
CkOAuth2_putClientId(oauth,clientId);
//  Register exactly http://localhost:3017/ as an allowed callback for this public client.
CkOAuth2_putLocalHost(oauth,'localhost');
CkOAuth2_putListenPort(oauth,3017);
CkOAuth2_putCodeChallenge(oauth,True);
CkOAuth2_putCodeChallengeMethod(oauth,'S256');
//  Cognito does NOT use an offline_access scope. Code flow returns a refresh token.
CkOAuth2_putScope(oauth,'openid email aws.cognito.signin.user.admin');
authUrl := CkOAuth2__startAuth(oauth);
if (CkOAuth2_getLastMethodSuccess(oauth) <> True) then
  begin
    Memo1.Lines.Add('Could not start the local OAuth listener.');
    Exit;
  end;
success := CkOAuth2_LaunchBrowser(oauth,authUrl);
if (success <> True) then
  begin
    CkOAuth2_Cancel(oauth);
    Memo1.Lines.Add('Could not launch the system browser.');
    Exit;
  end;
waited := 0;
while ((CkOAuth2_getAuthFlowState(oauth) < 3) and (waited < 180000)) do
  begin
    CkOAuth2_SleepMs(oauth,200);
    waited := waited + 200;
  end;

if (CkOAuth2_getAuthFlowState(oauth) < 3) then
  begin
    CkOAuth2_Cancel(oauth);
    Memo1.Lines.Add('Authorization timed out.');
    Exit;
  end;
if (CkOAuth2_getAuthFlowState(oauth) <> 3) then
  begin
    Memo1.Lines.Add('Authorization did not complete.');
    Exit;
  end;
token := CkJsonObject_Create();
CkJsonObject_putStrict(token,True);
success := CkJsonObject_Load(token,CkOAuth2__accessTokenResponse(oauth));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not parse the token response.');
    Exit;
  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;
Memo1.Lines.Add('Authorization completed; private token cache saved.');
//  Validate JWT signatures and claims before trusting their contents:
//  Validate a Cognito JWT.

CkJsonObject_Dispose(app);
CkStringBuilder_Dispose(endpoint);
CkStringBuilder_Dispose(tokenEndpoint);
CkOAuth2_Dispose(oauth);
CkStringBuilder_Dispose(authorizeEndpoint);
CkJsonObject_Dispose(token);
CkDateTime_Dispose(obtained);
CkFileAccess_Dispose(tokenusertokens);