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

AWS STS: Assume a Cross-Account Role with ExternalId and MFA

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.

Configure role_arn, role_session_name, external_id and mfa_serial. Supply the current code as a string in private sts_mfa_input.json, for example {"mfa_code":"012345"}; replace the file-input step with your application's runtime prompt. Remove that short-lived file after use. Requires caller authorization for the target role plus its trust policy permitting the caller, agreed ExternalId and MFA condition. ExternalId is not a password. No retry reuses the MFA code.

AWS references: AssumeRole

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("role_arn"))
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("role_arn") <> 1) Or (stringMatch5 = True) Then
    Log("Missing or invalid role_arn.")
    Return
End If

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

Dim identifier As ChilkatStringBuilder
identifier.Initialize
identifier.Append(credentials.StringOf("role_session_name"))
If (identifier.Length < 2) Or (identifier.Length > 64) Then
    Log("role_session_name must have 2-64 characters.")
    Return
End If

Dim allowed As ChilkatStringBuilder
allowed.Initialize
allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
Dim charIndex As Int = 0
Do While (charIndex < identifier.Length)
    If allowed.Contains(identifier.GetRange(charIndex, 1, False), True) <> True Then
        Log("Invalid character in role_session_name.")
        Return
    End If

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

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

'  Supply the current six-digit code from your application input at this point.
'  This portable sample reads a fresh, private, short-lived input file.
Dim mfaInput As ChilkatJsonObject
mfaInput.Initialize
mfaInput.Strict = True
success = mfaInput.LoadFile("qa_data/aws/sts_mfa_input.json")
If success <> True Then
    Log("Could not read current MFA input.")
    Return
End If

stringCompare.SetString(mfaInput.StringOf("mfa_code"))
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("", True)
If (mfaInput.JsonTypeOf("mfa_code") <> 1) Or (stringMatch9 = True) Then
    Log("Missing MFA code.")
    Return
End If

success = credentials.UpdateString("mfa_code", mfaInput.StringOf("mfa_code"))
If success <> True Then
    Log("Could not set MFA input.")
    Return
End If

'  MFA fields are optional as a pair. Preserve a leading zero in the code.
If (credentials.HasMember("mfa_serial") = True) Or (credentials.HasMember("mfa_code") = True) Then
    stringCompare.SetString(credentials.StringOf("mfa_serial"))
    Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("", True)
    If (credentials.JsonTypeOf("mfa_serial") <> 1) Or (stringMatch10 = True) Then
        Log("Missing or invalid mfa_serial.")
        Return
    End If

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

    Dim mfaCode As ChilkatStringBuilder
    mfaCode.Initialize
    mfaCode.Append(credentials.StringOf("mfa_code"))
    If mfaCode.Length <> 6 Then
        Log("mfa_code must be a six-digit string.")
        Return
    End If

    Dim digits As ChilkatStringBuilder
    digits.Initialize
    digits.Append("0123456789")
    Dim digitIndex As Int = 0
    Do While (digitIndex < 6)
        If digits.Contains(mfaCode.GetRange(digitIndex, 1, False), True) <> True Then
            Log("mfa_code must contain only ASCII digits.")
            Return
        End If

        digitIndex = digitIndex + 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 accessKey As String
Dim secretKey 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", "AssumeRole")
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("RoleArn", credentials.StringOf("role_arn"))
If success <> True Then
    Log("Could not set RoleArn.")
    Return
End If

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

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

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

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

success = rest.AddQueryParam("TokenCode", credentials.StringOf("mfa_code"))
If success <> True Then
    Log("Could not set TokenCode.")
    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 stringMatch12 As Boolean = stringCompare.ContentsEqual("AssumeRoleResponse", True)
If stringMatch12 <> True Then
    Log("Unexpected STS response root.")
    Return
End If

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

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

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

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

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

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

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

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

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

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

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

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

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

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