AWS STS: Exchange an OIDC Token for Role Credentials
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.
Provide role_arn, role_session_name and the complete web_identity_token from your OIDC provider. The exchange is unsigned: no AWS access key or SigV4 header is sent. Configure the IAM provider and role trust for the expected issuer, audience and subject. STS validates the token; this sample does not treat decoding a JWT as verification. Refresh expired input through your identity provider.
AWS references: AssumeRoleWithWebIdentity
Chilkat Lua Downloads
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
local expires = chilkat.DateTime.new()
local now = chilkat.DateTime.new()
local region = "us-west-2"
stringCompare:set_string(credentials:string_of("role_arn"))
local stringMatch1 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("role_arn") ~= 1) or (stringMatch1) then
print("Missing or invalid role_arn.")
return
end
stringCompare:set_string(credentials:string_of("role_session_name"))
local stringMatch2 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("role_session_name") ~= 1) or (stringMatch2) 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
stringCompare:set_string(credentials:string_of("web_identity_token"))
local stringMatch3 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("web_identity_token") ~= 1) or (stringMatch3) then
print("Missing or invalid web_identity_token.")
return
end
local endpoint = chilkat.StringBuilder.new()
endpoint:append("sts.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
rest.verbose_logging = false
-- 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", "AssumeRoleWithWebIdentity")
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("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
success = rest:add_query_param("WebIdentityToken", credentials:string_of("web_identity_token"))
if not success then
print("Could not set WebIdentityToken.")
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 stringMatch4 = stringCompare:contents_equal("AssumeRoleWithWebIdentityResponse", true)
if not stringMatch4 then
print("Unexpected STS response root.")
return
end
value = xml:get_child_content("ResponseMetadata|RequestId")
stringCompare:set_string(value)
local stringMatch5 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch5) then
print("Missing or empty ResponseMetadata|RequestId.")
return
end
if not xml:has_child_with_tag("AssumeRoleWithWebIdentityResult") then
print("Missing STS result.")
return
end
local accessKey = xml:get_child_content("AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId")
stringCompare:set_string(accessKey)
local stringMatch6 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch6) then
print("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId.")
return
end
local secretKey = xml:get_child_content("AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey")
stringCompare:set_string(secretKey)
local stringMatch7 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch7) then
print("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey.")
return
end
local sessionToken = xml:get_child_content("AssumeRoleWithWebIdentityResult|Credentials|SessionToken")
stringCompare:set_string(sessionToken)
local stringMatch8 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch8) then
print("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SessionToken.")
return
end
local expiration = xml:get_child_content("AssumeRoleWithWebIdentityResult|Credentials|Expiration")
stringCompare:set_string(expiration)
local stringMatch9 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch9) then
print("Missing or empty AssumeRoleWithWebIdentityResult|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("AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn")
stringCompare:set_string(value)
local stringMatch10 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch10) then
print("Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn.")
return
end
value = xml:get_child_content("AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId")
stringCompare:set_string(value)
local stringMatch11 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch11) then
print("Missing or empty AssumeRoleWithWebIdentityResult|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)
print("Example completed.")