Sample code for 30+ languages & platforms
Visual FoxPro 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 Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loStringCompare
LOCAL loCredentials
LOCAL lnStringMatch1
LOCAL lnStringMatch2
LOCAL loExpires
LOCAL loNow
LOCAL lcRegion
LOCAL lnStringMatch3
LOCAL lnStringMatch4
LOCAL loMfaCode
LOCAL loDigits
LOCAL lnDigitIndex
LOCAL loEndpoint
LOCAL loAws
LOCAL loRest
LOCAL loConnection
LOCAL loXml
LOCAL lcValue
LOCAL lcAccessKey
LOCAL lcSecretKey
LOCAL lcSessionToken
LOCAL lcExpiration
LOCAL lcResponseXml
LOCAL lnStringMatch5
LOCAL lnStringMatch6
LOCAL lnStringMatch7
LOCAL lnStringMatch8
LOCAL lnStringMatch9
LOCAL lnStringMatch10

lnSuccess = 0

loStringCompare = CreateObject('Chilkat.StringBuilder')
*  Assumes Chilkat is unlocked. See Global Unlock Sample.
*  Keep this file private and outside public web content/source control.
loCredentials = CreateObject('Chilkat.JsonObject')
loCredentials.Strict = 1
lnSuccess = loCredentials.LoadFile("qa_data/aws/sts.json")
IF (lnSuccess <> 1) THEN
    ? "Could not load private STS configuration."
    RELEASE loStringCompare
    RELEASE loCredentials
    CANCEL
ENDIF

loStringCompare.SetString(loCredentials.StringOf("access_key"))
lnStringMatch1 = loStringCompare.ContentsEqual("",1)
IF ((loCredentials.JsonTypeOf("access_key") <> 1) OR (lnStringMatch1 = 1)) THEN
    ? "Missing or invalid access_key."
    RELEASE loStringCompare
    RELEASE loCredentials
    CANCEL
ENDIF

loStringCompare.SetString(loCredentials.StringOf("secret_key"))
lnStringMatch2 = loStringCompare.ContentsEqual("",1)
IF ((loCredentials.JsonTypeOf("secret_key") <> 1) OR (lnStringMatch2 = 1)) THEN
    ? "Missing or invalid secret_key."
    RELEASE loStringCompare
    RELEASE loCredentials
    CANCEL
ENDIF

loExpires = CreateObject('Chilkat.CkDateTime')
loNow = CreateObject('Chilkat.CkDateTime')
lcRegion = "us-west-2"
IF (loCredentials.HasMember("session_token") = 1) THEN
    ? "GetSessionToken requires long-term IAM user credentials, not an existing session token."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    CANCEL
ENDIF

*  MFA fields are optional as a pair. Preserve a leading zero in the code.
IF ((loCredentials.HasMember("mfa_serial") = 1) OR (loCredentials.HasMember("mfa_code") = 1)) THEN
    loStringCompare.SetString(loCredentials.StringOf("mfa_serial"))
    lnStringMatch3 = loStringCompare.ContentsEqual("",1)
    IF ((loCredentials.JsonTypeOf("mfa_serial") <> 1) OR (lnStringMatch3 = 1)) THEN
        ? "Missing or invalid mfa_serial."
        RELEASE loStringCompare
        RELEASE loCredentials
        RELEASE loExpires
        RELEASE loNow
        CANCEL
    ENDIF

    loStringCompare.SetString(loCredentials.StringOf("mfa_code"))
    lnStringMatch4 = loStringCompare.ContentsEqual("",1)
    IF ((loCredentials.JsonTypeOf("mfa_code") <> 1) OR (lnStringMatch4 = 1)) THEN
        ? "Missing or invalid mfa_code."
        RELEASE loStringCompare
        RELEASE loCredentials
        RELEASE loExpires
        RELEASE loNow
        CANCEL
    ENDIF

    loMfaCode = CreateObject('Chilkat.StringBuilder')
    loMfaCode.Append(loCredentials.StringOf("mfa_code"))
    IF (loMfaCode.Length <> 6) THEN
        ? "mfa_code must be a six-digit string."
        RELEASE loStringCompare
        RELEASE loCredentials
        RELEASE loExpires
        RELEASE loNow
        RELEASE loMfaCode
        CANCEL
    ENDIF

    loDigits = CreateObject('Chilkat.StringBuilder')
    loDigits.Append("0123456789")
    lnDigitIndex = 0
    DO WHILE (lnDigitIndex < 6)
        IF (loDigits.Contains(loMfaCode.GetRange(lnDigitIndex,1,0),1) <> 1) THEN
            ? "mfa_code must contain only ASCII digits."
            RELEASE loStringCompare
            RELEASE loCredentials
            RELEASE loExpires
            RELEASE loNow
            RELEASE loMfaCode
            RELEASE loDigits
            CANCEL
        ENDIF

        lnDigitIndex = lnDigitIndex + 1
    ENDDO
ENDIF

loEndpoint = CreateObject('Chilkat.StringBuilder')
loEndpoint.Append("sts.")
loEndpoint.Append(lcRegion)
loEndpoint.Append(".amazonaws.com")
loAws = CreateObject('Chilkat.AuthAws')
loAws.AccessKey = loCredentials.StringOf("access_key")
loAws.SecretKey = loCredentials.StringOf("secret_key")
loAws.Region = lcRegion
loAws.ServiceName = "sts"
loAws.SignatureVersion = 4
loRest = CreateObject('Chilkat.Rest')
loRest.ConnectTimeoutMs = 20000
loRest.IdleTimeoutMs = 60000
loRest.VerboseLogging = 0
lnSuccess = loRest.SetAuthAws(loAws)
IF (lnSuccess <> 1) THEN
    ? "Could not configure request signing."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    CANCEL
ENDIF

*  Keep this verified Socket alive while Rest uses its connection.
loConnection = CreateObject('Chilkat.Socket')
loConnection.RequireSslCertVerify = 1
loConnection.MaxReadIdleMs = 60000
loConnection.MaxSendIdleMs = 60000
lnSuccess = loConnection.Connect(loEndpoint.GetAsString(),443,1,20000)
IF (lnSuccess <> 1) THEN
    ? "TLS connection failed; inspect diagnostics privately."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    CANCEL
ENDIF

lnSuccess = loRest.UseConnection(loConnection,1)
IF (lnSuccess <> 1) THEN
    ? "Could not attach TLS connection."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    CANCEL
ENDIF

loXml = CreateObject('Chilkat.Xml')
loXml.Strict = 1

lnSuccess = loRest.ClearAllQueryParams()
IF (lnSuccess <> 1) THEN
    ? "Could not clear request parameters."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Action","GetSessionToken")
IF (lnSuccess <> 1) THEN
    ? "Could not set Action."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Version","2011-06-15")
IF (lnSuccess <> 1) THEN
    ? "Could not set Version."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("DurationSeconds","3600")
IF (lnSuccess <> 1) THEN
    ? "Could not set DurationSeconds."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF (loCredentials.HasMember("mfa_serial") = 1) THEN
    lnSuccess = loRest.AddQueryParam("SerialNumber",loCredentials.StringOf("mfa_serial"))
    IF (lnSuccess <> 1) THEN
        ? "Could not set SerialNumber."
        RELEASE loStringCompare
        RELEASE loCredentials
        RELEASE loExpires
        RELEASE loNow
        RELEASE loMfaCode
        RELEASE loDigits
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        CANCEL
    ENDIF

    lnSuccess = loRest.AddQueryParam("TokenCode",loCredentials.StringOf("mfa_code"))
    IF (lnSuccess <> 1) THEN
        ? "Could not set TokenCode."
        RELEASE loStringCompare
        RELEASE loCredentials
        RELEASE loExpires
        RELEASE loNow
        RELEASE loMfaCode
        RELEASE loDigits
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        CANCEL
    ENDIF

ENDIF

lcResponseXml = loRest.FullRequestFormUrlEncoded("POST","/")
IF (loRest.LastMethodSuccess <> 1) THEN
    ? "STS request did not complete; no credentials were saved. Inspect diagnostics privately."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loXml.LoadXml(lcResponseXml)
IF (loRest.ResponseStatusCode <> 200) THEN
    ? "STS HTTP status: " + STR(loRest.ResponseStatusCode)
    IF (lnSuccess = 1) THEN
        lcValue = loXml.GetChildContent("Error|Code")
        IF (loXml.LastMethodSuccess = 1) THEN
            ? "AWS error code: " + lcValue
        ENDIF

        lcValue = loXml.GetChildContent("RequestId")
        IF (loXml.LastMethodSuccess = 1) THEN
            ? "AWS request ID: " + lcValue
        ENDIF

    ENDIF

    *  Full bodies, headers, and diagnostics can contain sensitive data.
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF (lnSuccess <> 1) THEN
    ? "Invalid STS XML response; no credentials were saved."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

loStringCompare.SetString(loXml.Tag)
lnStringMatch5 = loStringCompare.ContentsEqual("GetSessionTokenResponse",1)
IF (lnStringMatch5 <> 1) THEN
    ? "Unexpected STS response root."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lcValue = loXml.GetChildContent("ResponseMetadata|RequestId")
loStringCompare.SetString(lcValue)
lnStringMatch6 = loStringCompare.ContentsEqual("",1)
IF ((loXml.LastMethodSuccess <> 1) OR (lnStringMatch6 = 1)) THEN
    ? "Missing or empty ResponseMetadata|RequestId."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

? "AWS request ID: " + lcValue
lcAccessKey = loXml.GetChildContent("GetSessionTokenResult|Credentials|AccessKeyId")
loStringCompare.SetString(lcAccessKey)
lnStringMatch7 = loStringCompare.ContentsEqual("",1)
IF ((loXml.LastMethodSuccess <> 1) OR (lnStringMatch7 = 1)) THEN
    ? "Missing or empty GetSessionTokenResult|Credentials|AccessKeyId."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lcSecretKey = loXml.GetChildContent("GetSessionTokenResult|Credentials|SecretAccessKey")
loStringCompare.SetString(lcSecretKey)
lnStringMatch8 = loStringCompare.ContentsEqual("",1)
IF ((loXml.LastMethodSuccess <> 1) OR (lnStringMatch8 = 1)) THEN
    ? "Missing or empty GetSessionTokenResult|Credentials|SecretAccessKey."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lcSessionToken = loXml.GetChildContent("GetSessionTokenResult|Credentials|SessionToken")
loStringCompare.SetString(lcSessionToken)
lnStringMatch9 = loStringCompare.ContentsEqual("",1)
IF ((loXml.LastMethodSuccess <> 1) OR (lnStringMatch9 = 1)) THEN
    ? "Missing or empty GetSessionTokenResult|Credentials|SessionToken."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lcExpiration = loXml.GetChildContent("GetSessionTokenResult|Credentials|Expiration")
loStringCompare.SetString(lcExpiration)
lnStringMatch10 = loStringCompare.ContentsEqual("",1)
IF ((loXml.LastMethodSuccess <> 1) OR (lnStringMatch10 = 1)) THEN
    ? "Missing or empty GetSessionTokenResult|Credentials|Expiration."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loExpires.SetFromTimestamp(lcExpiration)
IF (lnSuccess <> 1) THEN
    ? "Returned expiration is invalid."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loNow.SetFromCurrentSystemTime()
IF (lnSuccess <> 1) THEN
    ? "Could not read current time."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF (loExpires.DiffSeconds(loNow) <= 60) THEN
    ? "Returned credentials are expired or expire within 60 seconds; obtain fresh credentials."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

*  Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
*  Reuses the existing handoff filename for the companion S3 example.
lnSuccess = loXml.SaveXml("qa_data/tokens/aws_session_token.xml")
IF (lnSuccess <> 1) THEN
    ? "Could not save the private credential file; do not assume it was updated."
    RELEASE loStringCompare
    RELEASE loCredentials
    RELEASE loExpires
    RELEASE loNow
    RELEASE loMfaCode
    RELEASE loDigits
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

? "Temporary credentials saved privately; expiration: " + lcExpiration

RELEASE loStringCompare
RELEASE loCredentials
RELEASE loExpires
RELEASE loNow
RELEASE loMfaCode
RELEASE loDigits
RELEASE loEndpoint
RELEASE loAws
RELEASE loRest
RELEASE loConnection
RELEASE loXml