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

AWS STS: Normalize STS Credentials and Use Chilkat.Rest

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.

Reads only private qa_data/tokens/aws_session_token.xml; no sts.json is needed. Accepts all seven credential-producing STS response roots, including the existing GetSessionToken/AssumeRole handoff. Builds a complete normalized in-memory session and uses it to sign GetCallerIdentity. The normalized fields are access_key, secret_key, session_token and expiration. Checks expiration with a 60-second margin before connecting. JWT-only GetWebIdentityToken responses are intentionally not credential sets.

AWS references: GetCallerIdentity

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
'  Load a privately stored STS XML response; never print its contents.
Dim tokenXml As ChilkatXml
tokenXml.Initialize
tokenXml.Strict = True
success = tokenXml.LoadXmlFile("qa_data/tokens/aws_session_token.xml")
If success <> True Then
    Log("Could not load private STS XML.")
    Return
End If

Dim credentialPath As String = ""
stringCompare.SetString(tokenXml.Tag)
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("GetSessionTokenResponse", True)
If stringMatch1 = True Then
    credentialPath = "GetSessionTokenResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("AssumeRoleResponse", True)
If stringMatch2 = True Then
    credentialPath = "AssumeRoleResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("AssumeRoleWithWebIdentityResponse", True)
If stringMatch3 = True Then
    credentialPath = "AssumeRoleWithWebIdentityResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("AssumeRoleWithSAMLResponse", True)
If stringMatch4 = True Then
    credentialPath = "AssumeRoleWithSAMLResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("GetFederationTokenResponse", True)
If stringMatch5 = True Then
    credentialPath = "GetFederationTokenResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("GetDelegatedAccessTokenResponse", True)
If stringMatch6 = True Then
    credentialPath = "GetDelegatedAccessTokenResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("AssumeRootResponse", True)
If stringMatch7 = True Then
    credentialPath = "AssumeRootResult|Credentials"
End If

stringCompare.SetString(credentialPath)
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch8 = True Then
    Log("Unsupported STS credential response.")
    Return
End If

Dim accessKey As String
Dim secretKey As String
Dim sessionToken As String
Dim expiration As String
Dim path As ChilkatStringBuilder
path.Initialize
success = path.SetString(credentialPath)
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

success = path.Append("|AccessKeyId")
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

accessKey = tokenXml.GetChildContent(path.GetAsString)
stringCompare.SetString(accessKey)
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("", True)
If (tokenXml.LastMethodSuccess <> True) Or (stringMatch9 = True) Then
    Log("Missing credential field AccessKeyId.")
    Return
End If

success = path.SetString(credentialPath)
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

success = path.Append("|SecretAccessKey")
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

secretKey = tokenXml.GetChildContent(path.GetAsString)
stringCompare.SetString(secretKey)
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("", True)
If (tokenXml.LastMethodSuccess <> True) Or (stringMatch10 = True) Then
    Log("Missing credential field SecretAccessKey.")
    Return
End If

success = path.SetString(credentialPath)
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

success = path.Append("|SessionToken")
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

sessionToken = tokenXml.GetChildContent(path.GetAsString)
stringCompare.SetString(sessionToken)
Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("", True)
If (tokenXml.LastMethodSuccess <> True) Or (stringMatch11 = True) Then
    Log("Missing credential field SessionToken.")
    Return
End If

success = path.SetString(credentialPath)
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

success = path.Append("|Expiration")
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

expiration = tokenXml.GetChildContent(path.GetAsString)
stringCompare.SetString(expiration)
Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("", True)
If (tokenXml.LastMethodSuccess <> True) Or (stringMatch12 = True) Then
    Log("Missing credential field Expiration.")
    Return
End If

Dim expires As ChilkatDateTime
expires.Initialize
Dim now As ChilkatDateTime
now.Initialize
success = expires.SetFromTimestamp(expiration)
If success <> True Then
    Log("Stored 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("Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.")
    Return
End If

Dim session As ChilkatJsonObject
session.Initialize
success = session.UpdateString("access_key", accessKey)
If success <> True Then
    Log("Could not build normalized session.")
    Return
End If

success = session.UpdateString("secret_key", secretKey)
If success <> True Then
    Log("Could not build normalized session.")
    Return
End If

success = session.UpdateString("session_token", sessionToken)
If success <> True Then
    Log("Could not build normalized session.")
    Return
End If

success = session.UpdateString("expiration", expiration)
If success <> True Then
    Log("Could not build normalized session.")
    Return
End If

Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("sts.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = session.StringOf("access_key")
aws.SecretKey = session.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 responseXml As String
success = rest.ClearAllQueryParams
If success <> True Then
    Log("Could not reset request parameters.")
    Return
End If

success = rest.AddQueryParam("Action", "GetCallerIdentity")
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

success = rest.AddQueryParam("X-Amz-Security-Token", session.StringOf("session_token"))
If success <> True Then
    Log("Could not set X-Amz-Security-Token.")
    Return
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 stringMatch13 As Boolean = stringCompare.ContentsEqual("GetCallerIdentityResponse", True)
If stringMatch13 <> True Then
    Log("Unexpected STS response root.")
    Return
End If

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

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

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

Log("Authenticated principal: " & value)
Log("Example completed.")