AWS STS: Obtain an AWS-Signed JWT for an External Service
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.
Set audience to the intended external service. Requests RS256 with a five-minute lifetime from a regional STS endpoint; outbound federation must be enabled for the account. Optional subject_mode is AWSIdentity or OriginIdentity. OriginIdentity requires the caller's trusted identity propagation context. Optional scope is permitted only for OriginIdentity and this single audience, and requires sts:SetWebIdentityTokenScope in addition to sts:GetWebIdentityToken. Validates scope spacing, characters and duplicate values.
The returned token is an external identity JWT, not an AWS access key/session-token credential set. The recipient must validate its signature using the trusted issuer's JWKS, issuer, audience and lifetime; merely decoding it is insufficient. The request cannot extend the calling session's lifetime.
AWS references: GetWebIdentityToken
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
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("audience"))
local stringMatch5 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("audience") ~= 1) or (stringMatch5) then
print("Missing or invalid audience.")
return
end
-- Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
local subjectMode = "AWSIdentity"
if credentials:has_member("subject_mode") then
stringCompare:set_string(credentials:string_of("subject_mode"))
local stringMatch6 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("subject_mode") ~= 1) or (stringMatch6) then
print("Missing or invalid subject_mode.")
return
end
subjectMode = credentials:string_of("subject_mode")
end
stringCompare:set_string(subjectMode)
local stringMatch7 = stringCompare:contents_equal("AWSIdentity", true)
stringCompare:set_string(subjectMode)
local stringMatch8 = stringCompare:contents_equal("OriginIdentity", true)
if (not stringMatch7) and (not stringMatch8) then
print("Invalid subject_mode.")
return
end
if credentials:has_member("scope") then
stringCompare:set_string(credentials:string_of("scope"))
local stringMatch9 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("scope") ~= 1) or (stringMatch9) then
print("Missing or invalid scope.")
return
end
stringCompare:set_string(subjectMode)
local stringMatch10 = stringCompare:contents_equal("OriginIdentity", true)
if not stringMatch10 then
print("scope requires OriginIdentity.")
return
end
local scopeText = chilkat.StringBuilder.new()
scopeText:append(credentials:string_of("scope"))
if (scopeText.length > 256) or ((scopeText:starts_with(" ", true)) or ((scopeText:ends_with(" ", true)) or (scopeText:contains(" ", true)))) then
print("Invalid scope length or spacing.")
return
end
local allowedScope = chilkat.StringBuilder.new()
allowedScope:append("!#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ")
local scopeIndex = 0
while scopeIndex < scopeText.length do
if not allowedScope:contains(scopeText:get_range(scopeIndex, 1, false), true) then
print("Invalid scope character.")
return
end
scopeIndex = scopeIndex + 1
end
local scopeValues = chilkat.StringTable.new()
success = scopeValues:split_and_append(scopeText:get_as_string(), " ", false, false)
if not success then
print("Could not split scope values.")
return
end
local seenScopes = chilkat.Hashtable.new()
scopeIndex = 0
local scopeValue = ""
while scopeIndex < scopeValues.count do
scopeValue = scopeValues:string_at(scopeIndex)
if seenScopes:contains(scopeValue) then
print("Duplicate scope value.")
return
end
success = seenScopes:add_str(scopeValue, "seen")
if not success then
print("Could not track scope values.")
return
end
scopeIndex = scopeIndex + 1
end
end
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 = ""
success = rest:clear_all_query_params()
if not success then
print("Could not reset request parameters.")
return
end
success = rest:add_query_param("Action", "GetWebIdentityToken")
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("Audience.member.1", credentials:string_of("audience"))
if not success then
print("Could not set Audience.member.1.")
return
end
success = rest:add_query_param("SigningAlgorithm", "RS256")
if not success then
print("Could not set SigningAlgorithm.")
return
end
success = rest:add_query_param("DurationSeconds", "300")
if not success then
print("Could not set DurationSeconds.")
return
end
success = rest:add_query_param("SubjectMode", subjectMode)
if not success then
print("Could not set SubjectMode.")
return
end
if credentials:has_member("scope") then
success = rest:add_query_param("Scope", credentials:string_of("scope"))
if not success then
print("Could not set Scope.")
return
end
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 stringMatch11 = stringCompare:contents_equal("GetWebIdentityTokenResponse", true)
if not stringMatch11 then
print("Unexpected STS response root.")
return
end
value = xml:get_child_content("ResponseMetadata|RequestId")
stringCompare:set_string(value)
local stringMatch12 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch12) then
print("Missing or empty ResponseMetadata|RequestId.")
return
end
if not xml:has_child_with_tag("GetWebIdentityTokenResult") then
print("Missing STS result.")
return
end
local sessionToken = xml:get_child_content("GetWebIdentityTokenResult|WebIdentityToken")
stringCompare:set_string(sessionToken)
local stringMatch13 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch13) then
print("Missing or empty GetWebIdentityTokenResult|WebIdentityToken.")
return
end
local expiration = xml:get_child_content("GetWebIdentityTokenResult|Expiration")
stringCompare:set_string(expiration)
local stringMatch14 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch14) then
print("Missing or empty GetWebIdentityTokenResult|Expiration.")
return
end
success = expires:set_from_timestamp(expiration)
if not success then
print("JWT 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("JWT credentials are expired or expire within 60 seconds; obtain fresh credentials.")
return
end
-- Hand sessionToken to the intended external service over TLS; never log it.
print("Web identity token obtained; expiration: " .. expiration)
print("Example completed.")