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

AWS STS: Exchange an OIDC Token for Role Credentials

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.

Provide role_arn, role_session_name and the complete web_identity_token from your OIDC provider. The exchange is unsigned: no AWS access key or SigV4 header is sent. Configure the IAM provider and role trust for the expected issuer, audience and subject. STS validates the token; this sample does not treat decoding a JWT as verification. Refresh expired input through your identity provider.

AWS references: AssumeRoleWithWebIdentity

Chilkat Visual Basic 6.0 Downloads

Visual Basic 6.0
Dim success As Long
success = 0

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

Dim expires As New CkDateTime
Dim now As New CkDateTime
Dim region As String
region = "us-west-2"
success = stringCompare.SetString(credentials.StringOf("role_arn"))
Dim stringMatch1 As Long
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("role_arn") <> 1) Or (stringMatch1 = 1)) Then
    Debug.Print "Missing or invalid role_arn."
    Exit Sub
End If

success = stringCompare.SetString(credentials.StringOf("role_session_name"))
Dim stringMatch2 As Long
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("role_session_name") <> 1) Or (stringMatch2 = 1)) Then
    Debug.Print "Missing or invalid role_session_name."
    Exit Sub
End If

Dim identifier As New ChilkatStringBuilder
success = identifier.Append(credentials.StringOf("role_session_name"))
If ((identifier.Length < 2) Or (identifier.Length > 64)) Then
    Debug.Print "role_session_name must have 2-64 characters."
    Exit Sub
End If

Dim allowed As New ChilkatStringBuilder
success = allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
Dim charIndex As Long
charIndex = 0
Do While (charIndex < identifier.Length)
    If (allowed.Contains(identifier.GetRange(charIndex,1,0),1) <> 1) Then
        Debug.Print "Invalid character in role_session_name."
        Exit Sub
    End If

    charIndex = charIndex + 1
Loop
success = stringCompare.SetString(credentials.StringOf("web_identity_token"))
Dim stringMatch3 As Long
stringMatch3 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("web_identity_token") <> 1) Or (stringMatch3 = 1)) Then
    Debug.Print "Missing or invalid web_identity_token."
    Exit Sub
End If

Dim endpoint As New ChilkatStringBuilder
success = endpoint.Append("sts.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim rest As New ChilkatRest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = 0
'  Keep this verified Socket alive while Rest uses its connection.
Dim connection As New ChilkatSocket
connection.RequireSslCertVerify = 1
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,1,20000)
If (success <> 1) Then
    Debug.Print "TLS connection failed; inspect diagnostics privately."
    Exit Sub
End If

success = rest.UseConnection(connection,1)
If (success <> 1) Then
    Debug.Print "Could not attach TLS connection."
    Exit Sub
End If

Dim xml As New ChilkatXml
xml.Strict = 1
Dim value As String
Dim accessKey As String
Dim secretKey As String
Dim sessionToken As String
Dim expiration As String
Dim responseXml As String
responseXml = ""
success = rest.ClearAllQueryParams()
If (success <> 1) Then
    Debug.Print "Could not reset request parameters."
    Exit Sub
End If

success = rest.AddQueryParam("Action","AssumeRoleWithWebIdentity")
If (success <> 1) Then
    Debug.Print "Could not set Action."
    Exit Sub
End If

success = rest.AddQueryParam("Version","2011-06-15")
If (success <> 1) Then
    Debug.Print "Could not set Version."
    Exit Sub
End If

success = rest.AddQueryParam("RoleArn",credentials.StringOf("role_arn"))
If (success <> 1) Then
    Debug.Print "Could not set RoleArn."
    Exit Sub
End If

success = rest.AddQueryParam("RoleSessionName",credentials.StringOf("role_session_name"))
If (success <> 1) Then
    Debug.Print "Could not set RoleSessionName."
    Exit Sub
End If

success = rest.AddQueryParam("DurationSeconds","3600")
If (success <> 1) Then
    Debug.Print "Could not set DurationSeconds."
    Exit Sub
End If

success = rest.AddQueryParam("WebIdentityToken",credentials.StringOf("web_identity_token"))
If (success <> 1) Then
    Debug.Print "Could not set WebIdentityToken."
    Exit Sub
End If

responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> 1) Then
    Debug.Print "STS transport failed; inspect diagnostics privately."
    Exit Sub
End If

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

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

    End If

    Exit Sub
End If

success = xml.LoadXml(responseXml)
If (success <> 1) Then
    Debug.Print "Invalid STS XML response."
    Exit Sub
End If

success = stringCompare.SetString(xml.Tag)
Dim stringMatch4 As Long
stringMatch4 = stringCompare.ContentsEqual("AssumeRoleWithWebIdentityResponse",1)
If (stringMatch4 <> 1) Then
    Debug.Print "Unexpected STS response root."
    Exit Sub
End If

value = xml.GetChildContent("ResponseMetadata|RequestId")
success = stringCompare.SetString(value)
Dim stringMatch5 As Long
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch5 = 1)) Then
    Debug.Print "Missing or empty ResponseMetadata|RequestId."
    Exit Sub
End If

If (xml.HasChildWithTag("AssumeRoleWithWebIdentityResult") <> 1) Then
    Debug.Print "Missing STS result."
    Exit Sub
End If

accessKey = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId")
success = stringCompare.SetString(accessKey)
Dim stringMatch6 As Long
stringMatch6 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch6 = 1)) Then
    Debug.Print "Missing or empty AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId."
    Exit Sub
End If

secretKey = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey")
success = stringCompare.SetString(secretKey)
Dim stringMatch7 As Long
stringMatch7 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch7 = 1)) Then
    Debug.Print "Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey."
    Exit Sub
End If

sessionToken = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|SessionToken")
success = stringCompare.SetString(sessionToken)
Dim stringMatch8 As Long
stringMatch8 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch8 = 1)) Then
    Debug.Print "Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SessionToken."
    Exit Sub
End If

expiration = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|Expiration")
success = stringCompare.SetString(expiration)
Dim stringMatch9 As Long
stringMatch9 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch9 = 1)) Then
    Debug.Print "Missing or empty AssumeRoleWithWebIdentityResult|Credentials|Expiration."
    Exit Sub
End If

success = expires.SetFromTimestamp(expiration)
If (success <> 1) Then
    Debug.Print "Returned expiration is invalid."
    Exit Sub
End If

success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
    Debug.Print "Could not read current time."
    Exit Sub
End If

If (expires.DiffSeconds(now) <= 60) Then
    Debug.Print "Returned credentials are expired or expire within 60 seconds; obtain fresh credentials."
    Exit Sub
End If

value = xml.GetChildContent("AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn")
success = stringCompare.SetString(value)
Dim stringMatch10 As Long
stringMatch10 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch10 = 1)) Then
    Debug.Print "Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn."
    Exit Sub
End If

value = xml.GetChildContent("AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId")
success = stringCompare.SetString(value)
Dim stringMatch11 As Long
stringMatch11 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch11 = 1)) Then
    Debug.Print "Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId."
    Exit Sub
End If

Dim session As New ChilkatJsonObject
success = session.UpdateString("access_key",accessKey)
If (success <> 1) Then
    Debug.Print "Could not build complete session."
    Exit Sub
End If

success = session.UpdateString("secret_key",secretKey)
If (success <> 1) Then
    Debug.Print "Could not build complete session."
    Exit Sub
End If

success = session.UpdateString("session_token",sessionToken)
If (success <> 1) Then
    Debug.Print "Could not build complete session."
    Exit Sub
End If

success = session.UpdateString("expiration",expiration)
If (success <> 1) Then
    Debug.Print "Could not build complete session."
    Exit Sub
End If

'  Use session in memory; do not print or log session.Emit().
Debug.Print "Session validated; expiration: " & expiration
Debug.Print "Example completed."