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

Xojo Plugin
Dim success As Boolean
success = False

Dim stringCompare As New Chilkat.StringBuilder
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Accept the private XML handoff from either GetSessionToken or AssumeRole.
Dim xmlToken As New Chilkat.Xml
xmlToken.Strict = True
success = xmlToken.LoadXmlFile("qa_data/tokens/aws_session_token.xml")
If (success <> True) Then
    System.DebugLog("Could not load the private STS credential file.")
    Return
End If

Dim credentialPath As String
credentialPath = ""
success = stringCompare.SetString(xmlToken.Tag)
Dim stringMatch1 As Boolean
stringMatch1 = stringCompare.ContentsEqual("GetSessionTokenResponse",True)
If (stringMatch1 = True) Then
    credentialPath = "GetSessionTokenResult|Credentials"
End If

success = stringCompare.SetString(xmlToken.Tag)
Dim stringMatch2 As Boolean
stringMatch2 = stringCompare.ContentsEqual("AssumeRoleResponse",True)
If (stringMatch2 = True) Then
    credentialPath = "AssumeRoleResult|Credentials"
End If

success = stringCompare.SetString(credentialPath)
Dim stringMatch3 As Boolean
stringMatch3 = stringCompare.ContentsEqual("",True)
If (stringMatch3 = True) Then
    System.DebugLog("Expected a GetSessionToken or AssumeRole credential response.")
    Return
End If

Dim accessKey As String
Dim secretKey As String
Dim sessionToken As String
Dim expiration As String
Dim path As New Chilkat.StringBuilder
success = path.SetString(credentialPath)
If (success <> True) Then
    System.DebugLog("Could not build credential path.")
    Return
End If

success = path.Append("|AccessKeyId")
If (success <> True) Then
    System.DebugLog("Could not build credential path.")
    Return
End If

accessKey = xmlToken.GetChildContent(path.GetAsString())
success = stringCompare.SetString(accessKey)
Dim stringMatch4 As Boolean
stringMatch4 = stringCompare.ContentsEqual("",True)
If ((xmlToken.LastMethodSuccess <> True) Or (stringMatch4 = True)) Then
    System.DebugLog("Missing or empty AccessKeyId.")
    Return
End If

success = path.SetString(credentialPath)
If (success <> True) Then
    System.DebugLog("Could not build credential path.")
    Return
End If

success = path.Append("|SecretAccessKey")
If (success <> True) Then
    System.DebugLog("Could not build credential path.")
    Return
End If

secretKey = xmlToken.GetChildContent(path.GetAsString())
success = stringCompare.SetString(secretKey)
Dim stringMatch5 As Boolean
stringMatch5 = stringCompare.ContentsEqual("",True)
If ((xmlToken.LastMethodSuccess <> True) Or (stringMatch5 = True)) Then
    System.DebugLog("Missing or empty SecretAccessKey.")
    Return
End If

success = path.SetString(credentialPath)
If (success <> True) Then
    System.DebugLog("Could not build credential path.")
    Return
End If

success = path.Append("|SessionToken")
If (success <> True) Then
    System.DebugLog("Could not build credential path.")
    Return
End If

sessionToken = xmlToken.GetChildContent(path.GetAsString())
success = stringCompare.SetString(sessionToken)
Dim stringMatch6 As Boolean
stringMatch6 = stringCompare.ContentsEqual("",True)
If ((xmlToken.LastMethodSuccess <> True) Or (stringMatch6 = True)) Then
    System.DebugLog("Missing or empty SessionToken.")
    Return
End If

success = path.SetString(credentialPath)
If (success <> True) Then
    System.DebugLog("Could not build credential path.")
    Return
End If

success = path.Append("|Expiration")
If (success <> True) Then
    System.DebugLog("Could not build credential path.")
    Return
End If

expiration = xmlToken.GetChildContent(path.GetAsString())
success = stringCompare.SetString(expiration)
Dim stringMatch7 As Boolean
stringMatch7 = stringCompare.ContentsEqual("",True)
If ((xmlToken.LastMethodSuccess <> True) Or (stringMatch7 = True)) Then
    System.DebugLog("Missing or empty Expiration.")
    Return
End If

Dim expires As New Chilkat.CkDateTime
Dim now As New Chilkat.CkDateTime
success = expires.SetFromTimestamp(expiration)
If (success <> True) Then
    System.DebugLog("Stored expiration is invalid.")
    Return
End If

success = now.SetFromCurrentSystemTime()
If (success <> True) Then
    System.DebugLog("Could not read current time.")
    Return
End If

If (expires.DiffSeconds(now) <= 60) Then
    System.DebugLog("Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.")
    Return
End If

//  This S3 region is independent of the region that issued the STS credentials.
Dim region As String
region = "us-west-2"
Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append("s3.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New Chilkat.AuthAws
aws.AccessKey = accessKey
aws.SecretKey = secretKey
aws.Region = region
aws.ServiceName = "s3"
aws.SignatureVersion = 4
Dim rest As New Chilkat.Rest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
If (success <> True) Then
    System.DebugLog("Could not configure request signing.")
    Return
End If

//  Keep this verified Socket alive while Rest uses its connection.
Dim connection As New Chilkat.Socket
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
If (success <> True) Then
    System.DebugLog("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection,True)
If (success <> True) Then
    System.DebugLog("Could not attach TLS connection.")
    Return
End If

Dim xml As New Chilkat.Xml
xml.Strict = True
Dim value As String
Dim seenTokens As New Chilkat.Hashtable
Dim continuation As String
continuation = ""
Dim responseXml As String
Dim page As Int32
page = 0
Dim index As Int32
Dim more As Boolean
more = True
While (more = True)
    If (page = 10000) Then
        System.DebugLog("Page bound reached; bucket enumeration is incomplete.")
        Return
    End If

    success = now.SetFromCurrentSystemTime()
    If (success <> True) Then
        System.DebugLog("Could not read current time.")
        Return
    End If

    If (expires.DiffSeconds(now) <= 60) Then
        System.DebugLog("Credentials are expiring; obtain fresh credentials before continuing the listing.")
        Return
    End If

    page = page + 1
    success = rest.ClearAllQueryParams()
    If (success <> True) Then
        System.DebugLog("Could not clear parameters from the previous page.")
        Return
    End If

    //  All three credential components are required. Never log this signed URL.
    success = rest.AddQueryParam("X-Amz-Security-Token",sessionToken)
    If (success <> True) Then
        System.DebugLog("Could not set X-Amz-Security-Token.")
        Return
    End If

    success = rest.AddQueryParam("max-buckets","100")
    If (success <> True) Then
        System.DebugLog("Could not set max-buckets.")
        Return
    End If

    success = stringCompare.SetString(continuation)
    Dim stringMatch8 As Boolean
    stringMatch8 = stringCompare.ContentsEqual("",True)
    If (stringMatch8 <> True) Then
        success = rest.AddQueryParam("continuation-token",continuation)
        If (success <> True) Then
            System.DebugLog("Could not set continuation-token.")
            Return
        End If

    End If

    responseXml = rest.FullRequestNoBody("GET","/")
    If (rest.LastMethodSuccess <> True) Then
        System.DebugLog("S3 request did not complete; enumeration is incomplete.")
        Return
    End If

    success = xml.LoadXml(responseXml)
    If (rest.ResponseStatusCode <> 200) Then
        System.DebugLog("S3 HTTP status: " + Str(rest.ResponseStatusCode))
        If (success = True) Then
            value = xml.GetChildContent("Code")
            If (xml.LastMethodSuccess = True) Then
                System.DebugLog("AWS error code: " + value)
            End If

            value = xml.GetChildContent("RequestId")
            If (xml.LastMethodSuccess = True) Then
                System.DebugLog("AWS request ID: " + value)
            End If

        End If

        Return
    End If

    If (success <> True) Then
        System.DebugLog("Invalid S3 XML response.")
        Return
    End If

    success = stringCompare.SetString(xml.Tag)
    Dim stringMatch9 As Boolean
    stringMatch9 = stringCompare.ContentsEqual("ListAllMyBucketsResult",True)
    If (stringMatch9 <> True) Then
        System.DebugLog("Unexpected S3 response root.")
        Return
    End If

    If (xml.HasChildWithTag("Buckets") <> True) Then
        System.DebugLog("Missing Buckets collection.")
        Return
    End If

    index = 0
    While (index < xml.NumChildrenAt("Buckets"))
        xml.I = index
        value = xml.GetChildContent("Buckets|Bucket[i]|Name")
        success = stringCompare.SetString(value)
        Dim stringMatch10 As Boolean
        stringMatch10 = stringCompare.ContentsEqual("",True)
        If ((xml.LastMethodSuccess <> True) Or (stringMatch10 = True)) Then
            System.DebugLog("Missing or empty Buckets|Bucket[i]|Name.")
            Return
        End If

        System.DebugLog("Bucket: " + value)
        index = index + 1
    Wend
    continuation = ""
    If (xml.HasChildWithTag("ContinuationToken") = True) Then
        continuation = xml.GetChildContent("ContinuationToken")
        If (xml.LastMethodSuccess <> True) Then
            System.DebugLog("Invalid continuation token.")
            Return
        End If

    End If

    more = False
    success = stringCompare.SetString(continuation)
    Dim stringMatch11 As Boolean
    stringMatch11 = stringCompare.ContentsEqual("",True)
    If (stringMatch11 <> True) Then
        If (seenTokens.Contains(continuation) = True) Then
            System.DebugLog("Repeated continuation token; enumeration is incomplete.")
            Return
        End If

        success = seenTokens.AddStr(continuation,"seen")
        If (success <> True) Then
            System.DebugLog("Could not track pagination.")
            Return
        End If

        more = True
    End If

Wend
System.DebugLog("Bucket enumeration complete.")