AWS STS: Assume a Role for S3 Bucket Listing
See more AWS Security Token Service Examples
Uses Chilkat.Rest and AuthAws with AWS Signature Version 4. STS uses the Query API version 2011-06-15; that version date is still current. The examples send URL-encoded POST forms rather than operation parameters in a GET URL. They use the commercial-partition regional endpoint sts.us-west-2.amazonaws.com and matching signing region/service sts, with explicit TLS certificate verification. Choose the appropriate region/partition endpoint for your deployment.
Load private qa_data/aws/sts.json with nonempty string fields access_key and secret_key. These examples do not discover credentials, assume roles implicitly, or refresh credentials automatically. No access key, secret key, token, full XML response or diagnostic dump is printed.
Both credential-producing examples retain the existing handoff file qa_data/tokens/aws_session_token.xml. It contains plaintext credentials: pre-create a private directory with restrictive OS permissions and keep it out of web roots, source control, shared logs and shared storage. The sample checks the write, but does not set ACLs, encrypt the file, perform atomic replacement, or coordinate concurrent writers. Prefer in-memory handoff or an appropriate credential store in production. A failed request can leave an older file in place; do not assume a failed run refreshed it. The consumer validates expiration, allowing a 60-second margin.
Set role_arn and role_session_name in the private configuration. Names must contain 2–64 allowed characters. The target trust policy and applicable caller authorization must permit AssumeRole. The sample's session policy permits only s3:ListAllMyBuckets, intersected with the role's permissions, for use by the companion S3 listing example; it cannot elevate the role's access. Other policy types, denies and resource-based rules still participate in authorization.
The fixed 3600-second request works within the one-hour role-chaining ceiling and must still fit the role's configured maximum. For temporary source credentials, also provide nonempty session_token and ISO 8601 expiration. The token is included in the signed form body. Optional external_id must be the value agreed with the role owner; it is not a password. Optional source_identity is subject to AWS syntax, trust conditions and sts:SetSourceIdentity permission. Optional MFA uses mfa_serial/mfa_code as a pair. These optional values must satisfy the actual trust policy.
This focused example omits managed session policies and session tags. When adding them, configure the required policies and tagging permissions, and account for inherited transitive tags during role chaining. STS session-token sizes are variable; preserve the complete value without a fixed buffer or truncation.
Chilkat Visual Basic 6.0 Downloads
Dim success As Long
success = 0
Dim stringCompare As New ChilkatStringBuilder
' Assumes Chilkat is unlocked. See Global Unlock Sample.
' Keep this file private and outside public web content/source control.
Dim credentials As New ChilkatJsonObject
credentials.Strict = 1
success = credentials.LoadFile("qa_data/aws/sts.json")
If (success <> 1) Then
Debug.Print "Could not load private STS configuration."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Long
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = 1)) Then
Debug.Print "Missing or invalid access_key."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Long
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = 1)) Then
Debug.Print "Missing or invalid secret_key."
Exit Sub
End If
Dim expires As New CkDateTime
Dim now As New CkDateTime
Dim region As String
region = "us-west-2"
If (credentials.HasMember("session_token") = 1) Then
success = stringCompare.SetString(credentials.StringOf("session_token"))
Dim stringMatch3 As Long
stringMatch3 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = 1)) Then
Debug.Print "Missing or invalid session_token."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("expiration"))
Dim stringMatch4 As Long
stringMatch4 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("expiration") <> 1) Or (stringMatch4 = 1)) Then
Debug.Print "Missing or invalid expiration."
Exit Sub
End If
success = expires.SetFromTimestamp(credentials.StringOf("expiration"))
If (success <> 1) Then
Debug.Print "Source 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 "Source credentials are expired or expire within 60 seconds; obtain fresh credentials."
Exit Sub
End If
End If
success = stringCompare.SetString(credentials.StringOf("role_arn"))
Dim stringMatch5 As Long
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("role_arn") <> 1) Or (stringMatch5 = 1)) Then
Debug.Print "Missing or invalid role_arn."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("role_session_name"))
Dim stringMatch6 As Long
stringMatch6 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("role_session_name") <> 1) Or (stringMatch6 = 1)) Then
Debug.Print "Missing or invalid role_session_name."
Exit Sub
End If
Dim identifier As New ChilkatStringBuilder
success = identifier.Append(credentials.StringOf("role_session_name"))
If ((identifier.Length < 2) Or (identifier.Length > 64)) Then
Debug.Print "role_session_name must have 2-64 characters."
Exit Sub
End If
Dim allowed As New ChilkatStringBuilder
success = allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
Dim charIndex As Long
charIndex = 0
Do While (charIndex < identifier.Length)
If (allowed.Contains(identifier.GetRange(charIndex,1,0),1) <> 1) Then
Debug.Print "Invalid character in role_session_name."
Exit Sub
End If
charIndex = charIndex + 1
Loop
Dim roleArn As New ChilkatStringBuilder
success = roleArn.Append(credentials.StringOf("role_arn"))
If ((roleArn.StartsWith("arn:aws:iam::",1) <> 1) Or (roleArn.Contains(":role/",1) <> 1)) Then
Debug.Print "Use an IAM role ARN in the commercial AWS partition."
Exit Sub
End If
If (credentials.HasMember("external_id") = 1) Then
success = stringCompare.SetString(credentials.StringOf("external_id"))
Dim stringMatch7 As Long
stringMatch7 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("external_id") <> 1) Or (stringMatch7 = 1)) Then
Debug.Print "Missing or invalid external_id."
Exit Sub
End If
End If
If (credentials.HasMember("source_identity") = 1) Then
success = stringCompare.SetString(credentials.StringOf("source_identity"))
Dim stringMatch8 As Long
stringMatch8 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("source_identity") <> 1) Or (stringMatch8 = 1)) Then
Debug.Print "Missing or invalid source_identity."
Exit Sub
End If
End If
' MFA fields are optional as a pair. Preserve a leading zero in the code.
If ((credentials.HasMember("mfa_serial") = 1) Or (credentials.HasMember("mfa_code") = 1)) Then
success = stringCompare.SetString(credentials.StringOf("mfa_serial"))
Dim stringMatch9 As Long
stringMatch9 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("mfa_serial") <> 1) Or (stringMatch9 = 1)) Then
Debug.Print "Missing or invalid mfa_serial."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("mfa_code"))
Dim stringMatch10 As Long
stringMatch10 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("mfa_code") <> 1) Or (stringMatch10 = 1)) Then
Debug.Print "Missing or invalid mfa_code."
Exit Sub
End If
Dim mfaCode As New ChilkatStringBuilder
success = mfaCode.Append(credentials.StringOf("mfa_code"))
If (mfaCode.Length <> 6) Then
Debug.Print "mfa_code must be a six-digit string."
Exit Sub
End If
Dim digits As New ChilkatStringBuilder
success = digits.Append("0123456789")
Dim digitIndex As Long
digitIndex = 0
Do While (digitIndex < 6)
If (digits.Contains(mfaCode.GetRange(digitIndex,1,0),1) <> 1) Then
Debug.Print "mfa_code must contain only ASCII digits."
Exit Sub
End If
digitIndex = digitIndex + 1
Loop
End If
Dim endpoint As New ChilkatStringBuilder
success = endpoint.Append("sts.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New ChilkatAuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sts"
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 accessKey As String
Dim secretKey As String
Dim sessionToken As String
Dim expiration As String
success = rest.ClearAllQueryParams()
If (success <> 1) Then
Debug.Print "Could not clear request parameters."
Exit Sub
End If
success = rest.AddQueryParam("Action","AssumeRole")
If (success <> 1) Then
Debug.Print "Could not set Action."
Exit Sub
End If
success = rest.AddQueryParam("Version","2011-06-15")
If (success <> 1) Then
Debug.Print "Could not set Version."
Exit Sub
End If
success = rest.AddQueryParam("DurationSeconds","3600")
If (success <> 1) Then
Debug.Print "Could not set DurationSeconds."
Exit Sub
End If
If (credentials.HasMember("session_token") = 1) Then
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
If (success <> 1) Then
Debug.Print "Could not set X-Amz-Security-Token."
Exit Sub
End If
End If
success = rest.AddQueryParam("RoleArn",credentials.StringOf("role_arn"))
If (success <> 1) Then
Debug.Print "Could not set RoleArn."
Exit Sub
End If
success = rest.AddQueryParam("RoleSessionName",credentials.StringOf("role_session_name"))
If (success <> 1) Then
Debug.Print "Could not set RoleSessionName."
Exit Sub
End If
' A session policy only restricts the role; it cannot add permissions.
Dim policy As New ChilkatJsonObject
success = policy.UpdateString("Version","2012-10-17")
If (success <> 1) Then
Debug.Print "Could not set policy version."
Exit Sub
End If
success = policy.UpdateString("Statement[0].Effect","Allow")
If (success <> 1) Then
Debug.Print "Could not set policy effect."
Exit Sub
End If
success = policy.UpdateString("Statement[0].Action","s3:ListAllMyBuckets")
If (success <> 1) Then
Debug.Print "Could not set policy action."
Exit Sub
End If
success = policy.UpdateString("Statement[0].Resource","*")
If (success <> 1) Then
Debug.Print "Could not set policy resource."
Exit Sub
End If
success = rest.AddQueryParam("Policy",policy.Emit())
If (success <> 1) Then
Debug.Print "Could not set Policy."
Exit Sub
End If
If (credentials.HasMember("external_id") = 1) Then
success = rest.AddQueryParam("ExternalId",credentials.StringOf("external_id"))
If (success <> 1) Then
Debug.Print "Could not set ExternalId."
Exit Sub
End If
End If
If (credentials.HasMember("source_identity") = 1) Then
success = rest.AddQueryParam("SourceIdentity",credentials.StringOf("source_identity"))
If (success <> 1) Then
Debug.Print "Could not set SourceIdentity."
Exit Sub
End If
End If
If (credentials.HasMember("mfa_serial") = 1) Then
success = rest.AddQueryParam("SerialNumber",credentials.StringOf("mfa_serial"))
If (success <> 1) Then
Debug.Print "Could not set SerialNumber."
Exit Sub
End If
success = rest.AddQueryParam("TokenCode",credentials.StringOf("mfa_code"))
If (success <> 1) Then
Debug.Print "Could not set TokenCode."
Exit Sub
End If
End If
Dim responseXml As String
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> 1) Then
Debug.Print "STS request did not complete; no credentials were saved. Inspect diagnostics privately."
Exit Sub
End If
success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
Debug.Print "STS HTTP status: " & rest.ResponseStatusCode
If (success = 1) Then
value = xml.GetChildContent("Error|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
' Full bodies, headers, and diagnostics can contain sensitive data.
Exit Sub
End If
If (success <> 1) Then
Debug.Print "Invalid STS XML response; no credentials were saved."
Exit Sub
End If
success = stringCompare.SetString(xml.Tag)
Dim stringMatch11 As Long
stringMatch11 = stringCompare.ContentsEqual("AssumeRoleResponse",1)
If (stringMatch11 <> 1) Then
Debug.Print "Unexpected STS response root."
Exit Sub
End If
value = xml.GetChildContent("ResponseMetadata|RequestId")
success = stringCompare.SetString(value)
Dim stringMatch12 As Long
stringMatch12 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch12 = 1)) Then
Debug.Print "Missing or empty ResponseMetadata|RequestId."
Exit Sub
End If
Debug.Print "AWS request ID: " & value
accessKey = xml.GetChildContent("AssumeRoleResult|Credentials|AccessKeyId")
success = stringCompare.SetString(accessKey)
Dim stringMatch13 As Long
stringMatch13 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch13 = 1)) Then
Debug.Print "Missing or empty AssumeRoleResult|Credentials|AccessKeyId."
Exit Sub
End If
secretKey = xml.GetChildContent("AssumeRoleResult|Credentials|SecretAccessKey")
success = stringCompare.SetString(secretKey)
Dim stringMatch14 As Long
stringMatch14 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch14 = 1)) Then
Debug.Print "Missing or empty AssumeRoleResult|Credentials|SecretAccessKey."
Exit Sub
End If
sessionToken = xml.GetChildContent("AssumeRoleResult|Credentials|SessionToken")
success = stringCompare.SetString(sessionToken)
Dim stringMatch15 As Long
stringMatch15 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch15 = 1)) Then
Debug.Print "Missing or empty AssumeRoleResult|Credentials|SessionToken."
Exit Sub
End If
expiration = xml.GetChildContent("AssumeRoleResult|Credentials|Expiration")
success = stringCompare.SetString(expiration)
Dim stringMatch16 As Long
stringMatch16 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch16 = 1)) Then
Debug.Print "Missing or empty AssumeRoleResult|Credentials|Expiration."
Exit Sub
End If
success = expires.SetFromTimestamp(expiration)
If (success <> 1) Then
Debug.Print "Returned 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 "Returned credentials are expired or expire within 60 seconds; obtain fresh credentials."
Exit Sub
End If
value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|Arn")
success = stringCompare.SetString(value)
Dim stringMatch17 As Long
stringMatch17 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch17 = 1)) Then
Debug.Print "Missing or empty AssumeRoleResult|AssumedRoleUser|Arn."
Exit Sub
End If
value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
success = stringCompare.SetString(value)
Dim stringMatch18 As Long
stringMatch18 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch18 = 1)) Then
Debug.Print "Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId."
Exit Sub
End If
' Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
' Reuses the existing handoff filename for the companion S3 example.
success = xml.SaveXml("qa_data/tokens/aws_session_token.xml")
If (success <> 1) Then
Debug.Print "Could not save the private credential file; do not assume it was updated."
Exit Sub
End If
Debug.Print "Temporary credentials saved privately; expiration: " & expiration