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

VBScript
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)

success = 0

set stringCompare = CreateObject("Chilkat.StringBuilder")
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Keep this file private and outside public web content/source control.
set credentials = CreateObject("Chilkat.JsonObject")
credentials.Strict = 1
success = credentials.LoadFile("qa_data/aws/sts.json")
If (success <> 1) Then
    outFile.WriteLine("Could not load private STS configuration.")
    WScript.Quit
End If

success = stringCompare.SetString(credentials.StringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = 1)) Then
    outFile.WriteLine("Missing or invalid access_key.")
    WScript.Quit
End If

success = stringCompare.SetString(credentials.StringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = 1)) Then
    outFile.WriteLine("Missing or invalid secret_key.")
    WScript.Quit
End If

set expires = CreateObject("Chilkat.CkDateTime")
set now = CreateObject("Chilkat.CkDateTime")
region = "us-west-2"
If (credentials.HasMember("session_token") = 1) Then
    success = stringCompare.SetString(credentials.StringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",1)
    If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = 1)) Then
        outFile.WriteLine("Missing or invalid session_token.")
        WScript.Quit
    End If

    success = stringCompare.SetString(credentials.StringOf("expiration"))
    stringMatch4 = stringCompare.ContentsEqual("",1)
    If ((credentials.JsonTypeOf("expiration") <> 1) Or (stringMatch4 = 1)) Then
        outFile.WriteLine("Missing or invalid expiration.")
        WScript.Quit
    End If

    success = expires.SetFromTimestamp(credentials.StringOf("expiration"))
    If (success <> 1) Then
        outFile.WriteLine("Source expiration is invalid.")
        WScript.Quit
    End If

    success = now.SetFromCurrentSystemTime()
    If (success <> 1) Then
        outFile.WriteLine("Could not read current time.")
        WScript.Quit
    End If

    If (expires.DiffSeconds(now) <= 60) Then
        outFile.WriteLine("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.")
        WScript.Quit
    End If

End If

success = stringCompare.SetString(credentials.StringOf("role_arn"))
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("role_arn") <> 1) Or (stringMatch5 = 1)) Then
    outFile.WriteLine("Missing or invalid role_arn.")
    WScript.Quit
End If

success = stringCompare.SetString(credentials.StringOf("role_session_name"))
stringMatch6 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("role_session_name") <> 1) Or (stringMatch6 = 1)) Then
    outFile.WriteLine("Missing or invalid role_session_name.")
    WScript.Quit
End If

set identifier = CreateObject("Chilkat.StringBuilder")
success = identifier.Append(credentials.StringOf("role_session_name"))
If ((identifier.Length < 2) Or (identifier.Length > 64)) Then
    outFile.WriteLine("role_session_name must have 2-64 characters.")
    WScript.Quit
End If

set allowed = CreateObject("Chilkat.StringBuilder")
success = allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
charIndex = 0
Do While (charIndex < identifier.Length)
    If (allowed.Contains(identifier.GetRange(charIndex,1,0),1) <> 1) Then
        outFile.WriteLine("Invalid character in role_session_name.")
        WScript.Quit
    End If

    charIndex = charIndex + 1
Loop
If ((credentials.HasMember("mfa_code") = 1) Or (credentials.HasMember("mfa_serial") = 1)) Then
    outFile.WriteLine("This unattended refresh example does not reuse MFA codes.")
    WScript.Quit
End If

'  Optional private cache contains only the four normalized session fields.
'  In an application, keep activeSnapshot in memory between units of work.
set files = CreateObject("Chilkat.FileAccess")
set cached = CreateObject("Chilkat.JsonObject")
cached.Strict = 1
activeSnapshot = ""
refreshRequired = 1
If (files.FileExists("qa_data/tokens/sts_session.json") = 1) Then
    success = cached.LoadFile("qa_data/tokens/sts_session.json")
    If (success <> 1) Then
        outFile.WriteLine("Invalid private cache.")
        WScript.Quit
    End If

    success = stringCompare.SetString(cached.StringOf("access_key"))
    stringMatch7 = stringCompare.ContentsEqual("",1)
    If ((cached.JsonTypeOf("access_key") <> 1) Or (stringMatch7 = 1)) Then
        outFile.WriteLine("Incomplete private cache.")
        WScript.Quit
    End If

    success = stringCompare.SetString(cached.StringOf("secret_key"))
    stringMatch8 = stringCompare.ContentsEqual("",1)
    If ((cached.JsonTypeOf("secret_key") <> 1) Or (stringMatch8 = 1)) Then
        outFile.WriteLine("Incomplete private cache.")
        WScript.Quit
    End If

    success = stringCompare.SetString(cached.StringOf("session_token"))
    stringMatch9 = stringCompare.ContentsEqual("",1)
    If ((cached.JsonTypeOf("session_token") <> 1) Or (stringMatch9 = 1)) Then
        outFile.WriteLine("Incomplete private cache.")
        WScript.Quit
    End If

    success = stringCompare.SetString(cached.StringOf("expiration"))
    stringMatch10 = stringCompare.ContentsEqual("",1)
    If ((cached.JsonTypeOf("expiration") <> 1) Or (stringMatch10 = 1)) Then
        outFile.WriteLine("Incomplete private cache.")
        WScript.Quit
    End If

    success = expires.SetFromTimestamp(cached.StringOf("expiration"))
    If (success <> 1) Then
        outFile.WriteLine("Invalid cached expiration.")
        WScript.Quit
    End If

    success = now.SetFromCurrentSystemTime()
    If (success <> 1) Then
        outFile.WriteLine("Could not read current time.")
        WScript.Quit
    End If

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

End If

If (refreshRequired = 1) Then
    set endpoint = CreateObject("Chilkat.StringBuilder")
    success = endpoint.Append("sts.")
    success = endpoint.Append(region)
    success = endpoint.Append(".amazonaws.com")
    set aws = CreateObject("Chilkat.AuthAws")
    aws.AccessKey = credentials.StringOf("access_key")
    aws.SecretKey = credentials.StringOf("secret_key")
    aws.Region = region
    aws.ServiceName = "sts"
    aws.SignatureVersion = 4
    set rest = CreateObject("Chilkat.Rest")
    rest.ConnectTimeoutMs = 20000
    rest.IdleTimeoutMs = 60000
    rest.VerboseLogging = 0
    success = rest.SetAuthAws(aws)
    If (success <> 1) Then
        outFile.WriteLine("Could not configure request signing.")
        WScript.Quit
    End If

    '  Keep this verified Socket alive while Rest uses its connection.
    set connection = CreateObject("Chilkat.Socket")
    connection.RequireSslCertVerify = 1
    connection.MaxReadIdleMs = 60000
    connection.MaxSendIdleMs = 60000
    success = connection.Connect(endpoint.GetAsString(),443,1,20000)
    If (success <> 1) Then
        outFile.WriteLine("TLS connection failed; inspect diagnostics privately.")
        WScript.Quit
    End If

    success = rest.UseConnection(connection,1)
    If (success <> 1) Then
        outFile.WriteLine("Could not attach TLS connection.")
        WScript.Quit
    End If

    set xml = CreateObject("Chilkat.Xml")
    xml.Strict = 1

    responseXml = ""
    attempt = 0
    delayMs = 1000
    received = 0

    Do While ((attempt < 3) And (received = 0))
        If (credentials.HasMember("session_token") = 1) Then
            success = stringCompare.SetString(credentials.StringOf("session_token"))
            stringMatch11 = stringCompare.ContentsEqual("",1)
            If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch11 = 1)) Then
                outFile.WriteLine("Missing or invalid session_token.")
                WScript.Quit
            End If

            success = stringCompare.SetString(credentials.StringOf("expiration"))
            stringMatch12 = stringCompare.ContentsEqual("",1)
            If ((credentials.JsonTypeOf("expiration") <> 1) Or (stringMatch12 = 1)) Then
                outFile.WriteLine("Missing or invalid expiration.")
                WScript.Quit
            End If

            success = expires.SetFromTimestamp(credentials.StringOf("expiration"))
            If (success <> 1) Then
                outFile.WriteLine("Source expiration is invalid.")
                WScript.Quit
            End If

            success = now.SetFromCurrentSystemTime()
            If (success <> 1) Then
                outFile.WriteLine("Could not read current time.")
                WScript.Quit
            End If

            If (expires.DiffSeconds(now) <= 60) Then
                outFile.WriteLine("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.")
                WScript.Quit
            End If

        End If

        attempt = attempt + 1
        success = rest.ClearAllQueryParams()
        If (success <> 1) Then
            outFile.WriteLine("Could not reset request parameters.")
            WScript.Quit
        End If

        success = rest.AddQueryParam("Action","AssumeRole")
        If (success <> 1) Then
            outFile.WriteLine("Could not set Action.")
            WScript.Quit
        End If

        success = rest.AddQueryParam("Version","2011-06-15")
        If (success <> 1) Then
            outFile.WriteLine("Could not set Version.")
            WScript.Quit
        End If

        If (credentials.HasMember("session_token") = 1) Then
            success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
            If (success <> 1) Then
                outFile.WriteLine("Could not set X-Amz-Security-Token.")
                WScript.Quit
            End If

        End If

        success = rest.AddQueryParam("RoleArn",credentials.StringOf("role_arn"))
        If (success <> 1) Then
            outFile.WriteLine("Could not set RoleArn.")
            WScript.Quit
        End If

        success = rest.AddQueryParam("RoleSessionName",credentials.StringOf("role_session_name"))
        If (success <> 1) Then
            outFile.WriteLine("Could not set RoleSessionName.")
            WScript.Quit
        End If

        success = rest.AddQueryParam("DurationSeconds","3600")
        If (success <> 1) Then
            outFile.WriteLine("Could not set DurationSeconds.")
            WScript.Quit
        End If

        responseXml = rest.FullRequestFormUrlEncoded("POST","/")
        If (rest.LastMethodSuccess <> 1) Then
            outFile.WriteLine("Transport failed; credential refresh was not published.")
            WScript.Quit
        End If

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

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

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

            If ((retryable <> 1) Or (attempt = 3)) Then
                outFile.WriteLine("Refresh failed. HTTP status: " & rest.ResponseStatusCode)
                outFile.WriteLine("AWS error code: " & value)
                WScript.Quit
            End If

            connection.SleepMs delayMs
            delayMs = delayMs * 2
        End If

    Loop
    If (received <> 1) Then
        outFile.WriteLine("Refresh attempts exhausted.")
        WScript.Quit
    End If

    success = xml.LoadXml(responseXml)
    If (success <> 1) Then
        outFile.WriteLine("Invalid STS XML response.")
        WScript.Quit
    End If

    success = stringCompare.SetString(xml.Tag)
    stringMatch15 = stringCompare.ContentsEqual("AssumeRoleResponse",1)
    If (stringMatch15 <> 1) Then
        outFile.WriteLine("Unexpected STS response root.")
        WScript.Quit
    End If

    value = xml.GetChildContent("ResponseMetadata|RequestId")
    success = stringCompare.SetString(value)
    stringMatch16 = stringCompare.ContentsEqual("",1)
    If ((xml.LastMethodSuccess <> 1) Or (stringMatch16 = 1)) Then
        outFile.WriteLine("Missing or empty ResponseMetadata|RequestId.")
        WScript.Quit
    End If

    If (xml.HasChildWithTag("AssumeRoleResult") <> 1) Then
        outFile.WriteLine("Missing STS result.")
        WScript.Quit
    End If

    accessKey = xml.GetChildContent("AssumeRoleResult|Credentials|AccessKeyId")
    success = stringCompare.SetString(accessKey)
    stringMatch17 = stringCompare.ContentsEqual("",1)
    If ((xml.LastMethodSuccess <> 1) Or (stringMatch17 = 1)) Then
        outFile.WriteLine("Missing or empty AssumeRoleResult|Credentials|AccessKeyId.")
        WScript.Quit
    End If

    secretKey = xml.GetChildContent("AssumeRoleResult|Credentials|SecretAccessKey")
    success = stringCompare.SetString(secretKey)
    stringMatch18 = stringCompare.ContentsEqual("",1)
    If ((xml.LastMethodSuccess <> 1) Or (stringMatch18 = 1)) Then
        outFile.WriteLine("Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.")
        WScript.Quit
    End If

    sessionToken = xml.GetChildContent("AssumeRoleResult|Credentials|SessionToken")
    success = stringCompare.SetString(sessionToken)
    stringMatch19 = stringCompare.ContentsEqual("",1)
    If ((xml.LastMethodSuccess <> 1) Or (stringMatch19 = 1)) Then
        outFile.WriteLine("Missing or empty AssumeRoleResult|Credentials|SessionToken.")
        WScript.Quit
    End If

    expiration = xml.GetChildContent("AssumeRoleResult|Credentials|Expiration")
    success = stringCompare.SetString(expiration)
    stringMatch20 = stringCompare.ContentsEqual("",1)
    If ((xml.LastMethodSuccess <> 1) Or (stringMatch20 = 1)) Then
        outFile.WriteLine("Missing or empty AssumeRoleResult|Credentials|Expiration.")
        WScript.Quit
    End If

    success = expires.SetFromTimestamp(expiration)
    If (success <> 1) Then
        outFile.WriteLine("Returned expiration is invalid.")
        WScript.Quit
    End If

    success = now.SetFromCurrentSystemTime()
    If (success <> 1) Then
        outFile.WriteLine("Could not read current time.")
        WScript.Quit
    End If

    If (expires.DiffSeconds(now) <= 60) Then
        outFile.WriteLine("Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.")
        WScript.Quit
    End If

    value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|Arn")
    success = stringCompare.SetString(value)
    stringMatch21 = stringCompare.ContentsEqual("",1)
    If ((xml.LastMethodSuccess <> 1) Or (stringMatch21 = 1)) Then
        outFile.WriteLine("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.")
        WScript.Quit
    End If

    value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
    success = stringCompare.SetString(value)
    stringMatch22 = stringCompare.ContentsEqual("",1)
    If ((xml.LastMethodSuccess <> 1) Or (stringMatch22 = 1)) Then
        outFile.WriteLine("Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.")
        WScript.Quit
    End If

    set session = CreateObject("Chilkat.JsonObject")
    success = session.UpdateString("access_key",accessKey)
    If (success <> 1) Then
        outFile.WriteLine("Could not build complete session.")
        WScript.Quit
    End If

    success = session.UpdateString("secret_key",secretKey)
    If (success <> 1) Then
        outFile.WriteLine("Could not build complete session.")
        WScript.Quit
    End If

    success = session.UpdateString("session_token",sessionToken)
    If (success <> 1) Then
        outFile.WriteLine("Could not build complete session.")
        WScript.Quit
    End If

    success = session.UpdateString("expiration",expiration)
    If (success <> 1) Then
        outFile.WriteLine("Could not build complete session.")
        WScript.Quit
    End If

    '  Use session in memory; do not print or log session.Emit().
    outFile.WriteLine("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.
set usable = CreateObject("Chilkat.JsonObject")
usable.Strict = 1
success = usable.Load(activeSnapshot)
If (success <> 1) Then
    outFile.WriteLine("Could not load the complete session snapshot.")
    WScript.Quit
End If

'  Pass usable to your service client here. Do not log activeSnapshot.
outFile.WriteLine("Session ready for the next unit of work; expiration: " & usable.StringOf("expiration"))
outFile.WriteLine("Example completed.")

outFile.Close