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

Unicode C++
#include <CkStringBuilderW.h>
#include <CkXmlW.h>
#include <CkDateTimeW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkHashtableW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Accept the private XML handoff from either GetSessionToken or AssumeRole.
    CkXmlW xmlToken;
    xmlToken.put_Strict(true);
    success = xmlToken.LoadXmlFile(L"qa_data/tokens/aws_session_token.xml");
    if (success != true) {
        wprintf(L"Could not load the private STS credential file.\n");
        return;
    }

    const wchar_t *credentialPath = L"";
    stringCompare.SetString(xmlToken.tag());
    bool stringMatch1 = stringCompare.ContentsEqual(L"GetSessionTokenResponse",true);
    if (stringMatch1 == true) {
        credentialPath = L"GetSessionTokenResult|Credentials";
    }

    stringCompare.SetString(xmlToken.tag());
    bool stringMatch2 = stringCompare.ContentsEqual(L"AssumeRoleResponse",true);
    if (stringMatch2 == true) {
        credentialPath = L"AssumeRoleResult|Credentials";
    }

    stringCompare.SetString(credentialPath);
    bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
    if (stringMatch3 == true) {
        wprintf(L"Expected a GetSessionToken or AssumeRole credential response.\n");
        return;
    }

    const wchar_t *accessKey = 0;
    const wchar_t *secretKey = 0;
    const wchar_t *sessionToken = 0;
    const wchar_t *expiration = 0;
    CkStringBuilderW path;
    success = path.SetString(credentialPath);
    if (success != true) {
        wprintf(L"Could not build credential path.\n");
        return;
    }

    success = path.Append(L"|AccessKeyId");
    if (success != true) {
        wprintf(L"Could not build credential path.\n");
        return;
    }

    accessKey = xmlToken.getChildContent(path.getAsString());
    stringCompare.SetString(accessKey);
    bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
    if ((xmlToken.get_LastMethodSuccess() != true) || (stringMatch4 == true)) {
        wprintf(L"Missing or empty AccessKeyId.\n");
        return;
    }

    success = path.SetString(credentialPath);
    if (success != true) {
        wprintf(L"Could not build credential path.\n");
        return;
    }

    success = path.Append(L"|SecretAccessKey");
    if (success != true) {
        wprintf(L"Could not build credential path.\n");
        return;
    }

    secretKey = xmlToken.getChildContent(path.getAsString());
    stringCompare.SetString(secretKey);
    bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
    if ((xmlToken.get_LastMethodSuccess() != true) || (stringMatch5 == true)) {
        wprintf(L"Missing or empty SecretAccessKey.\n");
        return;
    }

    success = path.SetString(credentialPath);
    if (success != true) {
        wprintf(L"Could not build credential path.\n");
        return;
    }

    success = path.Append(L"|SessionToken");
    if (success != true) {
        wprintf(L"Could not build credential path.\n");
        return;
    }

    sessionToken = xmlToken.getChildContent(path.getAsString());
    stringCompare.SetString(sessionToken);
    bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
    if ((xmlToken.get_LastMethodSuccess() != true) || (stringMatch6 == true)) {
        wprintf(L"Missing or empty SessionToken.\n");
        return;
    }

    success = path.SetString(credentialPath);
    if (success != true) {
        wprintf(L"Could not build credential path.\n");
        return;
    }

    success = path.Append(L"|Expiration");
    if (success != true) {
        wprintf(L"Could not build credential path.\n");
        return;
    }

    expiration = xmlToken.getChildContent(path.getAsString());
    stringCompare.SetString(expiration);
    bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
    if ((xmlToken.get_LastMethodSuccess() != true) || (stringMatch7 == true)) {
        wprintf(L"Missing or empty Expiration.\n");
        return;
    }

    CkDateTimeW expires;
    CkDateTimeW now;
    success = expires.SetFromTimestamp(expiration);
    if (success != true) {
        wprintf(L"Stored expiration is invalid.\n");
        return;
    }

    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        wprintf(L"Could not read current time.\n");
        return;
    }

    if (expires.DiffSeconds(now) <= 60) {
        wprintf(L"Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
        return;
    }

    //  This S3 region is independent of the region that issued the STS credentials.
    const wchar_t *region = L"us-west-2";
    CkStringBuilderW endpoint;
    endpoint.Append(L"s3.");
    endpoint.Append(region);
    endpoint.Append(L".amazonaws.com");
    CkAuthAwsW aws;
    aws.put_AccessKey(accessKey);
    aws.put_SecretKey(secretKey);
    aws.put_Region(region);
    aws.put_ServiceName(L"s3");
    aws.put_SignatureVersion(4);
    CkRestW rest;
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    rest.put_VerboseLogging(false);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        wprintf(L"Could not configure request signing.\n");
        return;
    }

    //  Keep this verified Socket alive while Rest uses its connection.
    CkSocketW connection;
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        wprintf(L"Could not attach TLS connection.\n");
        return;
    }

    CkXmlW xml;
    xml.put_Strict(true);
    const wchar_t *value = 0;
    CkHashtableW seenTokens;
    const wchar_t *continuation = L"";
    const wchar_t *responseXml = 0;
    int page = 0;
    int index;
    bool more = true;
    while ((more == true)) {
        if (page == 10000) {
            wprintf(L"Page bound reached; bucket enumeration is incomplete.\n");
            return;
        }

        success = now.SetFromCurrentSystemTime();
        if (success != true) {
            wprintf(L"Could not read current time.\n");
            return;
        }

        if (expires.DiffSeconds(now) <= 60) {
            wprintf(L"Credentials are expiring; obtain fresh credentials before continuing the listing.\n");
            return;
        }

        page = page + 1;
        success = rest.ClearAllQueryParams();
        if (success != true) {
            wprintf(L"Could not clear parameters from the previous page.\n");
            return;
        }

        //  All three credential components are required. Never log this signed URL.
        success = rest.AddQueryParam(L"X-Amz-Security-Token",sessionToken);
        if (success != true) {
            wprintf(L"Could not set X-Amz-Security-Token.\n");
            return;
        }

        success = rest.AddQueryParam(L"max-buckets",L"100");
        if (success != true) {
            wprintf(L"Could not set max-buckets.\n");
            return;
        }

        stringCompare.SetString(continuation);
        bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
        if (stringMatch8 != true) {
            success = rest.AddQueryParam(L"continuation-token",continuation);
            if (success != true) {
                wprintf(L"Could not set continuation-token.\n");
                return;
            }

        }

        responseXml = rest.fullRequestNoBody(L"GET",L"/");
        if (rest.get_LastMethodSuccess() != true) {
            wprintf(L"S3 request did not complete; enumeration is incomplete.\n");
            return;
        }

        success = xml.LoadXml(responseXml);
        if (rest.get_ResponseStatusCode() != 200) {
            wprintf(L"S3 HTTP status: %d\n",rest.get_ResponseStatusCode());
            if (success == true) {
                value = xml.getChildContent(L"Code");
                if (xml.get_LastMethodSuccess() == true) {
                    wprintf(L"AWS error code: %s\n",value);
                }

                value = xml.getChildContent(L"RequestId");
                if (xml.get_LastMethodSuccess() == true) {
                    wprintf(L"AWS request ID: %s\n",value);
                }

            }

            return;
        }

        if (success != true) {
            wprintf(L"Invalid S3 XML response.\n");
            return;
        }

        stringCompare.SetString(xml.tag());
        bool stringMatch9 = stringCompare.ContentsEqual(L"ListAllMyBucketsResult",true);
        if (stringMatch9 != true) {
            wprintf(L"Unexpected S3 response root.\n");
            return;
        }

        if (xml.HasChildWithTag(L"Buckets") != true) {
            wprintf(L"Missing Buckets collection.\n");
            return;
        }

        index = 0;
        while ((index < xml.NumChildrenAt(L"Buckets"))) {
            xml.put_I(index);
            value = xml.getChildContent(L"Buckets|Bucket[i]|Name");
            stringCompare.SetString(value);
            bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
            if ((xml.get_LastMethodSuccess() != true) || (stringMatch10 == true)) {
                wprintf(L"Missing or empty Buckets|Bucket[i]|Name.\n");
                return;
            }

            wprintf(L"Bucket: %s\n",value);
            index = index + 1;
        }

        continuation = L"";
        if (xml.HasChildWithTag(L"ContinuationToken") == true) {
            continuation = xml.getChildContent(L"ContinuationToken");
            if (xml.get_LastMethodSuccess() != true) {
                wprintf(L"Invalid continuation token.\n");
                return;
            }

        }

        more = false;
        stringCompare.SetString(continuation);
        bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
        if (stringMatch11 != true) {
            if (seenTokens.Contains(continuation) == true) {
                wprintf(L"Repeated continuation token; enumeration is incomplete.\n");
                return;
            }

            success = seenTokens.AddStr(continuation,L"seen");
            if (success != true) {
                wprintf(L"Could not track pagination.\n");
                return;
            }

            more = true;
        }

    }

    wprintf(L"Bucket enumeration complete.\n");
    }