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

AWS STS: Refresh an AssumeRole Session Before Expiration

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.

Configure source credentials, role_arn and role_session_name for an unattended role that does not require interactive MFA. Optional qa_data/tokens/sts_session.json holds a previous normalized session for exactly that role, session configuration and workload; keep this cache private and never reuse it across roles. A complete cached set with more than five minutes remaining is reused. Otherwise obtains a new one-hour session, validates it, and publishes one serialized in-memory snapshot. No cache file is overwritten. Existing credentials cannot be extended.

Retries throttling and selected transient HTTP errors at most three times with one- and two-second waits, rebuilding the signed form and checking source expiration on each attempt. Transport, authorization and invalid-response failures stop without publication. Add jitter, synchronization and a credential provider appropriate to your runtime in a concurrent application. This single-thread sample does not implement shared-cache locking or reuse expired sources/MFA codes. Repeat the refresh decision before each unit of work.

AWS references: AssumeRole

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local stringCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Keep this file private and outside public web content/source control.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/sts.json")
if not success then
    print("Could not load private STS configuration.")
    return
end

stringCompare:set_string(credentials:string_of("access_key"))
local stringMatch1 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (stringMatch1) then
    print("Missing or invalid access_key.")
    return
end

stringCompare:set_string(credentials:string_of("secret_key"))
local stringMatch2 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (stringMatch2) then
    print("Missing or invalid secret_key.")
    return
end

local expires = chilkat.DateTime.new()
local now = chilkat.DateTime.new()
local region = "us-west-2"
if credentials:has_member("session_token") then
    stringCompare:set_string(credentials:string_of("session_token"))
    local stringMatch3 = stringCompare:contents_equal("", true)
    if (credentials:json_type_of("session_token") ~= 1) or (stringMatch3) then
        print("Missing or invalid session_token.")
        return
    end

    stringCompare:set_string(credentials:string_of("expiration"))
    local stringMatch4 = stringCompare:contents_equal("", true)
    if (credentials:json_type_of("expiration") ~= 1) or (stringMatch4) then
        print("Missing or invalid expiration.")
        return
    end

    success = expires:set_from_timestamp(credentials:string_of("expiration"))
    if not success then
        print("Source expiration is invalid.")
        return
    end

    success = now:set_from_current_system_time()
    if not success then
        print("Could not read current time.")
        return
    end

    if expires:diff_seconds(now) <= 60 then
        print("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.")
        return
    end
end

stringCompare:set_string(credentials:string_of("role_arn"))
local stringMatch5 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("role_arn") ~= 1) or (stringMatch5) then
    print("Missing or invalid role_arn.")
    return
end

stringCompare:set_string(credentials:string_of("role_session_name"))
local stringMatch6 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("role_session_name") ~= 1) or (stringMatch6) then
    print("Missing or invalid role_session_name.")
    return
end

local identifier = chilkat.StringBuilder.new()
identifier:append(credentials:string_of("role_session_name"))
if (identifier.length < 2) or (identifier.length > 64) then
    print("role_session_name must have 2-64 characters.")
    return
end

local allowed = chilkat.StringBuilder.new()
allowed:append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
local charIndex = 0
while charIndex < identifier.length do
    if not allowed:contains(identifier:get_range(charIndex, 1, false), true) then
        print("Invalid character in role_session_name.")
        return
    end

    charIndex = charIndex + 1
end

if (credentials:has_member("mfa_code")) or (credentials:has_member("mfa_serial")) then
    print("This unattended refresh example does not reuse MFA codes.")
    return
end

-- Optional private cache contains only the four normalized session fields.
-- In an application, keep activeSnapshot in memory between units of work.
local files = chilkat.FileAccess.new()
local cached = chilkat.JsonObject.new()
cached.strict = true
local activeSnapshot = ""
local refreshRequired = true
if files:file_exists("qa_data/tokens/sts_session.json") then
    success = cached:load_file("qa_data/tokens/sts_session.json")
    if not success then
        print("Invalid private cache.")
        return
    end

    stringCompare:set_string(cached:string_of("access_key"))
    local stringMatch7 = stringCompare:contents_equal("", true)
    if (cached:json_type_of("access_key") ~= 1) or (stringMatch7) then
        print("Incomplete private cache.")
        return
    end

    stringCompare:set_string(cached:string_of("secret_key"))
    local stringMatch8 = stringCompare:contents_equal("", true)
    if (cached:json_type_of("secret_key") ~= 1) or (stringMatch8) then
        print("Incomplete private cache.")
        return
    end

    stringCompare:set_string(cached:string_of("session_token"))
    local stringMatch9 = stringCompare:contents_equal("", true)
    if (cached:json_type_of("session_token") ~= 1) or (stringMatch9) then
        print("Incomplete private cache.")
        return
    end

    stringCompare:set_string(cached:string_of("expiration"))
    local stringMatch10 = stringCompare:contents_equal("", true)
    if (cached:json_type_of("expiration") ~= 1) or (stringMatch10) then
        print("Incomplete private cache.")
        return
    end

    success = expires:set_from_timestamp(cached:string_of("expiration"))
    if not success then
        print("Invalid cached expiration.")
        return
    end

    success = now:set_from_current_system_time()
    if not success then
        print("Could not read current time.")
        return
    end

    if expires:diff_seconds(now) > 300 then
        activeSnapshot = cached:emit()
        refreshRequired = false
    end
end

if refreshRequired then
    local endpoint = chilkat.StringBuilder.new()
    endpoint:append("sts.")
    endpoint:append(region)
    endpoint:append(".amazonaws.com")
    local aws = chilkat.AuthAws.new()
    aws.access_key = credentials:string_of("access_key")
    aws.secret_key = credentials:string_of("secret_key")
    aws.region = region
    aws.service_name = "sts"
    aws.signature_version = 4
    local rest = chilkat.Rest.new()
    rest.connect_timeout_ms = 20000
    rest.idle_timeout_ms = 60000
    rest.verbose_logging = false
    success = rest:set_auth_aws(aws)
    if not success then
        print("Could not configure request signing.")
        return
    end

    -- Keep this verified Socket alive while Rest uses its connection.
    local connection = chilkat.Socket.new()
    connection.require_ssl_cert_verify = true
    connection.max_read_idle_ms = 60000
    connection.max_send_idle_ms = 60000
    success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
    if not success then
        print("TLS connection failed; inspect diagnostics privately.")
        return
    end

    success = rest:use_connection(connection, true)
    if not success then
        print("Could not attach TLS connection.")
        return
    end

    local xml = chilkat.Xml.new()
    xml.strict = true
    local value = ""
    local responseXml = ""
    local attempt = 0
    local delayMs = 1000
    local received = false
    local retryable = false
    while (attempt < 3) and (not received) do
        if credentials:has_member("session_token") then
            stringCompare:set_string(credentials:string_of("session_token"))
            local stringMatch11 = stringCompare:contents_equal("", true)
            if (credentials:json_type_of("session_token") ~= 1) or (stringMatch11) then
                print("Missing or invalid session_token.")
                return
            end

            stringCompare:set_string(credentials:string_of("expiration"))
            local stringMatch12 = stringCompare:contents_equal("", true)
            if (credentials:json_type_of("expiration") ~= 1) or (stringMatch12) then
                print("Missing or invalid expiration.")
                return
            end

            success = expires:set_from_timestamp(credentials:string_of("expiration"))
            if not success then
                print("Source expiration is invalid.")
                return
            end

            success = now:set_from_current_system_time()
            if not success then
                print("Could not read current time.")
                return
            end

            if expires:diff_seconds(now) <= 60 then
                print("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.")
                return
            end
        end

        attempt = attempt + 1
        success = rest:clear_all_query_params()
        if not success then
            print("Could not reset request parameters.")
            return
        end

        success = rest:add_query_param("Action", "AssumeRole")
        if not success then
            print("Could not set Action.")
            return
        end

        success = rest:add_query_param("Version", "2011-06-15")
        if not success then
            print("Could not set Version.")
            return
        end

        if credentials:has_member("session_token") then
            success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
            if not success then
                print("Could not set X-Amz-Security-Token.")
                return
            end
        end

        success = rest:add_query_param("RoleArn", credentials:string_of("role_arn"))
        if not success then
            print("Could not set RoleArn.")
            return
        end

        success = rest:add_query_param("RoleSessionName", credentials:string_of("role_session_name"))
        if not success then
            print("Could not set RoleSessionName.")
            return
        end

        success = rest:add_query_param("DurationSeconds", "3600")
        if not success then
            print("Could not set DurationSeconds.")
            return
        end

        responseXml = rest:full_request_form_url_encoded("POST", "/")
        if not rest.last_method_success then
            print("Transport failed; credential refresh was not published.")
            return
        end

        if rest.response_status_code == 200 then
            received = true
        end

        if rest.response_status_code ~= 200 then
            retryable = false
            value = ""
            success = xml:load_xml(responseXml)
            if success then
                value = xml:get_child_content("Error|Code")
            end

            stringCompare:set_string(value)
            local stringMatch13 = stringCompare:contents_equal("Throttling", true)
            stringCompare:set_string(value)
            local stringMatch14 = stringCompare:contents_equal("ThrottlingException", true)
            if (rest.response_status_code == 429) or ((rest.response_status_code == 500) or ((rest.response_status_code == 502) or ((rest.response_status_code == 503) or ((rest.response_status_code == 504) or ((stringMatch13) or (stringMatch14)))))) then
                retryable = true
            end

            if (not retryable) or (attempt == 3) then
                print("Refresh failed. HTTP status: " .. rest.response_status_code)
                print("AWS error code: " .. value)
                return
            end

            connection:sleep_ms(delayMs)
            delayMs = delayMs * 2
        end
    end

    if not received then
        print("Refresh attempts exhausted.")
        return
    end

    success = xml:load_xml(responseXml)
    if not success then
        print("Invalid STS XML response.")
        return
    end

    stringCompare:set_string(xml.tag)
    local stringMatch15 = stringCompare:contents_equal("AssumeRoleResponse", true)
    if not stringMatch15 then
        print("Unexpected STS response root.")
        return
    end

    value = xml:get_child_content("ResponseMetadata|RequestId")
    stringCompare:set_string(value)
    local stringMatch16 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch16) then
        print("Missing or empty ResponseMetadata|RequestId.")
        return
    end

    if not xml:has_child_with_tag("AssumeRoleResult") then
        print("Missing STS result.")
        return
    end

    local accessKey = xml:get_child_content("AssumeRoleResult|Credentials|AccessKeyId")
    stringCompare:set_string(accessKey)
    local stringMatch17 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch17) then
        print("Missing or empty AssumeRoleResult|Credentials|AccessKeyId.")
        return
    end

    local secretKey = xml:get_child_content("AssumeRoleResult|Credentials|SecretAccessKey")
    stringCompare:set_string(secretKey)
    local stringMatch18 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch18) then
        print("Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.")
        return
    end

    local sessionToken = xml:get_child_content("AssumeRoleResult|Credentials|SessionToken")
    stringCompare:set_string(sessionToken)
    local stringMatch19 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch19) then
        print("Missing or empty AssumeRoleResult|Credentials|SessionToken.")
        return
    end

    local expiration = xml:get_child_content("AssumeRoleResult|Credentials|Expiration")
    stringCompare:set_string(expiration)
    local stringMatch20 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch20) then
        print("Missing or empty AssumeRoleResult|Credentials|Expiration.")
        return
    end

    success = expires:set_from_timestamp(expiration)
    if not success then
        print("Returned expiration is invalid.")
        return
    end

    success = now:set_from_current_system_time()
    if not success then
        print("Could not read current time.")
        return
    end

    if expires:diff_seconds(now) <= 60 then
        print("Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.")
        return
    end

    value = xml:get_child_content("AssumeRoleResult|AssumedRoleUser|Arn")
    stringCompare:set_string(value)
    local stringMatch21 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch21) then
        print("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.")
        return
    end

    value = xml:get_child_content("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
    stringCompare:set_string(value)
    local stringMatch22 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch22) then
        print("Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.")
        return
    end

    local session = chilkat.JsonObject.new()
    success = session:update_string("access_key", accessKey)
    if not success then
        print("Could not build complete session.")
        return
    end

    success = session:update_string("secret_key", secretKey)
    if not success then
        print("Could not build complete session.")
        return
    end

    success = session:update_string("session_token", sessionToken)
    if not success then
        print("Could not build complete session.")
        return
    end

    success = session:update_string("expiration", expiration)
    if not success then
        print("Could not build complete session.")
        return
    end

    -- Use session in memory; do not print or log session.Emit().
    print("Session validated; expiration: " .. expiration)
    -- Publish one complete snapshot only after validating every returned field.
    activeSnapshot = session:emit()
end

-- Rehydrate a complete set for the next unit of work, never four partial updates.
local usable = chilkat.JsonObject.new()
usable.strict = true
success = usable:load(activeSnapshot)
if not success then
    print("Could not load the complete session snapshot.")
    return
end

-- Pass usable to your service client here. Do not log activeSnapshot.
print("Session ready for the next unit of work; expiration: " .. usable:string_of("expiration"))
print("Example completed.")