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

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 DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoStringCompare
    Handle hoCredentials
    Handle hoExpires
    Variant vNow
    Handle hoNow
    String sRegion
    Boolean iStringMatch1
    Boolean iStringMatch2
    Boolean iStringMatch3
    Handle hoEndpoint
    Handle hoRest
    Variant vConnection
    Handle hoConnection
    Handle hoXml
    String sValue
    String sAccessKey
    String sSecretKey
    String sSessionToken
    String sExpiration
    String sResponseXml
    Boolean iStringMatch4
    Boolean iStringMatch5
    Boolean iStringMatch6
    Boolean iStringMatch7
    Boolean iStringMatch8
    Boolean iStringMatch9
    Boolean iStringMatch10
    Boolean iStringMatch11
    Handle hoSession
    String sTemp1
    Integer iTemp1
    Boolean bTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatStringBuilder)) To hoStringCompare
    If (Not(IsComObjectCreated(hoStringCompare))) Begin
        Send CreateComObject of hoStringCompare
    End
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Keep this file private and outside public web content/source control.
    Get Create (RefClass(cComChilkatJsonObject)) To hoCredentials
    If (Not(IsComObjectCreated(hoCredentials))) Begin
        Send CreateComObject of hoCredentials
    End
    Set ComStrict Of hoCredentials To True
    Get ComLoadFile Of hoCredentials "qa_data/aws/sts.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load private STS configuration."
        Procedure_Return
    End

    Get Create (RefClass(cComCkDateTime)) To hoExpires
    If (Not(IsComObjectCreated(hoExpires))) Begin
        Send CreateComObject of hoExpires
    End
    Get Create (RefClass(cComCkDateTime)) To hoNow
    If (Not(IsComObjectCreated(hoNow))) Begin
        Send CreateComObject of hoNow
    End
    Move "us-west-2" To sRegion
    Get ComStringOf Of hoCredentials "role_arn" To sTemp1
    Get ComSetString Of hoStringCompare sTemp1 To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch1
    Get ComJsonTypeOf Of hoCredentials "role_arn" To iTemp1
    If ((iTemp1 <> 1) Or (iStringMatch1 = True)) Begin
        Showln "Missing or invalid role_arn."
        Procedure_Return
    End

    Get ComStringOf Of hoCredentials "principal_arn" To sTemp1
    Get ComSetString Of hoStringCompare sTemp1 To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch2
    Get ComJsonTypeOf Of hoCredentials "principal_arn" To iTemp1
    If ((iTemp1 <> 1) Or (iStringMatch2 = True)) Begin
        Showln "Missing or invalid principal_arn."
        Procedure_Return
    End

    Get ComStringOf Of hoCredentials "saml_assertion" To sTemp1
    Get ComSetString Of hoStringCompare sTemp1 To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch3
    Get ComJsonTypeOf Of hoCredentials "saml_assertion" To iTemp1
    If ((iTemp1 <> 1) Or (iStringMatch3 = True)) Begin
        Showln "Missing or invalid saml_assertion."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
    If (Not(IsComObjectCreated(hoEndpoint))) Begin
        Send CreateComObject of hoEndpoint
    End
    Get ComAppend Of hoEndpoint "sts." To iSuccess
    Get ComAppend Of hoEndpoint sRegion To iSuccess
    Get ComAppend Of hoEndpoint ".amazonaws.com" To iSuccess
    Get Create (RefClass(cComChilkatRest)) To hoRest
    If (Not(IsComObjectCreated(hoRest))) Begin
        Send CreateComObject of hoRest
    End
    Set ComConnectTimeoutMs Of hoRest To 20000
    Set ComIdleTimeoutMs Of hoRest To 60000
    Set ComVerboseLogging Of hoRest To False
    //  Keep this verified Socket alive while Rest uses its connection.
    Get Create (RefClass(cComChilkatSocket)) To hoConnection
    If (Not(IsComObjectCreated(hoConnection))) Begin
        Send CreateComObject of hoConnection
    End
    Set ComRequireSslCertVerify Of hoConnection To True
    Set ComMaxReadIdleMs Of hoConnection To 60000
    Set ComMaxSendIdleMs Of hoConnection To 60000
    Get ComGetAsString Of hoEndpoint To sTemp1
    Get ComConnect Of hoConnection sTemp1 443 True 20000 To iSuccess
    If (iSuccess <> True) Begin
        Showln "TLS connection failed; inspect diagnostics privately."
        Procedure_Return
    End

    Get pvComObject of hoConnection to vConnection
    Get ComUseConnection Of hoRest vConnection True To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not attach TLS connection."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatXml)) To hoXml
    If (Not(IsComObjectCreated(hoXml))) Begin
        Send CreateComObject of hoXml
    End
    Set ComStrict Of hoXml To True

    Move "" To sResponseXml
    Get ComClearAllQueryParams Of hoRest To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not reset request parameters."
        Procedure_Return
    End

    Get ComAddQueryParam Of hoRest "Action" "AssumeRoleWithSAML" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set Action."
        Procedure_Return
    End

    Get ComAddQueryParam Of hoRest "Version" "2011-06-15" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set Version."
        Procedure_Return
    End

    Get ComStringOf Of hoCredentials "role_arn" To sTemp1
    Get ComAddQueryParam Of hoRest "RoleArn" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set RoleArn."
        Procedure_Return
    End

    Get ComStringOf Of hoCredentials "principal_arn" To sTemp1
    Get ComAddQueryParam Of hoRest "PrincipalArn" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set PrincipalArn."
        Procedure_Return
    End

    Get ComStringOf Of hoCredentials "saml_assertion" To sTemp1
    Get ComAddQueryParam Of hoRest "SAMLAssertion" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set SAMLAssertion."
        Procedure_Return
    End

    Get ComAddQueryParam Of hoRest "DurationSeconds" "3600" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set DurationSeconds."
        Procedure_Return
    End

    Get ComFullRequestFormUrlEncoded Of hoRest "POST" "/" To sResponseXml
    Get ComLastMethodSuccess Of hoRest To bTemp1
    If (bTemp1 <> True) Begin
        Showln "STS transport failed; inspect diagnostics privately."
        Procedure_Return
    End

    Get ComResponseStatusCode Of hoRest To iTemp1
    If (iTemp1 <> 200) Begin
        Get ComResponseStatusCode Of hoRest To iTemp1
        Showln "STS HTTP status: " iTemp1
        Get ComLoadXml Of hoXml sResponseXml To iSuccess
        If (iSuccess = True) Begin
            Get ComGetChildContent Of hoXml "Error|Code" To sValue
            Get ComLastMethodSuccess Of hoXml To bTemp1
            If (bTemp1 = True) Begin
                Showln "AWS error code: " sValue
            End

            Get ComGetChildContent Of hoXml "RequestId" To sValue
            Get ComLastMethodSuccess Of hoXml To bTemp1
            If (bTemp1 = True) Begin
                Showln "AWS request ID: " sValue
            End

        End

        Procedure_Return
    End

    Get ComLoadXml Of hoXml sResponseXml To iSuccess
    If (iSuccess <> True) Begin
        Showln "Invalid STS XML response."
        Procedure_Return
    End

    Get ComTag Of hoXml To sTemp1
    Get ComSetString Of hoStringCompare sTemp1 To iSuccess
    Get ComContentsEqual Of hoStringCompare "AssumeRoleWithSAMLResponse" True To iStringMatch4
    If (iStringMatch4 <> True) Begin
        Showln "Unexpected STS response root."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "ResponseMetadata|RequestId" To sValue
    Get ComSetString Of hoStringCompare sValue To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch5
    Get ComLastMethodSuccess Of hoXml To bTemp1
    If ((bTemp1 <> True) Or (iStringMatch5 = True)) Begin
        Showln "Missing or empty ResponseMetadata|RequestId."
        Procedure_Return
    End

    Get ComHasChildWithTag Of hoXml "AssumeRoleWithSAMLResult" To bTemp1
    If (bTemp1 <> True) Begin
        Showln "Missing STS result."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "AssumeRoleWithSAMLResult|Credentials|AccessKeyId" To sAccessKey
    Get ComSetString Of hoStringCompare sAccessKey To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch6
    Get ComLastMethodSuccess Of hoXml To bTemp1
    If ((bTemp1 <> True) Or (iStringMatch6 = True)) Begin
        Showln "Missing or empty AssumeRoleWithSAMLResult|Credentials|AccessKeyId."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "AssumeRoleWithSAMLResult|Credentials|SecretAccessKey" To sSecretKey
    Get ComSetString Of hoStringCompare sSecretKey To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch7
    Get ComLastMethodSuccess Of hoXml To bTemp1
    If ((bTemp1 <> True) Or (iStringMatch7 = True)) Begin
        Showln "Missing or empty AssumeRoleWithSAMLResult|Credentials|SecretAccessKey."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "AssumeRoleWithSAMLResult|Credentials|SessionToken" To sSessionToken
    Get ComSetString Of hoStringCompare sSessionToken To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch8
    Get ComLastMethodSuccess Of hoXml To bTemp1
    If ((bTemp1 <> True) Or (iStringMatch8 = True)) Begin
        Showln "Missing or empty AssumeRoleWithSAMLResult|Credentials|SessionToken."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "AssumeRoleWithSAMLResult|Credentials|Expiration" To sExpiration
    Get ComSetString Of hoStringCompare sExpiration To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch9
    Get ComLastMethodSuccess Of hoXml To bTemp1
    If ((bTemp1 <> True) Or (iStringMatch9 = True)) Begin
        Showln "Missing or empty AssumeRoleWithSAMLResult|Credentials|Expiration."
        Procedure_Return
    End

    Get ComSetFromTimestamp Of hoExpires sExpiration To iSuccess
    If (iSuccess <> True) Begin
        Showln "Returned expiration is invalid."
        Procedure_Return
    End

    Get ComSetFromCurrentSystemTime Of hoNow To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not read current time."
        Procedure_Return
    End

    Get ComDiffSeconds Of hoExpires     Get pvComObject of hoNow to vNow
vNow To iTemp1
    If (iTemp1 <= 60) Begin
        Showln "Returned credentials are expired or expire within 60 seconds; obtain fresh credentials."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "AssumeRoleWithSAMLResult|AssumedRoleUser|Arn" To sValue
    Get ComSetString Of hoStringCompare sValue To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch10
    Get ComLastMethodSuccess Of hoXml To bTemp1
    If ((bTemp1 <> True) Or (iStringMatch10 = True)) Begin
        Showln "Missing or empty AssumeRoleWithSAMLResult|AssumedRoleUser|Arn."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "AssumeRoleWithSAMLResult|AssumedRoleUser|AssumedRoleId" To sValue
    Get ComSetString Of hoStringCompare sValue To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch11
    Get ComLastMethodSuccess Of hoXml To bTemp1
    If ((bTemp1 <> True) Or (iStringMatch11 = True)) Begin
        Showln "Missing or empty AssumeRoleWithSAMLResult|AssumedRoleUser|AssumedRoleId."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoSession
    If (Not(IsComObjectCreated(hoSession))) Begin
        Send CreateComObject of hoSession
    End
    Get ComUpdateString Of hoSession "access_key" sAccessKey To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not build complete session."
        Procedure_Return
    End

    Get ComUpdateString Of hoSession "secret_key" sSecretKey To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not build complete session."
        Procedure_Return
    End

    Get ComUpdateString Of hoSession "session_token" sSessionToken To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not build complete session."
        Procedure_Return
    End

    Get ComUpdateString Of hoSession "expiration" sExpiration To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not build complete session."
        Procedure_Return
    End

    //  Use session in memory; do not print or log session.Emit().
    Showln "Session validated; expiration: " sExpiration
    Showln "Example completed."


End_Procedure