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

AWS STS: GetSessionToken with Optional MFA

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.

Call with a long-term IAM user access key, not role/session credentials. This example rejects a supplied session_token and requests 3600 seconds. IAM user sessions allow 900–129600 seconds, default 43200. Do not use root credentials. Optional mfa_serial and mfa_code must be supplied together; the code is a six-digit string and can start with zero. Remove the short-lived MFA code from the private configuration after use; production applications should collect it at runtime.

GetSessionToken authenticates the IAM user and needs no permission grant for the GetSessionToken authentication operation. It does not assume a role or restrict the user's permissions via a session policy. The returned credentials inherit the user's permissions; IAM operations require MFA information, and the supported STS calls are limited to AssumeRole and GetCallerIdentity. For other workloads, prefer an appropriate role credential provider.

AWS API reference

Chilkat AutoIt Downloads

AutoIt
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
    ConsoleWrite("GetSessionToken requires long-term IAM user credentials, not an existing session token." & @CRLF)
    Exit
EndIf

;  MFA fields are optional as a pair. Preserve a leading zero in the code.
If (($oCredentials.HasMember("mfa_serial") = True) Or ($oCredentials.HasMember("mfa_code") = True)) Then
    $oStringCompare.SetString($oCredentials.StringOf("mfa_serial"))
Local $bStringMatch3 = $oStringCompare.ContentsEqual("",True)
    If (($oCredentials.JsonTypeOf("mfa_serial") <> 1) Or ($bStringMatch3 = True)) Then
        ConsoleWrite("Missing or invalid mfa_serial." & @CRLF)
        Exit
    EndIf

    $oStringCompare.SetString($oCredentials.StringOf("mfa_code"))
Local $bStringMatch4 = $oStringCompare.ContentsEqual("",True)
    If (($oCredentials.JsonTypeOf("mfa_code") <> 1) Or ($bStringMatch4 = True)) Then
        ConsoleWrite("Missing or invalid mfa_code." & @CRLF)
        Exit
    EndIf

    $oMfaCode = ObjCreate("Chilkat.StringBuilder")
    $oMfaCode.Append($oCredentials.StringOf("mfa_code"))
    If ($oMfaCode.Length <> 6) Then
        ConsoleWrite("mfa_code must be a six-digit string." & @CRLF)
        Exit
    EndIf

    $oDigits = ObjCreate("Chilkat.StringBuilder")
    $oDigits.Append("0123456789")
Local $iDigitIndex = 0
    While ($iDigitIndex < 6)
        If ($oDigits.Contains($oMfaCode.GetRange($iDigitIndex,1,False),True) <> True) Then
            ConsoleWrite("mfa_code must contain only ASCII digits." & @CRLF)
            Exit
        EndIf

        $iDigitIndex = $iDigitIndex + 1
    Wend
EndIf

$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
$bSuccess = $oRest.ClearAllQueryParams()
If ($bSuccess <> True) Then
    ConsoleWrite("Could not clear request parameters." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.AddQueryParam("Action","GetSessionToken")
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

$bSuccess = $oRest.AddQueryParam("DurationSeconds","3600")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set DurationSeconds." & @CRLF)
    Exit
EndIf

If ($oCredentials.HasMember("mfa_serial") = True) Then
    $bSuccess = $oRest.AddQueryParam("SerialNumber",$oCredentials.StringOf("mfa_serial"))
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not set SerialNumber." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oRest.AddQueryParam("TokenCode",$oCredentials.StringOf("mfa_code"))
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not set TokenCode." & @CRLF)
        Exit
    EndIf

EndIf

Local $sResponseXml = $oRest.FullRequestFormUrlEncoded("POST","/")
If ($oRest.LastMethodSuccess <> True) Then
    ConsoleWrite("STS request did not complete; no credentials were saved. Inspect diagnostics privately." & @CRLF)
    Exit
EndIf

$bSuccess = $oXml.LoadXml($sResponseXml)
If ($oRest.ResponseStatusCode <> 200) Then
    ConsoleWrite("STS HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
    If ($bSuccess = True) Then
        $sValue = $oXml.GetChildContent("Error|Code")
        If ($oXml.LastMethodSuccess = True) Then
            ConsoleWrite("AWS error code: " & $sValue & @CRLF)
        EndIf

        $sValue = $oXml.GetChildContent("RequestId")
        If ($oXml.LastMethodSuccess = True) Then
            ConsoleWrite("AWS request ID: " & $sValue & @CRLF)
        EndIf

    EndIf

    ;  Full bodies, headers, and diagnostics can contain sensitive data.
    Exit
EndIf

If ($bSuccess <> True) Then
    ConsoleWrite("Invalid STS XML response; no credentials were saved." & @CRLF)
    Exit
EndIf

$oStringCompare.SetString($oXml.Tag)
Local $bStringMatch5 = $oStringCompare.ContentsEqual("GetSessionTokenResponse",True)
If ($bStringMatch5 <> True) Then
    ConsoleWrite("Unexpected STS response root." & @CRLF)
    Exit
EndIf

$sValue = $oXml.GetChildContent("ResponseMetadata|RequestId")
$oStringCompare.SetString($sValue)
Local $bStringMatch6 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch6 = True)) Then
    ConsoleWrite("Missing or empty ResponseMetadata|RequestId." & @CRLF)
    Exit
EndIf

ConsoleWrite("AWS request ID: " & $sValue & @CRLF)
$sAccessKey = $oXml.GetChildContent("GetSessionTokenResult|Credentials|AccessKeyId")
$oStringCompare.SetString($sAccessKey)
Local $bStringMatch7 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch7 = True)) Then
    ConsoleWrite("Missing or empty GetSessionTokenResult|Credentials|AccessKeyId." & @CRLF)
    Exit
EndIf

$secretKey = $oXml.GetChildContent("GetSessionTokenResult|Credentials|SecretAccessKey")
$oStringCompare.SetString($secretKey)
Local $bStringMatch8 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch8 = True)) Then
    ConsoleWrite("Missing or empty GetSessionTokenResult|Credentials|SecretAccessKey." & @CRLF)
    Exit
EndIf

$sessionToken = $oXml.GetChildContent("GetSessionTokenResult|Credentials|SessionToken")
$oStringCompare.SetString($sessionToken)
Local $bStringMatch9 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch9 = True)) Then
    ConsoleWrite("Missing or empty GetSessionTokenResult|Credentials|SessionToken." & @CRLF)
    Exit
EndIf

$sExpiration = $oXml.GetChildContent("GetSessionTokenResult|Credentials|Expiration")
$oStringCompare.SetString($sExpiration)
Local $bStringMatch10 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch10 = True)) Then
    ConsoleWrite("Missing or empty GetSessionTokenResult|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

;  Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
;  Reuses the existing handoff filename for the companion S3 example.
$bSuccess = $oXml.SaveXml("qa_data/tokens/aws_session_token.xml")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not save the private credential file; do not assume it was updated." & @CRLF)
    Exit
EndIf

ConsoleWrite("Temporary credentials saved privately; expiration: " & $sExpiration & @CRLF)