Sample code for 30+ languages & platforms
Xojo Plugin Requires Chilkat v11.6.0+

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.

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.
//  Keep this file private and outside public web content/source control.
Dim credentials As New Chilkat.JsonObject
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/sts.json")
If (success <> True) Then
    System.DebugLog("Could not load private STS configuration.")
    Return
End If

success = stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean
stringMatch1 = stringCompare.ContentsEqual("",True)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True)) Then
    System.DebugLog("Missing or invalid access_key.")
    Return
End If

success = stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean
stringMatch2 = stringCompare.ContentsEqual("",True)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True)) Then
    System.DebugLog("Missing or invalid secret_key.")
    Return
End If

Dim expires As New Chilkat.CkDateTime
Dim now As New Chilkat.CkDateTime
Dim region As String
region = "us-west-2"
If (credentials.HasMember("session_token") = True) Then
    success = stringCompare.SetString(credentials.StringOf("session_token"))
    Dim stringMatch3 As Boolean
    stringMatch3 = stringCompare.ContentsEqual("",True)
    If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True)) Then
        System.DebugLog("Missing or invalid session_token.")
        Return
    End If

    success = stringCompare.SetString(credentials.StringOf("expiration"))
    Dim stringMatch4 As Boolean
    stringMatch4 = stringCompare.ContentsEqual("",True)
    If ((credentials.JsonTypeOf("expiration") <> 1) Or (stringMatch4 = True)) Then
        System.DebugLog("Missing or invalid expiration.")
        Return
    End If

    success = expires.SetFromTimestamp(credentials.StringOf("expiration"))
    If (success <> True) Then
        System.DebugLog("Source 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("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.")
        Return
    End If

End If

success = stringCompare.SetString(credentials.StringOf("role_arn"))
Dim stringMatch5 As Boolean
stringMatch5 = stringCompare.ContentsEqual("",True)
If ((credentials.JsonTypeOf("role_arn") <> 1) Or (stringMatch5 = True)) Then
    System.DebugLog("Missing or invalid role_arn.")
    Return
End If

success = stringCompare.SetString(credentials.StringOf("role_session_name"))
Dim stringMatch6 As Boolean
stringMatch6 = stringCompare.ContentsEqual("",True)
If ((credentials.JsonTypeOf("role_session_name") <> 1) Or (stringMatch6 = True)) Then
    System.DebugLog("Missing or invalid role_session_name.")
    Return
End If

Dim identifier As New Chilkat.StringBuilder
success = identifier.Append(credentials.StringOf("role_session_name"))
If ((identifier.Length < 2) Or (identifier.Length > 64)) Then
    System.DebugLog("role_session_name must have 2-64 characters.")
    Return
End If

Dim allowed As New Chilkat.StringBuilder
success = allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
Dim charIndex As Int32
charIndex = 0
While (charIndex < identifier.Length)
    If (allowed.Contains(identifier.GetRange(charIndex,1,False),True) <> True) Then
        System.DebugLog("Invalid character in role_session_name.")
        Return
    End If

    charIndex = charIndex + 1
Wend
Dim roleArn As New Chilkat.StringBuilder
success = roleArn.Append(credentials.StringOf("role_arn"))
If ((roleArn.StartsWith("arn:aws:iam::",True) <> True) Or (roleArn.Contains(":role/",True) <> True)) Then
    System.DebugLog("Use an IAM role ARN in the commercial AWS partition.")
    Return
End If

If (credentials.HasMember("external_id") = True) Then
    success = stringCompare.SetString(credentials.StringOf("external_id"))
    Dim stringMatch7 As Boolean
    stringMatch7 = stringCompare.ContentsEqual("",True)
    If ((credentials.JsonTypeOf("external_id") <> 1) Or (stringMatch7 = True)) Then
        System.DebugLog("Missing or invalid external_id.")
        Return
    End If

End If

If (credentials.HasMember("source_identity") = True) Then
    success = stringCompare.SetString(credentials.StringOf("source_identity"))
    Dim stringMatch8 As Boolean
    stringMatch8 = stringCompare.ContentsEqual("",True)
    If ((credentials.JsonTypeOf("source_identity") <> 1) Or (stringMatch8 = True)) Then
        System.DebugLog("Missing or invalid source_identity.")
        Return
    End If

End If

//  MFA fields are optional as a pair. Preserve a leading zero in the code.
If ((credentials.HasMember("mfa_serial") = True) Or (credentials.HasMember("mfa_code") = True)) Then
    success = stringCompare.SetString(credentials.StringOf("mfa_serial"))
    Dim stringMatch9 As Boolean
    stringMatch9 = stringCompare.ContentsEqual("",True)
    If ((credentials.JsonTypeOf("mfa_serial") <> 1) Or (stringMatch9 = True)) Then
        System.DebugLog("Missing or invalid mfa_serial.")
        Return
    End If

    success = stringCompare.SetString(credentials.StringOf("mfa_code"))
    Dim stringMatch10 As Boolean
    stringMatch10 = stringCompare.ContentsEqual("",True)
    If ((credentials.JsonTypeOf("mfa_code") <> 1) Or (stringMatch10 = True)) Then
        System.DebugLog("Missing or invalid mfa_code.")
        Return
    End If

    Dim mfaCode As New Chilkat.StringBuilder
    success = mfaCode.Append(credentials.StringOf("mfa_code"))
    If (mfaCode.Length <> 6) Then
        System.DebugLog("mfa_code must be a six-digit string.")
        Return
    End If

    Dim digits As New Chilkat.StringBuilder
    success = digits.Append("0123456789")
    Dim digitIndex As Int32
    digitIndex = 0
    While (digitIndex < 6)
        If (digits.Contains(mfaCode.GetRange(digitIndex,1,False),True) <> True) Then
            System.DebugLog("mfa_code must contain only ASCII digits.")
            Return
        End If

        digitIndex = digitIndex + 1
    Wend
End If

Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append("sts.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New Chilkat.AuthAws
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 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 accessKey As String
Dim secretKey As String
Dim sessionToken As String
Dim expiration As String
success = rest.ClearAllQueryParams()
If (success <> True) Then
    System.DebugLog("Could not clear request parameters.")
    Return
End If

success = rest.AddQueryParam("Action","AssumeRole")
If (success <> True) Then
    System.DebugLog("Could not set Action.")
    Return
End If

success = rest.AddQueryParam("Version","2011-06-15")
If (success <> True) Then
    System.DebugLog("Could not set Version.")
    Return
End If

success = rest.AddQueryParam("DurationSeconds","3600")
If (success <> True) Then
    System.DebugLog("Could not set DurationSeconds.")
    Return
End If

If (credentials.HasMember("session_token") = True) Then
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
    If (success <> True) Then
        System.DebugLog("Could not set X-Amz-Security-Token.")
        Return
    End If

End If

success = rest.AddQueryParam("RoleArn",credentials.StringOf("role_arn"))
If (success <> True) Then
    System.DebugLog("Could not set RoleArn.")
    Return
End If

success = rest.AddQueryParam("RoleSessionName",credentials.StringOf("role_session_name"))
If (success <> True) Then
    System.DebugLog("Could not set RoleSessionName.")
    Return
End If

//  A session policy only restricts the role; it cannot add permissions.
Dim policy As New Chilkat.JsonObject
success = policy.UpdateString("Version","2012-10-17")
If (success <> True) Then
    System.DebugLog("Could not set policy version.")
    Return
End If

success = policy.UpdateString("Statement[0].Effect","Allow")
If (success <> True) Then
    System.DebugLog("Could not set policy effect.")
    Return
End If

success = policy.UpdateString("Statement[0].Action","s3:ListAllMyBuckets")
If (success <> True) Then
    System.DebugLog("Could not set policy action.")
    Return
End If

success = policy.UpdateString("Statement[0].Resource","*")
If (success <> True) Then
    System.DebugLog("Could not set policy resource.")
    Return
End If

success = rest.AddQueryParam("Policy",policy.Emit())
If (success <> True) Then
    System.DebugLog("Could not set Policy.")
    Return
End If

If (credentials.HasMember("external_id") = True) Then
    success = rest.AddQueryParam("ExternalId",credentials.StringOf("external_id"))
    If (success <> True) Then
        System.DebugLog("Could not set ExternalId.")
        Return
    End If

End If

If (credentials.HasMember("source_identity") = True) Then
    success = rest.AddQueryParam("SourceIdentity",credentials.StringOf("source_identity"))
    If (success <> True) Then
        System.DebugLog("Could not set SourceIdentity.")
        Return
    End If

End If

If (credentials.HasMember("mfa_serial") = True) Then
    success = rest.AddQueryParam("SerialNumber",credentials.StringOf("mfa_serial"))
    If (success <> True) Then
        System.DebugLog("Could not set SerialNumber.")
        Return
    End If

    success = rest.AddQueryParam("TokenCode",credentials.StringOf("mfa_code"))
    If (success <> True) Then
        System.DebugLog("Could not set TokenCode.")
        Return
    End If

End If

Dim responseXml As String
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> True) Then
    System.DebugLog("STS request did not complete; no credentials were saved. Inspect diagnostics privately.")
    Return
End If

success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
    System.DebugLog("STS HTTP status: " + Str(rest.ResponseStatusCode))
    If (success = True) Then
        value = xml.GetChildContent("Error|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

    //  Full bodies, headers, and diagnostics can contain sensitive data.
    Return
End If

If (success <> True) Then
    System.DebugLog("Invalid STS XML response; no credentials were saved.")
    Return
End If

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

value = xml.GetChildContent("ResponseMetadata|RequestId")
success = stringCompare.SetString(value)
Dim stringMatch12 As Boolean
stringMatch12 = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch12 = True)) Then
    System.DebugLog("Missing or empty ResponseMetadata|RequestId.")
    Return
End If

System.DebugLog("AWS request ID: " + value)
accessKey = xml.GetChildContent("AssumeRoleResult|Credentials|AccessKeyId")
success = stringCompare.SetString(accessKey)
Dim stringMatch13 As Boolean
stringMatch13 = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch13 = True)) Then
    System.DebugLog("Missing or empty AssumeRoleResult|Credentials|AccessKeyId.")
    Return
End If

secretKey = xml.GetChildContent("AssumeRoleResult|Credentials|SecretAccessKey")
success = stringCompare.SetString(secretKey)
Dim stringMatch14 As Boolean
stringMatch14 = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch14 = True)) Then
    System.DebugLog("Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.")
    Return
End If

sessionToken = xml.GetChildContent("AssumeRoleResult|Credentials|SessionToken")
success = stringCompare.SetString(sessionToken)
Dim stringMatch15 As Boolean
stringMatch15 = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch15 = True)) Then
    System.DebugLog("Missing or empty AssumeRoleResult|Credentials|SessionToken.")
    Return
End If

expiration = xml.GetChildContent("AssumeRoleResult|Credentials|Expiration")
success = stringCompare.SetString(expiration)
Dim stringMatch16 As Boolean
stringMatch16 = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch16 = True)) Then
    System.DebugLog("Missing or empty AssumeRoleResult|Credentials|Expiration.")
    Return
End If

success = expires.SetFromTimestamp(expiration)
If (success <> True) Then
    System.DebugLog("Returned 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("Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.")
    Return
End If

value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|Arn")
success = stringCompare.SetString(value)
Dim stringMatch17 As Boolean
stringMatch17 = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch17 = True)) Then
    System.DebugLog("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.")
    Return
End If

value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
success = stringCompare.SetString(value)
Dim stringMatch18 As Boolean
stringMatch18 = stringCompare.ContentsEqual("",True)
If ((xml.LastMethodSuccess <> True) Or (stringMatch18 = True)) Then
    System.DebugLog("Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.")
    Return
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 <> True) Then
    System.DebugLog("Could not save the private credential file; do not assume it was updated.")
    Return
End If

System.DebugLog("Temporary credentials saved privately; expiration: " + expiration)