AWS STS: Normalize STS Credentials and Use Chilkat.Rest
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.
Reads only private qa_data/tokens/aws_session_token.xml; no sts.json is needed. Accepts all seven credential-producing STS response roots, including the existing GetSessionToken/AssumeRole handoff. Builds a complete normalized in-memory session and uses it to sign GetCallerIdentity. The normalized fields are access_key, secret_key, session_token and expiration. Checks expiration with a 60-second margin before connecting. JWT-only GetWebIdentityToken responses are intentionally not credential sets.
AWS references: GetCallerIdentity
Chilkat Lua Downloads
local chilkat = require("chilkat")
local stringCompare = chilkat.StringBuilder.new()
-- Load a privately stored STS XML response; never print its contents.
local tokenXml = chilkat.Xml.new()
tokenXml.strict = true
local success = tokenXml:load_xml_file("qa_data/tokens/aws_session_token.xml")
if not success then
print("Could not load private STS XML.")
return
end
local credentialPath = ""
stringCompare:set_string(tokenXml.tag)
local stringMatch1 = stringCompare:contents_equal("GetSessionTokenResponse", true)
if stringMatch1 then
credentialPath = "GetSessionTokenResult|Credentials"
end
stringCompare:set_string(tokenXml.tag)
local stringMatch2 = stringCompare:contents_equal("AssumeRoleResponse", true)
if stringMatch2 then
credentialPath = "AssumeRoleResult|Credentials"
end
stringCompare:set_string(tokenXml.tag)
local stringMatch3 = stringCompare:contents_equal("AssumeRoleWithWebIdentityResponse", true)
if stringMatch3 then
credentialPath = "AssumeRoleWithWebIdentityResult|Credentials"
end
stringCompare:set_string(tokenXml.tag)
local stringMatch4 = stringCompare:contents_equal("AssumeRoleWithSAMLResponse", true)
if stringMatch4 then
credentialPath = "AssumeRoleWithSAMLResult|Credentials"
end
stringCompare:set_string(tokenXml.tag)
local stringMatch5 = stringCompare:contents_equal("GetFederationTokenResponse", true)
if stringMatch5 then
credentialPath = "GetFederationTokenResult|Credentials"
end
stringCompare:set_string(tokenXml.tag)
local stringMatch6 = stringCompare:contents_equal("GetDelegatedAccessTokenResponse", true)
if stringMatch6 then
credentialPath = "GetDelegatedAccessTokenResult|Credentials"
end
stringCompare:set_string(tokenXml.tag)
local stringMatch7 = stringCompare:contents_equal("AssumeRootResponse", true)
if stringMatch7 then
credentialPath = "AssumeRootResult|Credentials"
end
stringCompare:set_string(credentialPath)
local stringMatch8 = stringCompare:contents_equal("", true)
if stringMatch8 then
print("Unsupported STS credential response.")
return
end
local path = chilkat.StringBuilder.new()
success = path:set_string(credentialPath)
if not success then
print("Could not construct credential path.")
return
end
success = path:append("|AccessKeyId")
if not success then
print("Could not construct credential path.")
return
end
local accessKey = tokenXml:get_child_content(path:get_as_string())
stringCompare:set_string(accessKey)
local stringMatch9 = stringCompare:contents_equal("", true)
if (not tokenXml.last_method_success) or (stringMatch9) then
print("Missing credential field AccessKeyId.")
return
end
success = path:set_string(credentialPath)
if not success then
print("Could not construct credential path.")
return
end
success = path:append("|SecretAccessKey")
if not success then
print("Could not construct credential path.")
return
end
local secretKey = tokenXml:get_child_content(path:get_as_string())
stringCompare:set_string(secretKey)
local stringMatch10 = stringCompare:contents_equal("", true)
if (not tokenXml.last_method_success) or (stringMatch10) then
print("Missing credential field SecretAccessKey.")
return
end
success = path:set_string(credentialPath)
if not success then
print("Could not construct credential path.")
return
end
success = path:append("|SessionToken")
if not success then
print("Could not construct credential path.")
return
end
local sessionToken = tokenXml:get_child_content(path:get_as_string())
stringCompare:set_string(sessionToken)
local stringMatch11 = stringCompare:contents_equal("", true)
if (not tokenXml.last_method_success) or (stringMatch11) then
print("Missing credential field SessionToken.")
return
end
success = path:set_string(credentialPath)
if not success then
print("Could not construct credential path.")
return
end
success = path:append("|Expiration")
if not success then
print("Could not construct credential path.")
return
end
local expiration = tokenXml:get_child_content(path:get_as_string())
stringCompare:set_string(expiration)
local stringMatch12 = stringCompare:contents_equal("", true)
if (not tokenXml.last_method_success) or (stringMatch12) then
print("Missing credential field Expiration.")
return
end
local expires = chilkat.DateTime.new()
local now = chilkat.DateTime.new()
success = expires:set_from_timestamp(expiration)
if not success then
print("Stored 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("Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.")
return
end
local session = chilkat.JsonObject.new()
success = session:update_string("access_key", accessKey)
if not success then
print("Could not build normalized session.")
return
end
success = session:update_string("secret_key", secretKey)
if not success then
print("Could not build normalized session.")
return
end
success = session:update_string("session_token", sessionToken)
if not success then
print("Could not build normalized session.")
return
end
success = session:update_string("expiration", expiration)
if not success then
print("Could not build normalized session.")
return
end
local region = "us-west-2"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("sts.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
local aws = chilkat.AuthAws.new()
aws.access_key = session:string_of("access_key")
aws.secret_key = session: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 = ""
success = rest:clear_all_query_params()
if not success then
print("Could not reset request parameters.")
return
end
success = rest:add_query_param("Action", "GetCallerIdentity")
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
success = rest:add_query_param("X-Amz-Security-Token", session:string_of("session_token"))
if not success then
print("Could not set X-Amz-Security-Token.")
return
end
local responseXml = rest:full_request_form_url_encoded("POST", "/")
if not rest.last_method_success then
print("STS transport failed; inspect diagnostics privately.")
return
end
if rest.response_status_code ~= 200 then
print("STS HTTP status: " .. rest.response_status_code)
success = xml:load_xml(responseXml)
if success then
value = xml:get_child_content("Error|Code")
if xml.last_method_success then
print("AWS error code: " .. value)
end
value = xml:get_child_content("RequestId")
if xml.last_method_success then
print("AWS request ID: " .. value)
end
end
return
end
success = xml:load_xml(responseXml)
if not success then
print("Invalid STS XML response.")
return
end
stringCompare:set_string(xml.tag)
local stringMatch13 = stringCompare:contents_equal("GetCallerIdentityResponse", true)
if not stringMatch13 then
print("Unexpected STS response root.")
return
end
value = xml:get_child_content("ResponseMetadata|RequestId")
stringCompare:set_string(value)
local stringMatch14 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch14) then
print("Missing or empty ResponseMetadata|RequestId.")
return
end
if not xml:has_child_with_tag("GetCallerIdentityResult") then
print("Missing STS result.")
return
end
value = xml:get_child_content("GetCallerIdentityResult|Arn")
stringCompare:set_string(value)
local stringMatch15 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch15) then
print("Missing or empty GetCallerIdentityResult|Arn.")
return
end
print("Authenticated principal: " .. value)
print("Example completed.")