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

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.

AWS API reference

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

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

    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 ComStringOf Of hoCredentials "access_key" To sTemp1
    Get ComSetString Of hoStringCompare sTemp1 To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch1
    Get ComJsonTypeOf Of hoCredentials "access_key" To iTemp1
    If ((iTemp1 <> 1) Or (iStringMatch1 = True)) Begin
        Showln "Missing or invalid access_key."
        Procedure_Return
    End

    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    Get ComSetString Of hoStringCompare sTemp1 To iSuccess
    Get ComContentsEqual Of hoStringCompare "" True To iStringMatch2
    Get ComJsonTypeOf Of hoCredentials "secret_key" To iTemp1
    If ((iTemp1 <> 1) Or (iStringMatch2 = True)) Begin
        Showln "Missing or invalid secret_key."
        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 ComHasMember Of hoCredentials "session_token" To bTemp1
    If (bTemp1 = True) Begin
        Showln "GetSessionToken requires long-term IAM user credentials, not an existing session token."
        Procedure_Return
    End

    //  MFA fields are optional as a pair. Preserve a leading zero in the code.
    Get ComHasMember Of hoCredentials "mfa_serial" To bTemp1
    Get ComHasMember Of hoCredentials "mfa_code" To bTemp2
    If ((bTemp1 = True) Or (bTemp2 = True)) Begin
        Get ComStringOf Of hoCredentials "mfa_serial" To sTemp1
        Get ComSetString Of hoStringCompare sTemp1 To iSuccess
        Get ComContentsEqual Of hoStringCompare "" True To iStringMatch3
        Get ComJsonTypeOf Of hoCredentials "mfa_serial" To iTemp1
        If ((iTemp1 <> 1) Or (iStringMatch3 = True)) Begin
            Showln "Missing or invalid mfa_serial."
            Procedure_Return
        End

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

        Get Create (RefClass(cComChilkatStringBuilder)) To hoMfaCode
        If (Not(IsComObjectCreated(hoMfaCode))) Begin
            Send CreateComObject of hoMfaCode
        End
        Get ComStringOf Of hoCredentials "mfa_code" To sTemp1
        Get ComAppend Of hoMfaCode sTemp1 To iSuccess
        Get ComLength Of hoMfaCode To iTemp1
        If (iTemp1 <> 6) Begin
            Showln "mfa_code must be a six-digit string."
            Procedure_Return
        End

        Get Create (RefClass(cComChilkatStringBuilder)) To hoDigits
        If (Not(IsComObjectCreated(hoDigits))) Begin
            Send CreateComObject of hoDigits
        End
        Get ComAppend Of hoDigits "0123456789" To iSuccess
        Move 0 To iDigitIndex
        While (iDigitIndex < 6)
            Get ComContains Of hoDigits (ComGetRange(hoMfaCode, iDigitIndex, 1, False)) True To bTemp1
            If (bTemp1 <> True) Begin
                Showln "mfa_code must contain only ASCII digits."
                Procedure_Return
            End

            Move (iDigitIndex + 1) To iDigitIndex
        Loop

    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(cComChilkatAuthAws)) To hoAws
    If (Not(IsComObjectCreated(hoAws))) Begin
        Send CreateComObject of hoAws
    End
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    Set ComAccessKey Of hoAws To sTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    Set ComSecretKey Of hoAws To sTemp1
    Set ComRegion Of hoAws To sRegion
    Set ComServiceName Of hoAws To "sts"
    Set ComSignatureVersion Of hoAws To 4
    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
    Get pvComObject of hoAws to vAws
    Get ComSetAuthAws Of hoRest vAws To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not configure request signing."
        Procedure_Return
    End

    //  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

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

    Get ComAddQueryParam Of hoRest "Action" "GetSessionToken" 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 ComAddQueryParam Of hoRest "DurationSeconds" "3600" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set DurationSeconds."
        Procedure_Return
    End

    Get ComHasMember Of hoCredentials "mfa_serial" To bTemp1
    If (bTemp1 = True) Begin
        Get ComStringOf Of hoCredentials "mfa_serial" To sTemp1
        Get ComAddQueryParam Of hoRest "SerialNumber" sTemp1 To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not set SerialNumber."
            Procedure_Return
        End

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

    End

    Get ComFullRequestFormUrlEncoded Of hoRest "POST" "/" To sResponseXml
    Get ComLastMethodSuccess Of hoRest To bTemp1
    If (bTemp1 <> True) Begin
        Showln "STS request did not complete; no credentials were saved. Inspect diagnostics privately."
        Procedure_Return
    End

    Get ComLoadXml Of hoXml sResponseXml To iSuccess
    Get ComResponseStatusCode Of hoRest To iTemp1
    If (iTemp1 <> 200) Begin
        Get ComResponseStatusCode Of hoRest To iTemp1
        Showln "STS HTTP status: " iTemp1
        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

        //  Full bodies, headers, and diagnostics can contain sensitive data.
        Procedure_Return
    End

    If (iSuccess <> True) Begin
        Showln "Invalid STS XML response; no credentials were saved."
        Procedure_Return
    End

    Get ComTag Of hoXml To sTemp1
    Get ComSetString Of hoStringCompare sTemp1 To iSuccess
    Get ComContentsEqual Of hoStringCompare "GetSessionTokenResponse" True To iStringMatch5
    If (iStringMatch5 <> 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 iStringMatch6
    Get ComLastMethodSuccess Of hoXml To bTemp1
    If ((bTemp1 <> True) Or (iStringMatch6 = True)) Begin
        Showln "Missing or empty ResponseMetadata|RequestId."
        Procedure_Return
    End

    Showln "AWS request ID: " sValue
    Get ComGetChildContent Of hoXml "GetSessionTokenResult|Credentials|AccessKeyId" To sAccessKey
    Get ComSetString Of hoStringCompare sAccessKey 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 GetSessionTokenResult|Credentials|AccessKeyId."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "GetSessionTokenResult|Credentials|SecretAccessKey" To sSecretKey
    Get ComSetString Of hoStringCompare sSecretKey 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 GetSessionTokenResult|Credentials|SecretAccessKey."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "GetSessionTokenResult|Credentials|SessionToken" To sSessionToken
    Get ComSetString Of hoStringCompare sSessionToken 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 GetSessionTokenResult|Credentials|SessionToken."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "GetSessionTokenResult|Credentials|Expiration" To sExpiration
    Get ComSetString Of hoStringCompare sExpiration 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 GetSessionTokenResult|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

    //  Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
    //  Reuses the existing handoff filename for the companion S3 example.
    Get ComSaveXml Of hoXml "qa_data/tokens/aws_session_token.xml" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not save the private credential file; do not assume it was updated."
        Procedure_Return
    End

    Showln "Temporary credentials saved privately; expiration: " sExpiration


End_Procedure