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

AWS STS: Obtain an AWS-Signed JWT for an External Service

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.

Set audience to the intended external service. Requests RS256 with a five-minute lifetime from a regional STS endpoint; outbound federation must be enabled for the account. Optional subject_mode is AWSIdentity or OriginIdentity. OriginIdentity requires the caller's trusted identity propagation context. Optional scope is permitted only for OriginIdentity and this single audience, and requires sts:SetWebIdentityTokenScope in addition to sts:GetWebIdentityToken. Validates scope spacing, characters and duplicate values.

The returned token is an external identity JWT, not an AWS access key/session-token credential set. The recipient must validate its signature using the trusted issuer's JWKS, issuer, audience and lifetime; merely decoding it is insufficient. The request cannot extend the calling session's lifetime.

AWS references: GetWebIdentityToken

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
    $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("audience"))
Local $bStringMatch5 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("audience") <> 1) Or ($bStringMatch5 = True)) Then
    ConsoleWrite("Missing or invalid audience." & @CRLF)
    Exit
EndIf

;  Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
Local $subjectMode = "AWSIdentity"
If ($oCredentials.HasMember("subject_mode") = True) Then
    $oStringCompare.SetString($oCredentials.StringOf("subject_mode"))
Local $bStringMatch6 = $oStringCompare.ContentsEqual("",True)
    If (($oCredentials.JsonTypeOf("subject_mode") <> 1) Or ($bStringMatch6 = True)) Then
        ConsoleWrite("Missing or invalid subject_mode." & @CRLF)
        Exit
    EndIf

    $subjectMode = $oCredentials.StringOf("subject_mode")
EndIf

$oStringCompare.SetString($subjectMode)
Local $bStringMatch7 = $oStringCompare.ContentsEqual("AWSIdentity",True)
$oStringCompare.SetString($subjectMode)
Local $bStringMatch8 = $oStringCompare.ContentsEqual("OriginIdentity",True)
If (($bStringMatch7 <> True) And ($bStringMatch8 <> True)) Then
    ConsoleWrite("Invalid subject_mode." & @CRLF)
    Exit
EndIf

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

    $oStringCompare.SetString($subjectMode)
Local $bStringMatch10 = $oStringCompare.ContentsEqual("OriginIdentity",True)
    If ($bStringMatch10 <> True) Then
        ConsoleWrite("scope requires OriginIdentity." & @CRLF)
        Exit
    EndIf

    $oScopeText = ObjCreate("Chilkat.StringBuilder")
    $oScopeText.Append($oCredentials.StringOf("scope"))
    If (($oScopeText.Length > 256) Or ($oScopeText.StartsWith(" ",True) = True) Or ($oScopeText.EndsWith(" ",True) = True) Or ($oScopeText.Contains("  ",True) = True)) Then
        ConsoleWrite("Invalid scope length or spacing." & @CRLF)
        Exit
    EndIf

    $oAllowedScope = ObjCreate("Chilkat.StringBuilder")
    $oAllowedScope.Append("!#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ")
Local $iScopeIndex = 0
    While ($iScopeIndex < $oScopeText.Length)
        If ($oAllowedScope.Contains($oScopeText.GetRange($iScopeIndex,1,False),True) <> True) Then
            ConsoleWrite("Invalid scope character." & @CRLF)
            Exit
        EndIf

        $iScopeIndex = $iScopeIndex + 1
    Wend
    $oScopeValues = ObjCreate("Chilkat.StringTable")
    $bSuccess = $oScopeValues.SplitAndAppend($oScopeText.GetAsString()," ",False,False)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not split scope values." & @CRLF)
        Exit
    EndIf

    $oSeenScopes = ObjCreate("Chilkat.Hashtable")
    $iScopeIndex = 0
Local $scopeValue
    While ($iScopeIndex < $oScopeValues.Count)
        $scopeValue = $oScopeValues.StringAt($iScopeIndex)
        If ($oSeenScopes.Contains($scopeValue) = True) Then
            ConsoleWrite("Duplicate scope value." & @CRLF)
            Exit
        EndIf

        $bSuccess = $oSeenScopes.AddStr($scopeValue,"seen")
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not track scope values." & @CRLF)
            Exit
        EndIf

        $iScopeIndex = $iScopeIndex + 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 $sessionToken
Local $sExpiration
Local $sResponseXml = ""
$bSuccess = $oRest.ClearAllQueryParams()
If ($bSuccess <> True) Then
    ConsoleWrite("Could not reset request parameters." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.AddQueryParam("Action","GetWebIdentityToken")
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("Audience.member.1",$oCredentials.StringOf("audience"))
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set Audience.member.1." & @CRLF)
    Exit
EndIf

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

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

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

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

EndIf

$sResponseXml = $oRest.FullRequestFormUrlEncoded("POST","/")
If ($oRest.LastMethodSuccess <> True) Then
    ConsoleWrite("STS transport failed; inspect diagnostics privately." & @CRLF)
    Exit
EndIf

If ($oRest.ResponseStatusCode <> 200) Then
    ConsoleWrite("STS HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
    $bSuccess = $oXml.LoadXml($sResponseXml)
    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

    Exit
EndIf

$bSuccess = $oXml.LoadXml($sResponseXml)
If ($bSuccess <> True) Then
    ConsoleWrite("Invalid STS XML response." & @CRLF)
    Exit
EndIf

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

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

If ($oXml.HasChildWithTag("GetWebIdentityTokenResult") <> True) Then
    ConsoleWrite("Missing STS result." & @CRLF)
    Exit
EndIf

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

$sExpiration = $oXml.GetChildContent("GetWebIdentityTokenResult|Expiration")
$oStringCompare.SetString($sExpiration)
Local $bStringMatch14 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch14 = True)) Then
    ConsoleWrite("Missing or empty GetWebIdentityTokenResult|Expiration." & @CRLF)
    Exit
EndIf

$bSuccess = $oExpires.SetFromTimestamp($sExpiration)
If ($bSuccess <> True) Then
    ConsoleWrite("JWT 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("JWT credentials are expired or expire within 60 seconds; obtain fresh credentials." & @CRLF)
    Exit
EndIf

;  Hand sessionToken to the intended external service over TLS; never log it.
ConsoleWrite("Web identity token obtained; expiration: " & $sExpiration & @CRLF)
ConsoleWrite("Example completed." & @CRLF)