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

Amazon Cognito: Refresh Tokens with Rotation Support

See more Amazon Cognito Examples

Renew a user session without asking for the password again. Choose the default GetTokensFromRefreshToken JSON API or the OAuth refresh_token grant. Both support refresh-token rotation. REFRESH_TOKEN_AUTH is incompatible with rotation and is intentionally not used. With rotation disabled, retain the old refresh token when the response omits a replacement; with rotation enabled, save the new one before another refresh.

Use a public client without a secret, matching the initial sign-in. Managed-login sessions can use the OAuth endpoint. API-origin sessions can use OAuth refresh only when device remembering is disabled; otherwise use the API with the confirmed DeviceKey. This collection's password sign-in example assumes device remembering is disabled. Coordinate simultaneous refreshes and handle the configured retry grace period; expiration or revocation requires a new sign-in. Rotating does not extend the original refresh-token lifetime.

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;
method: PWideChar;
cached: HCkJsonObject;
tokenEndpoint: HCkStringBuilder;
req: HCkHttpRequest;
token: HCkJsonObject;
obtained: HCkDateTime;
tokenrefreshedusertokens: 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);
//  "api" supports API sign-in and refresh rotation. "oauth" uses the Cognito domain.
method := 'api';
if ((method <> 'api') and (method <> 'oauth')) then
  begin
    Memo1.Lines.Add('Choose api or oauth.');
    Exit;
  end;
cached := CkJsonObject_Create();
CkJsonObject_putStrict(cached,True);
success := CkJsonObject_LoadFile(cached,'qa_data/tokens/cognito-user.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load qa_data/tokens/cognito-user.json.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(cached,'client_id') <> 1) or (CkJsonObject__stringOf(cached,'client_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
if (CkJsonObject__stringOf(cached,'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(cached,'user_pool_id') <> 1) or (CkJsonObject__stringOf(cached,'user_pool_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid user_pool_id.');
    Exit;
  end;
if (CkJsonObject__stringOf(cached,'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(cached,'account_key') <> 1) or (CkJsonObject__stringOf(cached,'account_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid account_key.');
    Exit;
  end;
if (CkJsonObject__stringOf(cached,'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(cached,'refresh_token') <> 1) or (CkJsonObject__stringOf(cached,'refresh_token') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid refresh_token.');
    Exit;
  end;
if (method = 'api') then
  begin
    CkJsonObject_UpdateString(body,'ClientId',clientId);
    CkJsonObject_UpdateString(body,'RefreshToken',CkJsonObject__stringOf(cached,'refresh_token'));
    //  If device remembering is enabled, supply the confirmed DeviceKey from your device flow.
    if ((CkJsonObject_JsonTypeOf(cached,'device_key') = 1) and (CkJsonObject__stringOf(cached,'device_key') <> '')) then
      begin
        CkJsonObject_UpdateString(body,'DeviceKey',CkJsonObject__stringOf(cached,'device_key'));
      end;
    CkHttp_SetRequestHeader(http,'X-Amz-Target','AWSCognitoIdentityProviderService.GetTokensFromRefreshToken');
    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
    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');
    req := CkHttpRequest_Create();
    CkHttpRequest_putHttpVerb(req,'POST');
    CkHttpRequest_putContentType(req,'application/x-www-form-urlencoded');
    CkHttpRequest_AddParam(req,'grant_type','refresh_token');
    CkHttpRequest_AddParam(req,'client_id',clientId);
    CkHttpRequest_AddParam(req,'refresh_token',CkJsonObject__stringOf(cached,'refresh_token'));
    success := CkHttp_HttpReq(http,CkStringBuilder__getAsString(tokenEndpoint),req,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;
token := CkJsonObject_Create();
if (method = 'api') then
  begin
    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;
  end
else
  begin
    success := CkJsonObject_Load(token,CkJsonObject__emit(result));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not copy the token response.');
        Exit;
      end;
  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;
//  Rotation enabled: save the replacement. Rotation disabled: retain the old refresh token.
if (CkJsonObject_HasMember(token,'refresh_token') = True) then
  begin
    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;
  end
else
  begin
    CkJsonObject_UpdateString(token,'refresh_token',CkJsonObject__stringOf(cached,'refresh_token'));
  end;
if ((CkJsonObject_JsonTypeOf(cached,'device_key') = 1) and (CkJsonObject__stringOf(cached,'device_key') <> '')) then
  begin
    CkJsonObject_UpdateString(token,'device_key',CkJsonObject__stringOf(cached,'device_key'));
  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));
tokenrefreshedusertokens := CkFileAccess_Create();
success := CkFileAccess_DirEnsureExists(tokenrefreshedusertokens,'qa_data/tokens');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not create the private cache directory.');
    Exit;
  end;
if (CkFileAccess_FileExists(tokenrefreshedusertokens,'qa_data/tokens/cognito-user.json') = True) then
  begin
    success := CkFileAccess_FileCopy(tokenrefreshedusertokens,'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 refreshed user tokens; preserve any previous backup.');
    Exit;
  end;
Memo1.Lines.Add('Tokens refreshed; private cache updated.');

CkJsonObject_Dispose(app);
CkStringBuilder_Dispose(endpoint);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(cached);
    CkStringBuilder_Dispose(tokenEndpoint);
    CkHttpRequest_Dispose(req);
CkJsonObject_Dispose(token);
CkDateTime_Dispose(obtained);
CkFileAccess_Dispose(tokenrefreshedusertokens);