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

AWS STS: Refresh an AssumeRole Session Before Expiration

See more AWS Security Token Service Examples

Uses the AWS STS Query API version 2011-06-15 and a verified TLS connection to the commercial-partition regional endpoint sts.us-west-2.amazonaws.com. Change the endpoint and signing region together for your deployment. Assumes Chilkat is unlocked.

Keep qa_data/aws/sts.json private and outside web roots/source control. Signed examples require nonempty access_key and secret_key strings; temporary source credentials also require session_token and ISO 8601 expiration. Federation exchanges load their specific fields without AWS keys. The examples do not print credentials, bearer tokens, full responses or diagnostic dumps. Credential-producing examples build a complete in-memory session object with access_key, secret_key, session_token and expiration; integrate that object into your application before it goes out of scope.

Configure source credentials, role_arn and role_session_name for an unattended role that does not require interactive MFA. Optional qa_data/tokens/sts_session.json holds a previous normalized session for exactly that role, session configuration and workload; keep this cache private and never reuse it across roles. A complete cached set with more than five minutes remaining is reused. Otherwise obtains a new one-hour session, validates it, and publishes one serialized in-memory snapshot. No cache file is overwritten. Existing credentials cannot be extended.

Retries throttling and selected transient HTTP errors at most three times with one- and two-second waits, rebuilding the signed form and checking source expiration on each attempt. Transport, authorization and invalid-response failures stop without publication. Add jitter, synchronization and a credential provider appropriate to your runtime in a concurrent application. This single-thread sample does not implement shared-cache locking or reuse expired sources/MFA codes. Repeat the refresh decision before each unit of work.

AWS references: AssumeRole

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
If ((credentials.HasMember("mfa_code") = True) Or (credentials.HasMember("mfa_serial") = True)) Then
    System.DebugLog("This unattended refresh example does not reuse MFA codes.")
    Return
End If

//  Optional private cache contains only the four normalized session fields.
//  In an application, keep activeSnapshot in memory between units of work.
Dim files As New Chilkat.FileAccess
Dim cached As New Chilkat.JsonObject
cached.Strict = True
Dim activeSnapshot As String
activeSnapshot = ""
Dim refreshRequired As Boolean
refreshRequired = True
If (files.FileExists("qa_data/tokens/sts_session.json") = True) Then
    success = cached.LoadFile("qa_data/tokens/sts_session.json")
    If (success <> True) Then
        System.DebugLog("Invalid private cache.")
        Return
    End If

    success = stringCompare.SetString(cached.StringOf("access_key"))
    Dim stringMatch7 As Boolean
    stringMatch7 = stringCompare.ContentsEqual("",True)
    If ((cached.JsonTypeOf("access_key") <> 1) Or (stringMatch7 = True)) Then
        System.DebugLog("Incomplete private cache.")
        Return
    End If

    success = stringCompare.SetString(cached.StringOf("secret_key"))
    Dim stringMatch8 As Boolean
    stringMatch8 = stringCompare.ContentsEqual("",True)
    If ((cached.JsonTypeOf("secret_key") <> 1) Or (stringMatch8 = True)) Then
        System.DebugLog("Incomplete private cache.")
        Return
    End If

    success = stringCompare.SetString(cached.StringOf("session_token"))
    Dim stringMatch9 As Boolean
    stringMatch9 = stringCompare.ContentsEqual("",True)
    If ((cached.JsonTypeOf("session_token") <> 1) Or (stringMatch9 = True)) Then
        System.DebugLog("Incomplete private cache.")
        Return
    End If

    success = stringCompare.SetString(cached.StringOf("expiration"))
    Dim stringMatch10 As Boolean
    stringMatch10 = stringCompare.ContentsEqual("",True)
    If ((cached.JsonTypeOf("expiration") <> 1) Or (stringMatch10 = True)) Then
        System.DebugLog("Incomplete private cache.")
        Return
    End If

    success = expires.SetFromTimestamp(cached.StringOf("expiration"))
    If (success <> True) Then
        System.DebugLog("Invalid cached expiration.")
        Return
    End If

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

    If (expires.DiffSeconds(now) > 300) Then
        activeSnapshot = cached.Emit()
        refreshRequired = False
    End If

End If

If (refreshRequired = True) Then
    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
    Dim responseXml As String
    responseXml = ""
    Dim attempt As Int32
    attempt = 0
    Dim delayMs As Int32
    delayMs = 1000
    Dim received As Boolean
    received = False
    Dim retryable As Boolean
    While ((attempt < 3) And (received = False))
        If (credentials.HasMember("session_token") = True) Then
            success = stringCompare.SetString(credentials.StringOf("session_token"))
            Dim stringMatch11 As Boolean
            stringMatch11 = stringCompare.ContentsEqual("",True)
            If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch11 = True)) Then
                System.DebugLog("Missing or invalid session_token.")
                Return
            End If

            success = stringCompare.SetString(credentials.StringOf("expiration"))
            Dim stringMatch12 As Boolean
            stringMatch12 = stringCompare.ContentsEqual("",True)
            If ((credentials.JsonTypeOf("expiration") <> 1) Or (stringMatch12 = 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

        attempt = attempt + 1
        success = rest.ClearAllQueryParams()
        If (success <> True) Then
            System.DebugLog("Could not reset 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

        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

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

        responseXml = rest.FullRequestFormUrlEncoded("POST","/")
        If (rest.LastMethodSuccess <> True) Then
            System.DebugLog("Transport failed; credential refresh was not published.")
            Return
        End If

        If (rest.ResponseStatusCode = 200) Then
            received = True
        End If

        If (rest.ResponseStatusCode <> 200) Then
            retryable = False
            value = ""
            success = xml.LoadXml(responseXml)
            If (success = True) Then
                value = xml.GetChildContent("Error|Code")
            End If

            success = stringCompare.SetString(value)
            Dim stringMatch13 As Boolean
            stringMatch13 = stringCompare.ContentsEqual("Throttling",True)
            success = stringCompare.SetString(value)
            Dim stringMatch14 As Boolean
            stringMatch14 = stringCompare.ContentsEqual("ThrottlingException",True)
            If ((rest.ResponseStatusCode = 429) Or (rest.ResponseStatusCode = 500) Or (rest.ResponseStatusCode = 502) Or (rest.ResponseStatusCode = 503) Or (rest.ResponseStatusCode = 504) Or (stringMatch13 = True) Or (stringMatch14 = True)) Then
                retryable = True
            End If

            If ((retryable <> True) Or (attempt = 3)) Then
                System.DebugLog("Refresh failed. HTTP status: " + Str(rest.ResponseStatusCode))
                System.DebugLog("AWS error code: " + value)
                Return
            End If

            connection.SleepMs delayMs
            delayMs = delayMs * 2
        End If

    Wend
    If (received <> True) Then
        System.DebugLog("Refresh attempts exhausted.")
        Return
    End If

    success = xml.LoadXml(responseXml)
    If (success <> True) Then
        System.DebugLog("Invalid STS XML response.")
        Return
    End If

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

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

    If (xml.HasChildWithTag("AssumeRoleResult") <> True) Then
        System.DebugLog("Missing STS result.")
        Return
    End If

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

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

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

    expiration = xml.GetChildContent("AssumeRoleResult|Credentials|Expiration")
    success = stringCompare.SetString(expiration)
    Dim stringMatch20 As Boolean
    stringMatch20 = stringCompare.ContentsEqual("",True)
    If ((xml.LastMethodSuccess <> True) Or (stringMatch20 = 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 stringMatch21 As Boolean
    stringMatch21 = stringCompare.ContentsEqual("",True)
    If ((xml.LastMethodSuccess <> True) Or (stringMatch21 = True)) Then
        System.DebugLog("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.")
        Return
    End If

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

    Dim session As New Chilkat.JsonObject
    success = session.UpdateString("access_key",accessKey)
    If (success <> True) Then
        System.DebugLog("Could not build complete session.")
        Return
    End If

    success = session.UpdateString("secret_key",secretKey)
    If (success <> True) Then
        System.DebugLog("Could not build complete session.")
        Return
    End If

    success = session.UpdateString("session_token",sessionToken)
    If (success <> True) Then
        System.DebugLog("Could not build complete session.")
        Return
    End If

    success = session.UpdateString("expiration",expiration)
    If (success <> True) Then
        System.DebugLog("Could not build complete session.")
        Return
    End If

    //  Use session in memory; do not print or log session.Emit().
    System.DebugLog("Session validated; expiration: " + expiration)
    //  Publish one complete snapshot only after validating every returned field.
    activeSnapshot = session.Emit()
End If

//  Rehydrate a complete set for the next unit of work, never four partial updates.
Dim usable As New Chilkat.JsonObject
usable.Strict = True
success = usable.Load(activeSnapshot)
If (success <> True) Then
    System.DebugLog("Could not load the complete session snapshot.")
    Return
End If

//  Pass usable to your service client here. Do not log activeSnapshot.
System.DebugLog("Session ready for the next unit of work; expiration: " + usable.StringOf("expiration"))
System.DebugLog("Example completed.")