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

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    CkStringBuilder stringCompare = new CkStringBuilder();
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Accept the private XML handoff from either GetSessionToken or AssumeRole.
    CkXml xmlToken = new CkXml();
    xmlToken.put_Strict(true);
    success = xmlToken.LoadXmlFile("qa_data/tokens/aws_session_token.xml");
    if (success != true) {
        System.out.println("Could not load the private STS credential file.");
        return;
        }

    String credentialPath = "";
    stringCompare.SetString(xmlToken.tag());
    boolean stringMatch1 = stringCompare.ContentsEqual("GetSessionTokenResponse",true);
    if (stringMatch1 == true) {
        credentialPath = "GetSessionTokenResult|Credentials";
        }

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

    stringCompare.SetString(credentialPath);
    boolean stringMatch3 = stringCompare.ContentsEqual("",true);
    if (stringMatch3 == true) {
        System.out.println("Expected a GetSessionToken or AssumeRole credential response.");
        return;
        }

    String accessKey;
    String secretKey;
    String sessionToken;
    String expiration;
    CkStringBuilder path = new CkStringBuilder();
    success = path.SetString(credentialPath);
    if (success != true) {
        System.out.println("Could not build credential path.");
        return;
        }

    success = path.Append("|AccessKeyId");
    if (success != true) {
        System.out.println("Could not build credential path.");
        return;
        }

    accessKey = xmlToken.getChildContent(path.getAsString());
    stringCompare.SetString(accessKey);
    boolean stringMatch4 = stringCompare.ContentsEqual("",true);
    if ((xmlToken.get_LastMethodSuccess() != true) || (stringMatch4 == true)) {
        System.out.println("Missing or empty AccessKeyId.");
        return;
        }

    success = path.SetString(credentialPath);
    if (success != true) {
        System.out.println("Could not build credential path.");
        return;
        }

    success = path.Append("|SecretAccessKey");
    if (success != true) {
        System.out.println("Could not build credential path.");
        return;
        }

    secretKey = xmlToken.getChildContent(path.getAsString());
    stringCompare.SetString(secretKey);
    boolean stringMatch5 = stringCompare.ContentsEqual("",true);
    if ((xmlToken.get_LastMethodSuccess() != true) || (stringMatch5 == true)) {
        System.out.println("Missing or empty SecretAccessKey.");
        return;
        }

    success = path.SetString(credentialPath);
    if (success != true) {
        System.out.println("Could not build credential path.");
        return;
        }

    success = path.Append("|SessionToken");
    if (success != true) {
        System.out.println("Could not build credential path.");
        return;
        }

    sessionToken = xmlToken.getChildContent(path.getAsString());
    stringCompare.SetString(sessionToken);
    boolean stringMatch6 = stringCompare.ContentsEqual("",true);
    if ((xmlToken.get_LastMethodSuccess() != true) || (stringMatch6 == true)) {
        System.out.println("Missing or empty SessionToken.");
        return;
        }

    success = path.SetString(credentialPath);
    if (success != true) {
        System.out.println("Could not build credential path.");
        return;
        }

    success = path.Append("|Expiration");
    if (success != true) {
        System.out.println("Could not build credential path.");
        return;
        }

    expiration = xmlToken.getChildContent(path.getAsString());
    stringCompare.SetString(expiration);
    boolean stringMatch7 = stringCompare.ContentsEqual("",true);
    if ((xmlToken.get_LastMethodSuccess() != true) || (stringMatch7 == true)) {
        System.out.println("Missing or empty Expiration.");
        return;
        }

    CkDateTime expires = new CkDateTime();
    CkDateTime now = new CkDateTime();
    success = expires.SetFromTimestamp(expiration);
    if (success != true) {
        System.out.println("Stored expiration is invalid.");
        return;
        }

    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        System.out.println("Could not read current time.");
        return;
        }

    if (expires.DiffSeconds(now) <= 60) {
        System.out.println("Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.");
        return;
        }

    //  This S3 region is independent of the region that issued the STS credentials.
    String region = "us-west-2";
    CkStringBuilder endpoint = new CkStringBuilder();
    endpoint.Append("s3.");
    endpoint.Append(region);
    endpoint.Append(".amazonaws.com");
    CkAuthAws aws = new CkAuthAws();
    aws.put_AccessKey(accessKey);
    aws.put_SecretKey(secretKey);
    aws.put_Region(region);
    aws.put_ServiceName("s3");
    aws.put_SignatureVersion(4);
    CkRest rest = new CkRest();
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    rest.put_VerboseLogging(false);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        System.out.println("Could not configure request signing.");
        return;
        }

    //  Keep this verified Socket alive while Rest uses its connection.
    CkSocket connection = new CkSocket();
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        System.out.println("TLS connection failed; inspect diagnostics privately.");
        return;
        }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        System.out.println("Could not attach TLS connection.");
        return;
        }

    CkXml xml = new CkXml();
    xml.put_Strict(true);
    String value;
    CkHashtable seenTokens = new CkHashtable();
    String continuation = "";
    String responseXml;
    int page = 0;
    int index;
    boolean more = true;
    while ((more == true)) {
        if (page == 10000) {
            System.out.println("Page bound reached; bucket enumeration is incomplete.");
            return;
            }

        success = now.SetFromCurrentSystemTime();
        if (success != true) {
            System.out.println("Could not read current time.");
            return;
            }

        if (expires.DiffSeconds(now) <= 60) {
            System.out.println("Credentials are expiring; obtain fresh credentials before continuing the listing.");
            return;
            }

        page = page+1;
        success = rest.ClearAllQueryParams();
        if (success != true) {
            System.out.println("Could not clear parameters from the previous page.");
            return;
            }

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

        success = rest.AddQueryParam("max-buckets","100");
        if (success != true) {
            System.out.println("Could not set max-buckets.");
            return;
            }

        stringCompare.SetString(continuation);
        boolean stringMatch8 = stringCompare.ContentsEqual("",true);
        if (stringMatch8 != true) {
            success = rest.AddQueryParam("continuation-token",continuation);
            if (success != true) {
                System.out.println("Could not set continuation-token.");
                return;
                }

            }

        responseXml = rest.fullRequestNoBody("GET","/");
        if (rest.get_LastMethodSuccess() != true) {
            System.out.println("S3 request did not complete; enumeration is incomplete.");
            return;
            }

        success = xml.LoadXml(responseXml);
        if (rest.get_ResponseStatusCode() != 200) {
            System.out.println("S3 HTTP status: " + rest.get_ResponseStatusCode());
            if (success == true) {
                value = xml.getChildContent("Code");
                if (xml.get_LastMethodSuccess() == true) {
                    System.out.println("AWS error code: " + value);
                    }

                value = xml.getChildContent("RequestId");
                if (xml.get_LastMethodSuccess() == true) {
                    System.out.println("AWS request ID: " + value);
                    }

                }

            return;
            }

        if (success != true) {
            System.out.println("Invalid S3 XML response.");
            return;
            }

        stringCompare.SetString(xml.tag());
        boolean stringMatch9 = stringCompare.ContentsEqual("ListAllMyBucketsResult",true);
        if (stringMatch9 != true) {
            System.out.println("Unexpected S3 response root.");
            return;
            }

        if (xml.HasChildWithTag("Buckets") != true) {
            System.out.println("Missing Buckets collection.");
            return;
            }

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

            System.out.println("Bucket: " + value);
            index = index+1;
            }

        continuation = "";
        if (xml.HasChildWithTag("ContinuationToken") == true) {
            continuation = xml.getChildContent("ContinuationToken");
            if (xml.get_LastMethodSuccess() != true) {
                System.out.println("Invalid continuation token.");
                return;
                }

            }

        more = false;
        stringCompare.SetString(continuation);
        boolean stringMatch11 = stringCompare.ContentsEqual("",true);
        if (stringMatch11 != true) {
            if (seenTokens.Contains(continuation) == true) {
                System.out.println("Repeated continuation token; enumeration is incomplete.");
                return;
                }

            success = seenTokens.AddStr(continuation,"seen");
            if (success != true) {
                System.out.println("Could not track pagination.");
                return;
                }

            more = true;
            }

        }

    System.out.println("Bucket enumeration complete.");
  }
}