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

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Keep this file private and outside public web content/source control.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/sts.json")
if (success != true)
    print "Could not load private STS configuration." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true))
    print "Missing or invalid access_key." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true))
    print "Missing or invalid secret_key." + "\n";
    exit
end

expires = Chilkat::CkDateTime.new()
now = Chilkat::CkDateTime.new()
region = "us-west-2"
if (credentials.HasMember("session_token") == true)
    print "GetSessionToken requires long-term IAM user credentials, not an existing session token." + "\n";
    exit
end

#  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))
    stringCompare.SetString(credentials.stringOf("mfa_serial"))
    stringMatch3 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("mfa_serial") != 1) or (stringMatch3 == true))
        print "Missing or invalid mfa_serial." + "\n";
        exit
    end

    stringCompare.SetString(credentials.stringOf("mfa_code"))
    stringMatch4 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("mfa_code") != 1) or (stringMatch4 == true))
        print "Missing or invalid mfa_code." + "\n";
        exit
    end

    mfaCode = Chilkat::CkStringBuilder.new()
    mfaCode.Append(credentials.stringOf("mfa_code"))
    if (mfaCode.get_Length() != 6)
        print "mfa_code must be a six-digit string." + "\n";
        exit
    end

    digits = Chilkat::CkStringBuilder.new()
    digits.Append("0123456789")
    digitIndex = 0
    while (digitIndex < 6)
        if (digits.Contains(mfaCode.getRange(digitIndex,1,false),true) != true)
            print "mfa_code must contain only ASCII digits." + "\n";
            exit
        end

        digitIndex = digitIndex + 1
    end
end

endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("sts.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = Chilkat::CkAuthAws.new()
aws.put_AccessKey(credentials.stringOf("access_key"))
aws.put_SecretKey(credentials.stringOf("secret_key"))
aws.put_Region(region)
aws.put_ServiceName("sts")
aws.put_SignatureVersion(4)
rest = Chilkat::CkRest.new()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
rest.put_VerboseLogging(false)
success = rest.SetAuthAws(aws)
if (success != true)
    print "Could not configure request signing." + "\n";
    exit
end

#  Keep this verified Socket alive while Rest uses its connection.
connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,true,20000)
if (success != true)
    print "TLS connection failed; inspect diagnostics privately." + "\n";
    exit
end

success = rest.UseConnection(connection,true)
if (success != true)
    print "Could not attach TLS connection." + "\n";
    exit
end

xml = Chilkat::CkXml.new()
xml.put_Strict(true)

success = rest.ClearAllQueryParams()
if (success != true)
    print "Could not clear request parameters." + "\n";
    exit
end

success = rest.AddQueryParam("Action","GetSessionToken")
if (success != true)
    print "Could not set Action." + "\n";
    exit
end

success = rest.AddQueryParam("Version","2011-06-15")
if (success != true)
    print "Could not set Version." + "\n";
    exit
end

success = rest.AddQueryParam("DurationSeconds","3600")
if (success != true)
    print "Could not set DurationSeconds." + "\n";
    exit
end

if (credentials.HasMember("mfa_serial") == true)
    success = rest.AddQueryParam("SerialNumber",credentials.stringOf("mfa_serial"))
    if (success != true)
        print "Could not set SerialNumber." + "\n";
        exit
    end

    success = rest.AddQueryParam("TokenCode",credentials.stringOf("mfa_code"))
    if (success != true)
        print "Could not set TokenCode." + "\n";
        exit
    end

end

responseXml = rest.fullRequestFormUrlEncoded("POST","/")
if (rest.get_LastMethodSuccess() != true)
    print "STS request did not complete; no credentials were saved. Inspect diagnostics privately." + "\n";
    exit
end

success = xml.LoadXml(responseXml)
if (rest.get_ResponseStatusCode() != 200)
    print "STS HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    if (success == true)
        value = xml.getChildContent("Error|Code")
        if (xml.get_LastMethodSuccess() == true)
            print "AWS error code: " + value + "\n";
        end

        value = xml.getChildContent("RequestId")
        if (xml.get_LastMethodSuccess() == true)
            print "AWS request ID: " + value + "\n";
        end

    end

    #  Full bodies, headers, and diagnostics can contain sensitive data.
    exit
end

if (success != true)
    print "Invalid STS XML response; no credentials were saved." + "\n";
    exit
end

stringCompare.SetString(xml.tag())
stringMatch5 = stringCompare.ContentsEqual("GetSessionTokenResponse",true)
if (stringMatch5 != true)
    print "Unexpected STS response root." + "\n";
    exit
end

value = xml.getChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
stringMatch6 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch6 == true))
    print "Missing or empty ResponseMetadata|RequestId." + "\n";
    exit
end

print "AWS request ID: " + value + "\n";
accessKey = xml.getChildContent("GetSessionTokenResult|Credentials|AccessKeyId")
stringCompare.SetString(accessKey)
stringMatch7 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch7 == true))
    print "Missing or empty GetSessionTokenResult|Credentials|AccessKeyId." + "\n";
    exit
end

secretKey = xml.getChildContent("GetSessionTokenResult|Credentials|SecretAccessKey")
stringCompare.SetString(secretKey)
stringMatch8 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch8 == true))
    print "Missing or empty GetSessionTokenResult|Credentials|SecretAccessKey." + "\n";
    exit
end

sessionToken = xml.getChildContent("GetSessionTokenResult|Credentials|SessionToken")
stringCompare.SetString(sessionToken)
stringMatch9 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch9 == true))
    print "Missing or empty GetSessionTokenResult|Credentials|SessionToken." + "\n";
    exit
end

expiration = xml.getChildContent("GetSessionTokenResult|Credentials|Expiration")
stringCompare.SetString(expiration)
stringMatch10 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch10 == true))
    print "Missing or empty GetSessionTokenResult|Credentials|Expiration." + "\n";
    exit
end

success = expires.SetFromTimestamp(expiration)
if (success != true)
    print "Returned expiration is invalid." + "\n";
    exit
end

success = now.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read current time." + "\n";
    exit
end

if (expires.DiffSeconds(now) <= 60)
    print "Returned credentials are expired or expire within 60 seconds; obtain fresh credentials." + "\n";
    exit
end

#  Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
#  Reuses the existing handoff filename for the companion S3 example.
success = xml.SaveXml("qa_data/tokens/aws_session_token.xml")
if (success != true)
    print "Could not save the private credential file; do not assume it was updated." + "\n";
    exit
end

print "Temporary credentials saved privately; expiration: " + expiration + "\n";