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

B4X
Dim success As Boolean = False

Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Keep this file private and outside public web content/source control.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/sts.json")
If success <> True Then
    Log("Could not load private STS configuration.")
    Return
End If

stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True) Then
    Log("Missing or invalid access_key.")
    Return
End If

stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True) Then
    Log("Missing or invalid secret_key.")
    Return
End If

Dim expires As ChilkatDateTime
expires.Initialize
Dim now As ChilkatDateTime
now.Initialize
Dim region As String = "us-west-2"
If credentials.HasMember("session_token") = True Then
    stringCompare.SetString(credentials.StringOf("session_token"))
    Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
    If (credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True) Then
        Log("Missing or invalid session_token.")
        Return
    End If

    stringCompare.SetString(credentials.StringOf("expiration"))
    Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("", True)
    If (credentials.JsonTypeOf("expiration") <> 1) Or (stringMatch4 = True) Then
        Log("Missing or invalid expiration.")
        Return
    End If

    success = expires.SetFromTimestamp(credentials.StringOf("expiration"))
    If success <> True Then
        Log("Source expiration is invalid.")
        Return
    End If

    success = now.SetFromCurrentSystemTime
    If success <> True Then
        Log("Could not read current time.")
        Return
    End If

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

End If

stringCompare.SetString(credentials.StringOf("audience"))
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("audience") <> 1) Or (stringMatch5 = True) Then
    Log("Missing or invalid audience.")
    Return
End If

'  Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
Dim subjectMode As String = "AWSIdentity"
If credentials.HasMember("subject_mode") = True Then
    stringCompare.SetString(credentials.StringOf("subject_mode"))
    Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("", True)
    If (credentials.JsonTypeOf("subject_mode") <> 1) Or (stringMatch6 = True) Then
        Log("Missing or invalid subject_mode.")
        Return
    End If

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

stringCompare.SetString(subjectMode)
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("AWSIdentity", True)
stringCompare.SetString(subjectMode)
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("OriginIdentity", True)
If (stringMatch7 <> True) And (stringMatch8 <> True) Then
    Log("Invalid subject_mode.")
    Return
End If

If credentials.HasMember("scope") = True Then
    stringCompare.SetString(credentials.StringOf("scope"))
    Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("", True)
    If (credentials.JsonTypeOf("scope") <> 1) Or (stringMatch9 = True) Then
        Log("Missing or invalid scope.")
        Return
    End If

    stringCompare.SetString(subjectMode)
    Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("OriginIdentity", True)
    If stringMatch10 <> True Then
        Log("scope requires OriginIdentity.")
        Return
    End If

    Dim scopeText As ChilkatStringBuilder
    scopeText.Initialize
    scopeText.Append(credentials.StringOf("scope"))
    If (scopeText.Length > 256) Or (scopeText.StartsWith(" ", True) = True) Or (scopeText.EndsWith(" ", True) = True) Or (scopeText.Contains("  ", True) = True) Then
        Log("Invalid scope length or spacing.")
        Return
    End If

    Dim allowedScope As ChilkatStringBuilder
    allowedScope.Initialize
    allowedScope.Append("!#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ")
    Dim scopeIndex As Int = 0
    Do While (scopeIndex < scopeText.Length)
        If allowedScope.Contains(scopeText.GetRange(scopeIndex, 1, False), True) <> True Then
            Log("Invalid scope character.")
            Return
        End If

        scopeIndex = scopeIndex + 1
    Loop
    Dim scopeValues As ChilkatStringTable
    scopeValues.Initialize
    success = scopeValues.SplitAndAppend(scopeText.GetAsString, " ", False, False)
    If success <> True Then
        Log("Could not split scope values.")
        Return
    End If

    Dim seenScopes As ChilkatHashtable
    seenScopes.Initialize
    scopeIndex = 0
    Dim scopeValue As String
    Do While (scopeIndex < scopeValues.Count)
        scopeValue = scopeValues.StringAt(scopeIndex)
        If seenScopes.Contains(scopeValue) = True Then
            Log("Duplicate scope value.")
            Return
        End If

        success = seenScopes.AddStr(scopeValue, "seen")
        If success <> True Then
            Log("Could not track scope values.")
            Return
        End If

        scopeIndex = scopeIndex + 1
    Loop
End If

Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("sts.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sts"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("Could not configure request signing.")
    Return
End If

'  Keep this verified Socket alive while Rest uses its connection.
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection, True)
If success <> True Then
    Log("Could not attach TLS connection.")
    Return
End If

Dim xml As ChilkatXml
xml.Initialize
xml.Strict = True
Dim value As String
Dim sessionToken As String
Dim expiration As String
Dim responseXml As String = ""
success = rest.ClearAllQueryParams
If success <> True Then
    Log("Could not reset request parameters.")
    Return
End If

success = rest.AddQueryParam("Action", "GetWebIdentityToken")
If success <> True Then
    Log("Could not set Action.")
    Return
End If

success = rest.AddQueryParam("Version", "2011-06-15")
If success <> True Then
    Log("Could not set Version.")
    Return
End If

If credentials.HasMember("session_token") = True Then
    success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
    If success <> True Then
        Log("Could not set X-Amz-Security-Token.")
        Return
    End If

End If

success = rest.AddQueryParam("Audience.member.1", credentials.StringOf("audience"))
If success <> True Then
    Log("Could not set Audience.member.1.")
    Return
End If

success = rest.AddQueryParam("SigningAlgorithm", "RS256")
If success <> True Then
    Log("Could not set SigningAlgorithm.")
    Return
End If

success = rest.AddQueryParam("DurationSeconds", "300")
If success <> True Then
    Log("Could not set DurationSeconds.")
    Return
End If

success = rest.AddQueryParam("SubjectMode", subjectMode)
If success <> True Then
    Log("Could not set SubjectMode.")
    Return
End If

If credentials.HasMember("scope") = True Then
    success = rest.AddQueryParam("Scope", credentials.StringOf("scope"))
    If success <> True Then
        Log("Could not set Scope.")
        Return
    End If

End If

responseXml = rest.FullRequestFormUrlEncoded("POST", "/")
If rest.LastMethodSuccess <> True Then
    Log("STS transport failed; inspect diagnostics privately.")
    Return
End If

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

        value = xml.GetChildContent("RequestId")
        If xml.LastMethodSuccess = True Then
            Log("AWS request ID: " & value)
        End If

    End If

    Return
End If

success = xml.LoadXml(responseXml)
If success <> True Then
    Log("Invalid STS XML response.")
    Return
End If

stringCompare.SetString(xml.Tag)
Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("GetWebIdentityTokenResponse", True)
If stringMatch11 <> True Then
    Log("Unexpected STS response root.")
    Return
End If

value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch12 = True) Then
    Log("Missing or empty ResponseMetadata|RequestId.")
    Return
End If

If xml.HasChildWithTag("GetWebIdentityTokenResult") <> True Then
    Log("Missing STS result.")
    Return
End If

sessionToken = xml.GetChildContent("GetWebIdentityTokenResult|WebIdentityToken")
stringCompare.SetString(sessionToken)
Dim stringMatch13 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch13 = True) Then
    Log("Missing or empty GetWebIdentityTokenResult|WebIdentityToken.")
    Return
End If

expiration = xml.GetChildContent("GetWebIdentityTokenResult|Expiration")
stringCompare.SetString(expiration)
Dim stringMatch14 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch14 = True) Then
    Log("Missing or empty GetWebIdentityTokenResult|Expiration.")
    Return
End If

success = expires.SetFromTimestamp(expiration)
If success <> True Then
    Log("JWT expiration is invalid.")
    Return
End If

success = now.SetFromCurrentSystemTime
If success <> True Then
    Log("Could not read current time.")
    Return
End If

If expires.DiffSeconds(now) <= 60 Then
    Log("JWT credentials are expired or expire within 60 seconds; obtain fresh credentials.")
    Return
End If

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