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

S3: List All Buckets with STS Credentials

See more AWS Security Token Service Examples

Uses all three temporary credential fields from the private XML file produced by either GetSessionToken or AssumeRole. Validates the response root, nonempty credential fields and ISO 8601 expiration before connecting, then checks expiry with a 60-second margin before each page. Does not print credential data, renew it automatically, or infer freshness merely from the presence of a file.

Uses Chilkat.Rest/AuthAws with Signature Version 4, service s3, explicit us-west-2 signing region, a matching regional endpoint, and TLS certificate verification. STS issuance region does not fix the service-request signing region. The session token is sent in the signed query on every request; do not log the request URL. Configure the appropriate endpoint for other partitions.

Requests max-buckets=100 and follows S3's ContinuationToken, including after an empty page. Tokens are opaque, repeated tokens stop enumeration, and a 10,000-page bound reports incomplete results. Requires s3:ListAllMyBuckets. Lists general purpose buckets owned by the authenticated account, not every bucket the caller can access. Directory buckets are excluded. Does not depend on Owner.DisplayName. Pagination is important for accounts with elevated bucket quotas, where unpaginated listing is rejected.

Pre-protect the credential file and output environment. This read-only consumer does not change the XML file. A production credential provider should coordinate refresh and publication of a complete credential set rather than partially updating it while requests are running.

AWS API reference

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
xmlToken: HCkXml;
credentialPath: PWideChar;
stringMatch1: Boolean;
stringMatch2: Boolean;
stringMatch3: Boolean;
accessKey: PWideChar;
secretKey: PWideChar;
sessionToken: PWideChar;
expiration: PWideChar;
path: HCkStringBuilder;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: Boolean;
stringMatch7: Boolean;
expires: HCkDateTime;
now: HCkDateTime;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
value: PWideChar;
seenTokens: HCkHashtable;
continuation: PWideChar;
responseXml: PWideChar;
page: Integer;
index: Integer;
more: Boolean;
stringMatch8: Boolean;
stringMatch9: Boolean;
stringMatch10: Boolean;
stringMatch11: Boolean;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Accept the private XML handoff from either GetSessionToken or AssumeRole.
xmlToken := CkXml_Create();
CkXml_putStrict(xmlToken,True);
success := CkXml_LoadXmlFile(xmlToken,'qa_data/tokens/aws_session_token.xml');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load the private STS credential file.');
    Exit;
  end;
credentialPath := '';
CkStringBuilder_SetString(stringCompare,CkXml__tag(xmlToken));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'GetSessionTokenResponse',True);
if (stringMatch1 = True) then
  begin
    credentialPath := 'GetSessionTokenResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(xmlToken));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'AssumeRoleResponse',True);
if (stringMatch2 = True) then
  begin
    credentialPath := 'AssumeRoleResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,credentialPath);
stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if (stringMatch3 = True) then
  begin
    Memo1.Lines.Add('Expected a GetSessionToken or AssumeRole credential response.');
    Exit;
  end;

path := CkStringBuilder_Create();
success := CkStringBuilder_SetString(path,credentialPath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build credential path.');
    Exit;
  end;
success := CkStringBuilder_Append(path,'|AccessKeyId');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build credential path.');
    Exit;
  end;
accessKey := CkXml__getChildContent(xmlToken,CkStringBuilder__getAsString(path));
CkStringBuilder_SetString(stringCompare,accessKey);
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xmlToken) <> True) or (stringMatch4 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty AccessKeyId.');
    Exit;
  end;
success := CkStringBuilder_SetString(path,credentialPath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build credential path.');
    Exit;
  end;
success := CkStringBuilder_Append(path,'|SecretAccessKey');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build credential path.');
    Exit;
  end;
secretKey := CkXml__getChildContent(xmlToken,CkStringBuilder__getAsString(path));
CkStringBuilder_SetString(stringCompare,secretKey);
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xmlToken) <> True) or (stringMatch5 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty SecretAccessKey.');
    Exit;
  end;
success := CkStringBuilder_SetString(path,credentialPath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build credential path.');
    Exit;
  end;
success := CkStringBuilder_Append(path,'|SessionToken');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build credential path.');
    Exit;
  end;
sessionToken := CkXml__getChildContent(xmlToken,CkStringBuilder__getAsString(path));
CkStringBuilder_SetString(stringCompare,sessionToken);
stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xmlToken) <> True) or (stringMatch6 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty SessionToken.');
    Exit;
  end;
success := CkStringBuilder_SetString(path,credentialPath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build credential path.');
    Exit;
  end;
success := CkStringBuilder_Append(path,'|Expiration');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build credential path.');
    Exit;
  end;
expiration := CkXml__getChildContent(xmlToken,CkStringBuilder__getAsString(path));
CkStringBuilder_SetString(stringCompare,expiration);
stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xmlToken) <> True) or (stringMatch7 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty Expiration.');
    Exit;
  end;
expires := CkDateTime_Create();
now := CkDateTime_Create();
success := CkDateTime_SetFromTimestamp(expires,expiration);
if (success <> True) then
  begin
    Memo1.Lines.Add('Stored expiration is invalid.');
    Exit;
  end;
success := CkDateTime_SetFromCurrentSystemTime(now);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read current time.');
    Exit;
  end;
if (CkDateTime_DiffSeconds(expires,now) <= 60) then
  begin
    Memo1.Lines.Add('Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.');
    Exit;
  end;
//  This S3 region is independent of the region that issued the STS credentials.
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'s3.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,accessKey);
CkAuthAws_putSecretKey(aws,secretKey);
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'s3');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
CkRest_putVerboseLogging(rest,False);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure request signing.');
    Exit;
  end;
//  Keep this verified Socket alive while Rest uses its connection.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach TLS connection.');
    Exit;
  end;
xml := CkXml_Create();
CkXml_putStrict(xml,True);

seenTokens := CkHashtable_Create();
continuation := '';

page := 0;

more := True;
while (more = True) do
  begin
    if (page = 10000) then
      begin
        Memo1.Lines.Add('Page bound reached; bucket enumeration is incomplete.');
        Exit;
      end;
    success := CkDateTime_SetFromCurrentSystemTime(now);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not read current time.');
        Exit;
      end;
    if (CkDateTime_DiffSeconds(expires,now) <= 60) then
      begin
        Memo1.Lines.Add('Credentials are expiring; obtain fresh credentials before continuing the listing.');
        Exit;
      end;
    page := page + 1;
    success := CkRest_ClearAllQueryParams(rest);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not clear parameters from the previous page.');
        Exit;
      end;
    //  All three credential components are required. Never log this signed URL.
    success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',sessionToken);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set X-Amz-Security-Token.');
        Exit;
      end;
    success := CkRest_AddQueryParam(rest,'max-buckets','100');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set max-buckets.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,continuation);
    stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if (stringMatch8 <> True) then
      begin
        success := CkRest_AddQueryParam(rest,'continuation-token',continuation);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set continuation-token.');
            Exit;
          end;
      end;
    responseXml := CkRest__fullRequestNoBody(rest,'GET','/');
    if (CkRest_getLastMethodSuccess(rest) <> True) then
      begin
        Memo1.Lines.Add('S3 request did not complete; enumeration is incomplete.');
        Exit;
      end;
    success := CkXml_LoadXml(xml,responseXml);
    if (CkRest_getResponseStatusCode(rest) <> 200) then
      begin
        Memo1.Lines.Add('S3 HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
        if (success = True) then
          begin
            value := CkXml__getChildContent(xml,'Code');
            if (CkXml_getLastMethodSuccess(xml) = True) then
              begin
                Memo1.Lines.Add('AWS error code: ' + value);
              end;
            value := CkXml__getChildContent(xml,'RequestId');
            if (CkXml_getLastMethodSuccess(xml) = True) then
              begin
                Memo1.Lines.Add('AWS request ID: ' + value);
              end;
          end;
        Exit;
      end;
    if (success <> True) then
      begin
        Memo1.Lines.Add('Invalid S3 XML response.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkXml__tag(xml));
    stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'ListAllMyBucketsResult',True);
    if (stringMatch9 <> True) then
      begin
        Memo1.Lines.Add('Unexpected S3 response root.');
        Exit;
      end;
    if (CkXml_HasChildWithTag(xml,'Buckets') <> True) then
      begin
        Memo1.Lines.Add('Missing Buckets collection.');
        Exit;
      end;
    index := 0;
    while (index < CkXml_NumChildrenAt(xml,'Buckets')) do
      begin
        CkXml_putI(xml,index);
        value := CkXml__getChildContent(xml,'Buckets|Bucket[i]|Name');
        CkStringBuilder_SetString(stringCompare,value);
        stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
        if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch10 = True)) then
          begin
            Memo1.Lines.Add('Missing or empty Buckets|Bucket[i]|Name.');
            Exit;
          end;
        Memo1.Lines.Add('Bucket: ' + value);
        index := index + 1;
      end;

    continuation := '';
    if (CkXml_HasChildWithTag(xml,'ContinuationToken') = True) then
      begin
        continuation := CkXml__getChildContent(xml,'ContinuationToken');
        if (CkXml_getLastMethodSuccess(xml) <> True) then
          begin
            Memo1.Lines.Add('Invalid continuation token.');
            Exit;
          end;
      end;
    more := False;
    CkStringBuilder_SetString(stringCompare,continuation);
    stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if (stringMatch11 <> True) then
      begin
        if (CkHashtable_Contains(seenTokens,continuation) = True) then
          begin
            Memo1.Lines.Add('Repeated continuation token; enumeration is incomplete.');
            Exit;
          end;
        success := CkHashtable_AddStr(seenTokens,continuation,'seen');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not track pagination.');
            Exit;
          end;
        more := True;
      end;
  end;

Memo1.Lines.Add('Bucket enumeration complete.');

CkStringBuilder_Dispose(stringCompare);
CkXml_Dispose(xmlToken);
CkStringBuilder_Dispose(path);
CkDateTime_Dispose(expires);
CkDateTime_Dispose(now);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkHashtable_Dispose(seenTokens);