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 AutoIt Downloads
Local $bSuccess = False
$oStringCompare = ObjCreate("Chilkat.StringBuilder")
; Assumes Chilkat is unlocked. See Global Unlock Sample.
; Keep this file private and outside public web content/source control.
$oCredentials = ObjCreate("Chilkat.JsonObject")
$oCredentials.Strict = True
$bSuccess = $oCredentials.LoadFile("qa_data/aws/sts.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load private STS configuration." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("access_key"))
Local $bStringMatch1 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("access_key") <> 1) Or ($bStringMatch1 = True)) Then
ConsoleWrite("Missing or invalid access_key." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("secret_key"))
Local $bStringMatch2 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("secret_key") <> 1) Or ($bStringMatch2 = True)) Then
ConsoleWrite("Missing or invalid secret_key." & @CRLF)
Exit
EndIf
$oExpires = ObjCreate("Chilkat.CkDateTime")
$oNow = ObjCreate("Chilkat.CkDateTime")
Local $sRegion = "us-west-2"
If ($oCredentials.HasMember("session_token") = True) Then
$oStringCompare.SetString($oCredentials.StringOf("session_token"))
Local $bStringMatch3 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("session_token") <> 1) Or ($bStringMatch3 = True)) Then
ConsoleWrite("Missing or invalid session_token." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("expiration"))
Local $bStringMatch4 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("expiration") <> 1) Or ($bStringMatch4 = True)) Then
ConsoleWrite("Missing or invalid expiration." & @CRLF)
Exit
EndIf
$bSuccess = $oExpires.SetFromTimestamp($oCredentials.StringOf("expiration"))
If ($bSuccess <> True) Then
ConsoleWrite("Source expiration is invalid." & @CRLF)
Exit
EndIf
$bSuccess = $oNow.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not read current time." & @CRLF)
Exit
EndIf
If ($oExpires.DiffSeconds($oNow) <= 60) Then
ConsoleWrite("Source credentials are expired or expire within 60 seconds; obtain fresh credentials." & @CRLF)
Exit
EndIf
EndIf
$oStringCompare.SetString($oCredentials.StringOf("role_arn"))
Local $bStringMatch5 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("role_arn") <> 1) Or ($bStringMatch5 = True)) Then
ConsoleWrite("Missing or invalid role_arn." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("role_session_name"))
Local $bStringMatch6 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("role_session_name") <> 1) Or ($bStringMatch6 = True)) Then
ConsoleWrite("Missing or invalid role_session_name." & @CRLF)
Exit
EndIf
$oIdentifier = ObjCreate("Chilkat.StringBuilder")
$oIdentifier.Append($oCredentials.StringOf("role_session_name"))
If (($oIdentifier.Length < 2) Or ($oIdentifier.Length > 64)) Then
ConsoleWrite("role_session_name must have 2-64 characters." & @CRLF)
Exit
EndIf
$oAllowed = ObjCreate("Chilkat.StringBuilder")
$oAllowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
Local $iCharIndex = 0
While ($iCharIndex < $oIdentifier.Length)
If ($oAllowed.Contains($oIdentifier.GetRange($iCharIndex,1,False),True) <> True) Then
ConsoleWrite("Invalid character in role_session_name." & @CRLF)
Exit
EndIf
$iCharIndex = $iCharIndex + 1
Wend
If (($oCredentials.HasMember("mfa_code") = True) Or ($oCredentials.HasMember("mfa_serial") = True)) Then
ConsoleWrite("This unattended refresh example does not reuse MFA codes." & @CRLF)
Exit
EndIf
; Optional private cache contains only the four normalized session fields.
; In an application, keep activeSnapshot in memory between units of work.
$oFiles = ObjCreate("Chilkat.FileAccess")
$oCached = ObjCreate("Chilkat.JsonObject")
$oCached.Strict = True
Local $sActiveSnapshot = ""
Local $bRefreshRequired = True
If ($oFiles.FileExists("qa_data/tokens/sts_session.json") = True) Then
$bSuccess = $oCached.LoadFile("qa_data/tokens/sts_session.json")
If ($bSuccess <> True) Then
ConsoleWrite("Invalid private cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCached.StringOf("access_key"))
Local $bStringMatch7 = $oStringCompare.ContentsEqual("",True)
If (($oCached.JsonTypeOf("access_key") <> 1) Or ($bStringMatch7 = True)) Then
ConsoleWrite("Incomplete private cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCached.StringOf("secret_key"))
Local $bStringMatch8 = $oStringCompare.ContentsEqual("",True)
If (($oCached.JsonTypeOf("secret_key") <> 1) Or ($bStringMatch8 = True)) Then
ConsoleWrite("Incomplete private cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCached.StringOf("session_token"))
Local $bStringMatch9 = $oStringCompare.ContentsEqual("",True)
If (($oCached.JsonTypeOf("session_token") <> 1) Or ($bStringMatch9 = True)) Then
ConsoleWrite("Incomplete private cache." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCached.StringOf("expiration"))
Local $bStringMatch10 = $oStringCompare.ContentsEqual("",True)
If (($oCached.JsonTypeOf("expiration") <> 1) Or ($bStringMatch10 = True)) Then
ConsoleWrite("Incomplete private cache." & @CRLF)
Exit
EndIf
$bSuccess = $oExpires.SetFromTimestamp($oCached.StringOf("expiration"))
If ($bSuccess <> True) Then
ConsoleWrite("Invalid cached expiration." & @CRLF)
Exit
EndIf
$bSuccess = $oNow.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not read current time." & @CRLF)
Exit
EndIf
If ($oExpires.DiffSeconds($oNow) > 300) Then
$sActiveSnapshot = $oCached.Emit()
$bRefreshRequired = False
EndIf
EndIf
If ($bRefreshRequired = True) Then
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("sts.")
$oEndpoint.Append($sRegion)
$oEndpoint.Append(".amazonaws.com")
$oAws = ObjCreate("Chilkat.AuthAws")
$oAws.AccessKey = $oCredentials.StringOf("access_key")
$oAws.SecretKey = $oCredentials.StringOf("secret_key")
$oAws.Region = $sRegion
$oAws.ServiceName = "sts"
$oAws.SignatureVersion = 4
$oRest = ObjCreate("Chilkat.Rest")
$oRest.ConnectTimeoutMs = 20000
$oRest.IdleTimeoutMs = 60000
$oRest.VerboseLogging = False
$bSuccess = $oRest.SetAuthAws($oAws)
If ($bSuccess <> True) Then
ConsoleWrite("Could not configure request signing." & @CRLF)
Exit
EndIf
; Keep this verified Socket alive while Rest uses its connection.
$oConnection = ObjCreate("Chilkat.Socket")
$oConnection.RequireSslCertVerify = True
$oConnection.MaxReadIdleMs = 60000
$oConnection.MaxSendIdleMs = 60000
$bSuccess = $oConnection.Connect($oEndpoint.GetAsString(),443,True,20000)
If ($bSuccess <> True) Then
ConsoleWrite("TLS connection failed; inspect diagnostics privately." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.UseConnection($oConnection,True)
If ($bSuccess <> True) Then
ConsoleWrite("Could not attach TLS connection." & @CRLF)
Exit
EndIf
$oXml = ObjCreate("Chilkat.Xml")
$oXml.Strict = True
Local $sValue
Local $sAccessKey
Local $secretKey
Local $sessionToken
Local $sExpiration
Local $sResponseXml = ""
Local $iAttempt = 0
Local $iDelayMs = 1000
Local $bReceived = False
Local $bRetryable
While (($iAttempt < 3) And ($bReceived = False))
If ($oCredentials.HasMember("session_token") = True) Then
$oStringCompare.SetString($oCredentials.StringOf("session_token"))
Local $bStringMatch11 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("session_token") <> 1) Or ($bStringMatch11 = True)) Then
ConsoleWrite("Missing or invalid session_token." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("expiration"))
Local $bStringMatch12 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("expiration") <> 1) Or ($bStringMatch12 = True)) Then
ConsoleWrite("Missing or invalid expiration." & @CRLF)
Exit
EndIf
$bSuccess = $oExpires.SetFromTimestamp($oCredentials.StringOf("expiration"))
If ($bSuccess <> True) Then
ConsoleWrite("Source expiration is invalid." & @CRLF)
Exit
EndIf
$bSuccess = $oNow.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not read current time." & @CRLF)
Exit
EndIf
If ($oExpires.DiffSeconds($oNow) <= 60) Then
ConsoleWrite("Source credentials are expired or expire within 60 seconds; obtain fresh credentials." & @CRLF)
Exit
EndIf
EndIf
$iAttempt = $iAttempt + 1
$bSuccess = $oRest.ClearAllQueryParams()
If ($bSuccess <> True) Then
ConsoleWrite("Could not reset request parameters." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.AddQueryParam("Action","AssumeRole")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set Action." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.AddQueryParam("Version","2011-06-15")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set Version." & @CRLF)
Exit
EndIf
If ($oCredentials.HasMember("session_token") = True) Then
$bSuccess = $oRest.AddQueryParam("X-Amz-Security-Token",$oCredentials.StringOf("session_token"))
If ($bSuccess <> True) Then
ConsoleWrite("Could not set X-Amz-Security-Token." & @CRLF)
Exit
EndIf
EndIf
$bSuccess = $oRest.AddQueryParam("RoleArn",$oCredentials.StringOf("role_arn"))
If ($bSuccess <> True) Then
ConsoleWrite("Could not set RoleArn." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.AddQueryParam("RoleSessionName",$oCredentials.StringOf("role_session_name"))
If ($bSuccess <> True) Then
ConsoleWrite("Could not set RoleSessionName." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.AddQueryParam("DurationSeconds","3600")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set DurationSeconds." & @CRLF)
Exit
EndIf
$sResponseXml = $oRest.FullRequestFormUrlEncoded("POST","/")
If ($oRest.LastMethodSuccess <> True) Then
ConsoleWrite("Transport failed; credential refresh was not published." & @CRLF)
Exit
EndIf
If ($oRest.ResponseStatusCode = 200) Then
$bReceived = True
EndIf
If ($oRest.ResponseStatusCode <> 200) Then
$bRetryable = False
$sValue = ""
$bSuccess = $oXml.LoadXml($sResponseXml)
If ($bSuccess = True) Then
$sValue = $oXml.GetChildContent("Error|Code")
EndIf
$oStringCompare.SetString($sValue)
Local $bStringMatch13 = $oStringCompare.ContentsEqual("Throttling",True)
$oStringCompare.SetString($sValue)
Local $bStringMatch14 = $oStringCompare.ContentsEqual("ThrottlingException",True)
If (($oRest.ResponseStatusCode = 429) Or ($oRest.ResponseStatusCode = 500) Or ($oRest.ResponseStatusCode = 502) Or ($oRest.ResponseStatusCode = 503) Or ($oRest.ResponseStatusCode = 504) Or ($bStringMatch13 = True) Or ($bStringMatch14 = True)) Then
$bRetryable = True
EndIf
If (($bRetryable <> True) Or ($iAttempt = 3)) Then
ConsoleWrite("Refresh failed. HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
ConsoleWrite("AWS error code: " & $sValue & @CRLF)
Exit
EndIf
$oConnection.SleepMs $iDelayMs
$iDelayMs = $iDelayMs * 2
EndIf
Wend
If ($bReceived <> True) Then
ConsoleWrite("Refresh attempts exhausted." & @CRLF)
Exit
EndIf
$bSuccess = $oXml.LoadXml($sResponseXml)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid STS XML response." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oXml.Tag)
Local $bStringMatch15 = $oStringCompare.ContentsEqual("AssumeRoleResponse",True)
If ($bStringMatch15 <> True) Then
ConsoleWrite("Unexpected STS response root." & @CRLF)
Exit
EndIf
$sValue = $oXml.GetChildContent("ResponseMetadata|RequestId")
$oStringCompare.SetString($sValue)
Local $bStringMatch16 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch16 = True)) Then
ConsoleWrite("Missing or empty ResponseMetadata|RequestId." & @CRLF)
Exit
EndIf
If ($oXml.HasChildWithTag("AssumeRoleResult") <> True) Then
ConsoleWrite("Missing STS result." & @CRLF)
Exit
EndIf
$sAccessKey = $oXml.GetChildContent("AssumeRoleResult|Credentials|AccessKeyId")
$oStringCompare.SetString($sAccessKey)
Local $bStringMatch17 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch17 = True)) Then
ConsoleWrite("Missing or empty AssumeRoleResult|Credentials|AccessKeyId." & @CRLF)
Exit
EndIf
$secretKey = $oXml.GetChildContent("AssumeRoleResult|Credentials|SecretAccessKey")
$oStringCompare.SetString($secretKey)
Local $bStringMatch18 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch18 = True)) Then
ConsoleWrite("Missing or empty AssumeRoleResult|Credentials|SecretAccessKey." & @CRLF)
Exit
EndIf
$sessionToken = $oXml.GetChildContent("AssumeRoleResult|Credentials|SessionToken")
$oStringCompare.SetString($sessionToken)
Local $bStringMatch19 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch19 = True)) Then
ConsoleWrite("Missing or empty AssumeRoleResult|Credentials|SessionToken." & @CRLF)
Exit
EndIf
$sExpiration = $oXml.GetChildContent("AssumeRoleResult|Credentials|Expiration")
$oStringCompare.SetString($sExpiration)
Local $bStringMatch20 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch20 = True)) Then
ConsoleWrite("Missing or empty AssumeRoleResult|Credentials|Expiration." & @CRLF)
Exit
EndIf
$bSuccess = $oExpires.SetFromTimestamp($sExpiration)
If ($bSuccess <> True) Then
ConsoleWrite("Returned expiration is invalid." & @CRLF)
Exit
EndIf
$bSuccess = $oNow.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
ConsoleWrite("Could not read current time." & @CRLF)
Exit
EndIf
If ($oExpires.DiffSeconds($oNow) <= 60) Then
ConsoleWrite("Returned credentials are expired or expire within 60 seconds; obtain fresh credentials." & @CRLF)
Exit
EndIf
$sValue = $oXml.GetChildContent("AssumeRoleResult|AssumedRoleUser|Arn")
$oStringCompare.SetString($sValue)
Local $bStringMatch21 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch21 = True)) Then
ConsoleWrite("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn." & @CRLF)
Exit
EndIf
$sValue = $oXml.GetChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
$oStringCompare.SetString($sValue)
Local $bStringMatch22 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch22 = True)) Then
ConsoleWrite("Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId." & @CRLF)
Exit
EndIf
$oSession = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oSession.UpdateString("access_key",$sAccessKey)
If ($bSuccess <> True) Then
ConsoleWrite("Could not build complete session." & @CRLF)
Exit
EndIf
$bSuccess = $oSession.UpdateString("secret_key",$secretKey)
If ($bSuccess <> True) Then
ConsoleWrite("Could not build complete session." & @CRLF)
Exit
EndIf
$bSuccess = $oSession.UpdateString("session_token",$sessionToken)
If ($bSuccess <> True) Then
ConsoleWrite("Could not build complete session." & @CRLF)
Exit
EndIf
$bSuccess = $oSession.UpdateString("expiration",$sExpiration)
If ($bSuccess <> True) Then
ConsoleWrite("Could not build complete session." & @CRLF)
Exit
EndIf
; Use session in memory; do not print or log session.Emit().
ConsoleWrite("Session validated; expiration: " & $sExpiration & @CRLF)
; Publish one complete snapshot only after validating every returned field.
$sActiveSnapshot = $oSession.Emit()
EndIf
; Rehydrate a complete set for the next unit of work, never four partial updates.
$oUsable = ObjCreate("Chilkat.JsonObject")
$oUsable.Strict = True
$bSuccess = $oUsable.Load($sActiveSnapshot)
If ($bSuccess <> True) Then
ConsoleWrite("Could not load the complete session snapshot." & @CRLF)
Exit
EndIf
; Pass usable to your service client here. Do not log activeSnapshot.
ConsoleWrite("Session ready for the next unit of work; expiration: " & $oUsable.StringOf("expiration") & @CRLF)
ConsoleWrite("Example completed." & @CRLF)