Sample code for 30+ languages & platforms
VBScript 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 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("audience"))
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("audience") <> 1) Or (stringMatch5 = 1)) Then
    outFile.WriteLine("Missing or invalid audience.")
    WScript.Quit
End If

'  Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
subjectMode = "AWSIdentity"
If (credentials.HasMember("subject_mode") = 1) Then
    success = stringCompare.SetString(credentials.StringOf("subject_mode"))
    stringMatch6 = stringCompare.ContentsEqual("",1)
    If ((credentials.JsonTypeOf("subject_mode") <> 1) Or (stringMatch6 = 1)) Then
        outFile.WriteLine("Missing or invalid subject_mode.")
        WScript.Quit
    End If

    subjectMode = credentials.StringOf("subject_mode")
End If

success = stringCompare.SetString(subjectMode)
stringMatch7 = stringCompare.ContentsEqual("AWSIdentity",1)
success = stringCompare.SetString(subjectMode)
stringMatch8 = stringCompare.ContentsEqual("OriginIdentity",1)
If ((stringMatch7 <> 1) And (stringMatch8 <> 1)) Then
    outFile.WriteLine("Invalid subject_mode.")
    WScript.Quit
End If

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

    success = stringCompare.SetString(subjectMode)
    stringMatch10 = stringCompare.ContentsEqual("OriginIdentity",1)
    If (stringMatch10 <> 1) Then
        outFile.WriteLine("scope requires OriginIdentity.")
        WScript.Quit
    End If

    set scopeText = CreateObject("Chilkat.StringBuilder")
    success = scopeText.Append(credentials.StringOf("scope"))
    If ((scopeText.Length > 256) Or (scopeText.StartsWith(" ",1) = 1) Or (scopeText.EndsWith(" ",1) = 1) Or (scopeText.Contains("  ",1) = 1)) Then
        outFile.WriteLine("Invalid scope length or spacing.")
        WScript.Quit
    End If

    set allowedScope = CreateObject("Chilkat.StringBuilder")
    success = allowedScope.Append("!#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ")
    scopeIndex = 0
    Do While (scopeIndex < scopeText.Length)
        If (allowedScope.Contains(scopeText.GetRange(scopeIndex,1,0),1) <> 1) Then
            outFile.WriteLine("Invalid scope character.")
            WScript.Quit
        End If

        scopeIndex = scopeIndex + 1
    Loop
    set scopeValues = CreateObject("Chilkat.StringTable")
    success = scopeValues.SplitAndAppend(scopeText.GetAsString()," ",0,0)
    If (success <> 1) Then
        outFile.WriteLine("Could not split scope values.")
        WScript.Quit
    End If

    set seenScopes = CreateObject("Chilkat.Hashtable")
    scopeIndex = 0

    Do While (scopeIndex < scopeValues.Count)
        scopeValue = scopeValues.StringAt(scopeIndex)
        If (seenScopes.Contains(scopeValue) = 1) Then
            outFile.WriteLine("Duplicate scope value.")
            WScript.Quit
        End If

        success = seenScopes.AddStr(scopeValue,"seen")
        If (success <> 1) Then
            outFile.WriteLine("Could not track scope values.")
            WScript.Quit
        End If

        scopeIndex = scopeIndex + 1
    Loop
End If

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 = ""
success = rest.ClearAllQueryParams()
If (success <> 1) Then
    outFile.WriteLine("Could not reset request parameters.")
    WScript.Quit
End If

success = rest.AddQueryParam("Action","GetWebIdentityToken")
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("Audience.member.1",credentials.StringOf("audience"))
If (success <> 1) Then
    outFile.WriteLine("Could not set Audience.member.1.")
    WScript.Quit
End If

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

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

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

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

End If

responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> 1) Then
    outFile.WriteLine("STS transport failed; inspect diagnostics privately.")
    WScript.Quit
End If

If (rest.ResponseStatusCode <> 200) Then
    outFile.WriteLine("STS HTTP status: " & rest.ResponseStatusCode)
    success = xml.LoadXml(responseXml)
    If (success = 1) Then
        value = xml.GetChildContent("Error|Code")
        If (xml.LastMethodSuccess = 1) Then
            outFile.WriteLine("AWS error code: " & value)
        End If

        value = xml.GetChildContent("RequestId")
        If (xml.LastMethodSuccess = 1) Then
            outFile.WriteLine("AWS request ID: " & value)
        End If

    End If

    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)
stringMatch11 = stringCompare.ContentsEqual("GetWebIdentityTokenResponse",1)
If (stringMatch11 <> 1) Then
    outFile.WriteLine("Unexpected STS response root.")
    WScript.Quit
End If

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

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

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

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

success = expires.SetFromTimestamp(expiration)
If (success <> 1) Then
    outFile.WriteLine("JWT 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("JWT credentials are expired or expire within 60 seconds; obtain fresh credentials.")
    WScript.Quit
End If

'  Hand sessionToken to the intended external service over TLS; never log it.
outFile.WriteLine("Web identity token obtained; expiration: " & expiration)
outFile.WriteLine("Example completed.")

outFile.Close