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

AWS STS: Assume a Role for S3 Bucket Listing

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.

Set role_arn and role_session_name in the private configuration. Names must contain 2–64 allowed characters. The target trust policy and applicable caller authorization must permit AssumeRole. The sample's session policy permits only s3:ListAllMyBuckets, intersected with the role's permissions, for use by the companion S3 listing example; it cannot elevate the role's access. Other policy types, denies and resource-based rules still participate in authorization.

The fixed 3600-second request works within the one-hour role-chaining ceiling and must still fit the role's configured maximum. For temporary source credentials, also provide nonempty session_token and ISO 8601 expiration. The token is included in the signed form body. Optional external_id must be the value agreed with the role owner; it is not a password. Optional source_identity is subject to AWS syntax, trust conditions and sts:SetSourceIdentity permission. Optional MFA uses mfa_serial/mfa_code as a pair. These optional values must satisfy the actual trust policy.

This focused example omits managed session policies and session tags. When adding them, configure the required policies and tagging permissions, and account for inherited transitive tags during role chaining. STS session-token sizes are variable; preserve the complete value without a fixed buffer or truncation.

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

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

    success = expires.SetFromTimestamp(credentials.stringOf("expiration"))
    if (success != true)
        print "Source 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 "Source credentials are expired or expire within 60 seconds; obtain fresh credentials." + "\n";
        exit
    end

end

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

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

identifier = Chilkat::CkStringBuilder.new()
identifier.Append(credentials.stringOf("role_session_name"))
if ((identifier.get_Length() < 2) or (identifier.get_Length() > 64))
    print "role_session_name must have 2-64 characters." + "\n";
    exit
end

allowed = Chilkat::CkStringBuilder.new()
allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
charIndex = 0
while (charIndex < identifier.get_Length())
    if (allowed.Contains(identifier.getRange(charIndex,1,false),true) != true)
        print "Invalid character in role_session_name." + "\n";
        exit
    end

    charIndex = charIndex + 1
end
roleArn = Chilkat::CkStringBuilder.new()
roleArn.Append(credentials.stringOf("role_arn"))
if ((roleArn.StartsWith("arn:aws:iam::",true) != true) or (roleArn.Contains(":role/",true) != true))
    print "Use an IAM role ARN in the commercial AWS partition." + "\n";
    exit
end

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

end

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

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

    stringCompare.SetString(credentials.stringOf("mfa_code"))
    stringMatch10 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("mfa_code") != 1) or (stringMatch10 == 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","AssumeRole")
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("session_token") == true)
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
    if (success != true)
        print "Could not set X-Amz-Security-Token." + "\n";
        exit
    end

end

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

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

#  A session policy only restricts the role; it cannot add permissions.
policy = Chilkat::CkJsonObject.new()
success = policy.UpdateString("Version","2012-10-17")
if (success != true)
    print "Could not set policy version." + "\n";
    exit
end

success = policy.UpdateString("Statement[0].Effect","Allow")
if (success != true)
    print "Could not set policy effect." + "\n";
    exit
end

success = policy.UpdateString("Statement[0].Action","s3:ListAllMyBuckets")
if (success != true)
    print "Could not set policy action." + "\n";
    exit
end

success = policy.UpdateString("Statement[0].Resource","*")
if (success != true)
    print "Could not set policy resource." + "\n";
    exit
end

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

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

end

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

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())
stringMatch11 = stringCompare.ContentsEqual("AssumeRoleResponse",true)
if (stringMatch11 != true)
    print "Unexpected STS response root." + "\n";
    exit
end

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

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

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

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

expiration = xml.getChildContent("AssumeRoleResult|Credentials|Expiration")
stringCompare.SetString(expiration)
stringMatch16 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch16 == true))
    print "Missing or empty AssumeRoleResult|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

value = xml.getChildContent("AssumeRoleResult|AssumedRoleUser|Arn")
stringCompare.SetString(value)
stringMatch17 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch17 == true))
    print "Missing or empty AssumeRoleResult|AssumedRoleUser|Arn." + "\n";
    exit
end

value = xml.getChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
stringCompare.SetString(value)
stringMatch18 = stringCompare.ContentsEqual("",true)
if ((xml.get_LastMethodSuccess() != true) or (stringMatch18 == true))
    print "Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId." + "\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";