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

Visual Basic 6.0
Dim success As Long
success = 0

Dim stringCompare As New ChilkatStringBuilder
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Accept the private XML handoff from either GetSessionToken or AssumeRole.
Dim xmlToken As New ChilkatXml
xmlToken.Strict = 1
success = xmlToken.LoadXmlFile("qa_data/tokens/aws_session_token.xml")
If (success <> 1) Then
    Debug.Print "Could not load the private STS credential file."
    Exit Sub
End If

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

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

success = stringCompare.SetString(credentialPath)
Dim stringMatch3 As Long
stringMatch3 = stringCompare.ContentsEqual("",1)
If (stringMatch3 = 1) Then
    Debug.Print "Expected a GetSessionToken or AssumeRole credential response."
    Exit Sub
End If

Dim accessKey As String
Dim secretKey As String
Dim sessionToken As String
Dim expiration As String
Dim path As New ChilkatStringBuilder
success = path.SetString(credentialPath)
If (success <> 1) Then
    Debug.Print "Could not build credential path."
    Exit Sub
End If

success = path.Append("|AccessKeyId")
If (success <> 1) Then
    Debug.Print "Could not build credential path."
    Exit Sub
End If

accessKey = xmlToken.GetChildContent(path.GetAsString())
success = stringCompare.SetString(accessKey)
Dim stringMatch4 As Long
stringMatch4 = stringCompare.ContentsEqual("",1)
If ((xmlToken.LastMethodSuccess <> 1) Or (stringMatch4 = 1)) Then
    Debug.Print "Missing or empty AccessKeyId."
    Exit Sub
End If

success = path.SetString(credentialPath)
If (success <> 1) Then
    Debug.Print "Could not build credential path."
    Exit Sub
End If

success = path.Append("|SecretAccessKey")
If (success <> 1) Then
    Debug.Print "Could not build credential path."
    Exit Sub
End If

secretKey = xmlToken.GetChildContent(path.GetAsString())
success = stringCompare.SetString(secretKey)
Dim stringMatch5 As Long
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((xmlToken.LastMethodSuccess <> 1) Or (stringMatch5 = 1)) Then
    Debug.Print "Missing or empty SecretAccessKey."
    Exit Sub
End If

success = path.SetString(credentialPath)
If (success <> 1) Then
    Debug.Print "Could not build credential path."
    Exit Sub
End If

success = path.Append("|SessionToken")
If (success <> 1) Then
    Debug.Print "Could not build credential path."
    Exit Sub
End If

sessionToken = xmlToken.GetChildContent(path.GetAsString())
success = stringCompare.SetString(sessionToken)
Dim stringMatch6 As Long
stringMatch6 = stringCompare.ContentsEqual("",1)
If ((xmlToken.LastMethodSuccess <> 1) Or (stringMatch6 = 1)) Then
    Debug.Print "Missing or empty SessionToken."
    Exit Sub
End If

success = path.SetString(credentialPath)
If (success <> 1) Then
    Debug.Print "Could not build credential path."
    Exit Sub
End If

success = path.Append("|Expiration")
If (success <> 1) Then
    Debug.Print "Could not build credential path."
    Exit Sub
End If

expiration = xmlToken.GetChildContent(path.GetAsString())
success = stringCompare.SetString(expiration)
Dim stringMatch7 As Long
stringMatch7 = stringCompare.ContentsEqual("",1)
If ((xmlToken.LastMethodSuccess <> 1) Or (stringMatch7 = 1)) Then
    Debug.Print "Missing or empty Expiration."
    Exit Sub
End If

Dim expires As New CkDateTime
Dim now As New CkDateTime
success = expires.SetFromTimestamp(expiration)
If (success <> 1) Then
    Debug.Print "Stored expiration is invalid."
    Exit Sub
End If

success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
    Debug.Print "Could not read current time."
    Exit Sub
End If

If (expires.DiffSeconds(now) <= 60) Then
    Debug.Print "Stored credentials are expired or expire within 60 seconds; obtain fresh credentials."
    Exit Sub
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 ChilkatStringBuilder
success = endpoint.Append("s3.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New ChilkatAuthAws
aws.AccessKey = accessKey
aws.SecretKey = secretKey
aws.Region = region
aws.ServiceName = "s3"
aws.SignatureVersion = 4
Dim rest As New ChilkatRest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = 0
success = rest.SetAuthAws(aws)
If (success <> 1) Then
    Debug.Print "Could not configure request signing."
    Exit Sub
End If

'  Keep this verified Socket alive while Rest uses its connection.
Dim connection As New ChilkatSocket
connection.RequireSslCertVerify = 1
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,1,20000)
If (success <> 1) Then
    Debug.Print "TLS connection failed; inspect diagnostics privately."
    Exit Sub
End If

success = rest.UseConnection(connection,1)
If (success <> 1) Then
    Debug.Print "Could not attach TLS connection."
    Exit Sub
End If

Dim xml As New ChilkatXml
xml.Strict = 1
Dim value As String
Dim seenTokens As New ChilkatHashtable
Dim continuation As String
continuation = ""
Dim responseXml As String
Dim page As Long
page = 0
Dim index As Long
Dim more As Long
more = 1
Do While (more = 1)
    If (page = 10000) Then
        Debug.Print "Page bound reached; bucket enumeration is incomplete."
        Exit Sub
    End If

    success = now.SetFromCurrentSystemTime()
    If (success <> 1) Then
        Debug.Print "Could not read current time."
        Exit Sub
    End If

    If (expires.DiffSeconds(now) <= 60) Then
        Debug.Print "Credentials are expiring; obtain fresh credentials before continuing the listing."
        Exit Sub
    End If

    page = page + 1
    success = rest.ClearAllQueryParams()
    If (success <> 1) Then
        Debug.Print "Could not clear parameters from the previous page."
        Exit Sub
    End If

    '  All three credential components are required. Never log this signed URL.
    success = rest.AddQueryParam("X-Amz-Security-Token",sessionToken)
    If (success <> 1) Then
        Debug.Print "Could not set X-Amz-Security-Token."
        Exit Sub
    End If

    success = rest.AddQueryParam("max-buckets","100")
    If (success <> 1) Then
        Debug.Print "Could not set max-buckets."
        Exit Sub
    End If

    success = stringCompare.SetString(continuation)
    Dim stringMatch8 As Long
    stringMatch8 = stringCompare.ContentsEqual("",1)
    If (stringMatch8 <> 1) Then
        success = rest.AddQueryParam("continuation-token",continuation)
        If (success <> 1) Then
            Debug.Print "Could not set continuation-token."
            Exit Sub
        End If

    End If

    responseXml = rest.FullRequestNoBody("GET","/")
    If (rest.LastMethodSuccess <> 1) Then
        Debug.Print "S3 request did not complete; enumeration is incomplete."
        Exit Sub
    End If

    success = xml.LoadXml(responseXml)
    If (rest.ResponseStatusCode <> 200) Then
        Debug.Print "S3 HTTP status: " & rest.ResponseStatusCode
        If (success = 1) Then
            value = xml.GetChildContent("Code")
            If (xml.LastMethodSuccess = 1) Then
                Debug.Print "AWS error code: " & value
            End If

            value = xml.GetChildContent("RequestId")
            If (xml.LastMethodSuccess = 1) Then
                Debug.Print "AWS request ID: " & value
            End If

        End If

        Exit Sub
    End If

    If (success <> 1) Then
        Debug.Print "Invalid S3 XML response."
        Exit Sub
    End If

    success = stringCompare.SetString(xml.Tag)
    Dim stringMatch9 As Long
    stringMatch9 = stringCompare.ContentsEqual("ListAllMyBucketsResult",1)
    If (stringMatch9 <> 1) Then
        Debug.Print "Unexpected S3 response root."
        Exit Sub
    End If

    If (xml.HasChildWithTag("Buckets") <> 1) Then
        Debug.Print "Missing Buckets collection."
        Exit Sub
    End If

    index = 0
    Do While (index < xml.NumChildrenAt("Buckets"))
        xml.I = index
        value = xml.GetChildContent("Buckets|Bucket[i]|Name")
        success = stringCompare.SetString(value)
        Dim stringMatch10 As Long
        stringMatch10 = stringCompare.ContentsEqual("",1)
        If ((xml.LastMethodSuccess <> 1) Or (stringMatch10 = 1)) Then
            Debug.Print "Missing or empty Buckets|Bucket[i]|Name."
            Exit Sub
        End If

        Debug.Print "Bucket: " & value
        index = index + 1
    Loop
    continuation = ""
    If (xml.HasChildWithTag("ContinuationToken") = 1) Then
        continuation = xml.GetChildContent("ContinuationToken")
        If (xml.LastMethodSuccess <> 1) Then
            Debug.Print "Invalid continuation token."
            Exit Sub
        End If

    End If

    more = 0
    success = stringCompare.SetString(continuation)
    Dim stringMatch11 As Long
    stringMatch11 = stringCompare.ContentsEqual("",1)
    If (stringMatch11 <> 1) Then
        If (seenTokens.Contains(continuation) = 1) Then
            Debug.Print "Repeated continuation token; enumeration is incomplete."
            Exit Sub
        End If

        success = seenTokens.AddStr(continuation,"seen")
        If (success <> 1) Then
            Debug.Print "Could not track pagination."
            Exit Sub
        End If

        more = 1
    End If

Loop
Debug.Print "Bucket enumeration complete."