AWS STS: Exchange a SAML Assertion 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, principal_arn for the IAM SAML provider, and saml_assertion containing the complete base64-encoded SAML response supplied by your IdP. Do not base64-encode it a second time. Uses unsigned POST with no AWS keys. The IdP metadata, role claims and trust must already be configured. STS verifies the assertion. The session can end sooner than the requested hour due to SessionNotOnOrAfter. IAM Identity Center AWSReservedSSO_ roles are not supported by this operation.
AWS references: AssumeRoleWithSAML
Chilkat B4X Downloads
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
Dim expires As ChilkatDateTime
expires.Initialize
Dim now As ChilkatDateTime
now.Initialize
Dim region As String = "us-west-2"
stringCompare.SetString(credentials.StringOf("role_arn"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("role_arn") <> 1) Or (stringMatch1 = True) Then
Log("Missing or invalid role_arn.")
Return
End If
stringCompare.SetString(credentials.StringOf("principal_arn"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("principal_arn") <> 1) Or (stringMatch2 = True) Then
Log("Missing or invalid principal_arn.")
Return
End If
stringCompare.SetString(credentials.StringOf("saml_assertion"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("saml_assertion") <> 1) Or (stringMatch3 = True) Then
Log("Missing or invalid saml_assertion.")
Return
End If
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("sts.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
' 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", "AssumeRoleWithSAML")
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("RoleArn", credentials.StringOf("role_arn"))
If success <> True Then
Log("Could not set RoleArn.")
Return
End If
success = rest.AddQueryParam("PrincipalArn", credentials.StringOf("principal_arn"))
If success <> True Then
Log("Could not set PrincipalArn.")
Return
End If
success = rest.AddQueryParam("SAMLAssertion", credentials.StringOf("saml_assertion"))
If success <> True Then
Log("Could not set SAMLAssertion.")
Return
End If
success = rest.AddQueryParam("DurationSeconds", "3600")
If success <> True Then
Log("Could not set DurationSeconds.")
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 stringMatch4 As Boolean = stringCompare.ContentsEqual("AssumeRoleWithSAMLResponse", True)
If stringMatch4 <> True Then
Log("Unexpected STS response root.")
Return
End If
value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch5 = True) Then
Log("Missing or empty ResponseMetadata|RequestId.")
Return
End If
If xml.HasChildWithTag("AssumeRoleWithSAMLResult") <> True Then
Log("Missing STS result.")
Return
End If
accessKey = xml.GetChildContent("AssumeRoleWithSAMLResult|Credentials|AccessKeyId")
stringCompare.SetString(accessKey)
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch6 = True) Then
Log("Missing or empty AssumeRoleWithSAMLResult|Credentials|AccessKeyId.")
Return
End If
secretKey = xml.GetChildContent("AssumeRoleWithSAMLResult|Credentials|SecretAccessKey")
stringCompare.SetString(secretKey)
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch7 = True) Then
Log("Missing or empty AssumeRoleWithSAMLResult|Credentials|SecretAccessKey.")
Return
End If
sessionToken = xml.GetChildContent("AssumeRoleWithSAMLResult|Credentials|SessionToken")
stringCompare.SetString(sessionToken)
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch8 = True) Then
Log("Missing or empty AssumeRoleWithSAMLResult|Credentials|SessionToken.")
Return
End If
expiration = xml.GetChildContent("AssumeRoleWithSAMLResult|Credentials|Expiration")
stringCompare.SetString(expiration)
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch9 = True) Then
Log("Missing or empty AssumeRoleWithSAMLResult|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("AssumeRoleWithSAMLResult|AssumedRoleUser|Arn")
stringCompare.SetString(value)
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch10 = True) Then
Log("Missing or empty AssumeRoleWithSAMLResult|AssumedRoleUser|Arn.")
Return
End If
value = xml.GetChildContent("AssumeRoleWithSAMLResult|AssumedRoleUser|AssumedRoleId")
stringCompare.SetString(value)
Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch11 = True) Then
Log("Missing or empty AssumeRoleWithSAMLResult|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.")