AWS STS: GetSessionToken with Optional MFA
See more AWS Security Token Service Examples
Uses Chilkat.Rest and AuthAws with AWS Signature Version 4. STS uses the Query API version 2011-06-15; that version date is still current. The examples send URL-encoded POST forms rather than operation parameters in a GET URL. They use the commercial-partition regional endpoint sts.us-west-2.amazonaws.com and matching signing region/service sts, with explicit TLS certificate verification. Choose the appropriate region/partition endpoint for your deployment.
Load private qa_data/aws/sts.json with nonempty string fields access_key and secret_key. These examples do not discover credentials, assume roles implicitly, or refresh credentials automatically. No access key, secret key, token, full XML response or diagnostic dump is printed.
Both credential-producing examples retain the existing handoff file qa_data/tokens/aws_session_token.xml. It contains plaintext credentials: pre-create a private directory with restrictive OS permissions and keep it out of web roots, source control, shared logs and shared storage. The sample checks the write, but does not set ACLs, encrypt the file, perform atomic replacement, or coordinate concurrent writers. Prefer in-memory handoff or an appropriate credential store in production. A failed request can leave an older file in place; do not assume a failed run refreshed it. The consumer validates expiration, allowing a 60-second margin.
Call with a long-term IAM user access key, not role/session credentials. This example rejects a supplied session_token and requests 3600 seconds. IAM user sessions allow 900–129600 seconds, default 43200. Do not use root credentials. Optional mfa_serial and mfa_code must be supplied together; the code is a six-digit string and can start with zero. Remove the short-lived MFA code from the private configuration after use; production applications should collect it at runtime.
GetSessionToken authenticates the IAM user and needs no permission grant for the GetSessionToken authentication operation. It does not assume a role or restrict the user's permissions via a session policy. The returned credentials inherit the user's permissions; IAM operations require MFA information, and the supported STS calls are limited to AssumeRole and GetCallerIdentity. For other workloads, prefer an appropriate role credential provider.
Chilkat Visual Basic 6.0 Downloads
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
success = stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Long
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = 1)) Then
Debug.Print "Missing or invalid access_key."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Long
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = 1)) Then
Debug.Print "Missing or invalid secret_key."
Exit Sub
End If
Dim expires As New CkDateTime
Dim now As New CkDateTime
Dim region As String
region = "us-west-2"
If (credentials.HasMember("session_token") = 1) Then
Debug.Print "GetSessionToken requires long-term IAM user credentials, not an existing session token."
Exit Sub
End If
' MFA fields are optional as a pair. Preserve a leading zero in the code.
If ((credentials.HasMember("mfa_serial") = 1) Or (credentials.HasMember("mfa_code") = 1)) Then
success = stringCompare.SetString(credentials.StringOf("mfa_serial"))
Dim stringMatch3 As Long
stringMatch3 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("mfa_serial") <> 1) Or (stringMatch3 = 1)) Then
Debug.Print "Missing or invalid mfa_serial."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("mfa_code"))
Dim stringMatch4 As Long
stringMatch4 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("mfa_code") <> 1) Or (stringMatch4 = 1)) Then
Debug.Print "Missing or invalid mfa_code."
Exit Sub
End If
Dim mfaCode As New ChilkatStringBuilder
success = mfaCode.Append(credentials.StringOf("mfa_code"))
If (mfaCode.Length <> 6) Then
Debug.Print "mfa_code must be a six-digit string."
Exit Sub
End If
Dim digits As New ChilkatStringBuilder
success = digits.Append("0123456789")
Dim digitIndex As Long
digitIndex = 0
Do While (digitIndex < 6)
If (digits.Contains(mfaCode.GetRange(digitIndex,1,0),1) <> 1) Then
Debug.Print "mfa_code must contain only ASCII digits."
Exit Sub
End If
digitIndex = digitIndex + 1
Loop
End If
Dim endpoint As New ChilkatStringBuilder
success = endpoint.Append("sts.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New ChilkatAuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sts"
aws.SignatureVersion = 4
Dim rest As New ChilkatRest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = 0
success = rest.SetAuthAws(aws)
If (success <> 1) Then
Debug.Print "Could not configure request signing."
Exit Sub
End If
' 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
success = rest.ClearAllQueryParams()
If (success <> 1) Then
Debug.Print "Could not clear request parameters."
Exit Sub
End If
success = rest.AddQueryParam("Action","GetSessionToken")
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("DurationSeconds","3600")
If (success <> 1) Then
Debug.Print "Could not set DurationSeconds."
Exit Sub
End If
If (credentials.HasMember("mfa_serial") = 1) Then
success = rest.AddQueryParam("SerialNumber",credentials.StringOf("mfa_serial"))
If (success <> 1) Then
Debug.Print "Could not set SerialNumber."
Exit Sub
End If
success = rest.AddQueryParam("TokenCode",credentials.StringOf("mfa_code"))
If (success <> 1) Then
Debug.Print "Could not set TokenCode."
Exit Sub
End If
End If
Dim responseXml As String
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> 1) Then
Debug.Print "STS request did not complete; no credentials were saved. Inspect diagnostics privately."
Exit Sub
End If
success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
Debug.Print "STS HTTP status: " & rest.ResponseStatusCode
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
' Full bodies, headers, and diagnostics can contain sensitive data.
Exit Sub
End If
If (success <> 1) Then
Debug.Print "Invalid STS XML response; no credentials were saved."
Exit Sub
End If
success = stringCompare.SetString(xml.Tag)
Dim stringMatch5 As Long
stringMatch5 = stringCompare.ContentsEqual("GetSessionTokenResponse",1)
If (stringMatch5 <> 1) Then
Debug.Print "Unexpected STS response root."
Exit Sub
End If
value = xml.GetChildContent("ResponseMetadata|RequestId")
success = stringCompare.SetString(value)
Dim stringMatch6 As Long
stringMatch6 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch6 = 1)) Then
Debug.Print "Missing or empty ResponseMetadata|RequestId."
Exit Sub
End If
Debug.Print "AWS request ID: " & value
accessKey = xml.GetChildContent("GetSessionTokenResult|Credentials|AccessKeyId")
success = stringCompare.SetString(accessKey)
Dim stringMatch7 As Long
stringMatch7 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch7 = 1)) Then
Debug.Print "Missing or empty GetSessionTokenResult|Credentials|AccessKeyId."
Exit Sub
End If
secretKey = xml.GetChildContent("GetSessionTokenResult|Credentials|SecretAccessKey")
success = stringCompare.SetString(secretKey)
Dim stringMatch8 As Long
stringMatch8 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch8 = 1)) Then
Debug.Print "Missing or empty GetSessionTokenResult|Credentials|SecretAccessKey."
Exit Sub
End If
sessionToken = xml.GetChildContent("GetSessionTokenResult|Credentials|SessionToken")
success = stringCompare.SetString(sessionToken)
Dim stringMatch9 As Long
stringMatch9 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch9 = 1)) Then
Debug.Print "Missing or empty GetSessionTokenResult|Credentials|SessionToken."
Exit Sub
End If
expiration = xml.GetChildContent("GetSessionTokenResult|Credentials|Expiration")
success = stringCompare.SetString(expiration)
Dim stringMatch10 As Long
stringMatch10 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch10 = 1)) Then
Debug.Print "Missing or empty GetSessionTokenResult|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
' Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
' Reuses the existing handoff filename for the companion S3 example.
success = xml.SaveXml("qa_data/tokens/aws_session_token.xml")
If (success <> 1) Then
Debug.Print "Could not save the private credential file; do not assume it was updated."
Exit Sub
End If
Debug.Print "Temporary credentials saved privately; expiration: " & expiration