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 Python Downloads
import sys
import chilkat2
success = False
stringCompare = chilkat2.StringBuilder()
# Assumes Chilkat is unlocked. See Global Unlock Sample.
# Keep this file private and outside public web content/source control.
credentials = chilkat2.JsonObject()
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/sts.json")
if (success != True):
print("Could not load private STS configuration.")
sys.exit()
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.")
sys.exit()
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.")
sys.exit()
expires = chilkat2.CkDateTime()
now = chilkat2.CkDateTime()
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.")
sys.exit()
stringCompare.SetString(credentials.StringOf("expiration"))
stringMatch4 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("expiration") != 1) or (stringMatch4 == True)):
print("Missing or invalid expiration.")
sys.exit()
success = expires.SetFromTimestamp(credentials.StringOf("expiration"))
if (success != True):
print("Source expiration is invalid.")
sys.exit()
success = now.SetFromCurrentSystemTime()
if (success != True):
print("Could not read current time.")
sys.exit()
if (expires.DiffSeconds(now) <= 60):
print("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.")
sys.exit()
stringCompare.SetString(credentials.StringOf("audience"))
stringMatch5 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("audience") != 1) or (stringMatch5 == True)):
print("Missing or invalid audience.")
sys.exit()
# Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
subjectMode = "AWSIdentity"
if (credentials.HasMember("subject_mode") == True):
stringCompare.SetString(credentials.StringOf("subject_mode"))
stringMatch6 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("subject_mode") != 1) or (stringMatch6 == True)):
print("Missing or invalid subject_mode.")
sys.exit()
subjectMode = credentials.StringOf("subject_mode")
stringCompare.SetString(subjectMode)
stringMatch7 = stringCompare.ContentsEqual("AWSIdentity",True)
stringCompare.SetString(subjectMode)
stringMatch8 = stringCompare.ContentsEqual("OriginIdentity",True)
if ((stringMatch7 != True) and (stringMatch8 != True)):
print("Invalid subject_mode.")
sys.exit()
if (credentials.HasMember("scope") == True):
stringCompare.SetString(credentials.StringOf("scope"))
stringMatch9 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("scope") != 1) or (stringMatch9 == True)):
print("Missing or invalid scope.")
sys.exit()
stringCompare.SetString(subjectMode)
stringMatch10 = stringCompare.ContentsEqual("OriginIdentity",True)
if (stringMatch10 != True):
print("scope requires OriginIdentity.")
sys.exit()
scopeText = chilkat2.StringBuilder()
scopeText.Append(credentials.StringOf("scope"))
if ((scopeText.Length > 256) or (scopeText.StartsWith(" ",True) == True) or (scopeText.EndsWith(" ",True) == True) or (scopeText.Contains(" ",True) == True)):
print("Invalid scope length or spacing.")
sys.exit()
allowedScope = chilkat2.StringBuilder()
allowedScope.Append("!#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ")
scopeIndex = 0
while (scopeIndex < scopeText.Length) :
if (allowedScope.Contains(scopeText.GetRange(scopeIndex,1,False),True) != True):
print("Invalid scope character.")
sys.exit()
scopeIndex = scopeIndex + 1
scopeValues = chilkat2.StringTable()
success = scopeValues.SplitAndAppend(scopeText.GetAsString()," ",False,False)
if (success != True):
print("Could not split scope values.")
sys.exit()
seenScopes = chilkat2.Hashtable()
scopeIndex = 0
while (scopeIndex < scopeValues.Count) :
scopeValue = scopeValues.StringAt(scopeIndex)
if (seenScopes.Contains(scopeValue) == True):
print("Duplicate scope value.")
sys.exit()
success = seenScopes.AddStr(scopeValue,"seen")
if (success != True):
print("Could not track scope values.")
sys.exit()
scopeIndex = scopeIndex + 1
endpoint = chilkat2.StringBuilder()
endpoint.Append("sts.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = chilkat2.AuthAws()
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sts"
aws.SignatureVersion = 4
rest = chilkat2.Rest()
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
if (success != True):
print("Could not configure request signing.")
sys.exit()
# Keep this verified Socket alive while Rest uses its connection.
connection = chilkat2.Socket()
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
if (success != True):
print("TLS connection failed; inspect diagnostics privately.")
sys.exit()
success = rest.UseConnection(connection,True)
if (success != True):
print("Could not attach TLS connection.")
sys.exit()
xml = chilkat2.Xml()
xml.Strict = True
responseXml = ""
success = rest.ClearAllQueryParams()
if (success != True):
print("Could not reset request parameters.")
sys.exit()
success = rest.AddQueryParam("Action","GetWebIdentityToken")
if (success != True):
print("Could not set Action.")
sys.exit()
success = rest.AddQueryParam("Version","2011-06-15")
if (success != True):
print("Could not set Version.")
sys.exit()
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.")
sys.exit()
success = rest.AddQueryParam("Audience.member.1",credentials.StringOf("audience"))
if (success != True):
print("Could not set Audience.member.1.")
sys.exit()
success = rest.AddQueryParam("SigningAlgorithm","RS256")
if (success != True):
print("Could not set SigningAlgorithm.")
sys.exit()
success = rest.AddQueryParam("DurationSeconds","300")
if (success != True):
print("Could not set DurationSeconds.")
sys.exit()
success = rest.AddQueryParam("SubjectMode",subjectMode)
if (success != True):
print("Could not set SubjectMode.")
sys.exit()
if (credentials.HasMember("scope") == True):
success = rest.AddQueryParam("Scope",credentials.StringOf("scope"))
if (success != True):
print("Could not set Scope.")
sys.exit()
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
if (rest.LastMethodSuccess != True):
print("STS transport failed; inspect diagnostics privately.")
sys.exit()
if (rest.ResponseStatusCode != 200):
print("STS HTTP status: " + str(rest.ResponseStatusCode))
success = xml.LoadXml(responseXml)
if (success == True):
value = xml.GetChildContent("Error|Code")
if (xml.LastMethodSuccess == True):
print("AWS error code: " + value)
value = xml.GetChildContent("RequestId")
if (xml.LastMethodSuccess == True):
print("AWS request ID: " + value)
sys.exit()
success = xml.LoadXml(responseXml)
if (success != True):
print("Invalid STS XML response.")
sys.exit()
stringCompare.SetString(xml.Tag)
stringMatch11 = stringCompare.ContentsEqual("GetWebIdentityTokenResponse",True)
if (stringMatch11 != True):
print("Unexpected STS response root.")
sys.exit()
value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
stringMatch12 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch12 == True)):
print("Missing or empty ResponseMetadata|RequestId.")
sys.exit()
if (xml.HasChildWithTag("GetWebIdentityTokenResult") != True):
print("Missing STS result.")
sys.exit()
sessionToken = xml.GetChildContent("GetWebIdentityTokenResult|WebIdentityToken")
stringCompare.SetString(sessionToken)
stringMatch13 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch13 == True)):
print("Missing or empty GetWebIdentityTokenResult|WebIdentityToken.")
sys.exit()
expiration = xml.GetChildContent("GetWebIdentityTokenResult|Expiration")
stringCompare.SetString(expiration)
stringMatch14 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch14 == True)):
print("Missing or empty GetWebIdentityTokenResult|Expiration.")
sys.exit()
success = expires.SetFromTimestamp(expiration)
if (success != True):
print("JWT expiration is invalid.")
sys.exit()
success = now.SetFromCurrentSystemTime()
if (success != True):
print("Could not read current time.")
sys.exit()
if (expires.DiffSeconds(now) <= 60):
print("JWT credentials are expired or expire within 60 seconds; obtain fresh credentials.")
sys.exit()
# Hand sessionToken to the intended external service over TLS; never log it.
print("Web identity token obtained; expiration: " + expiration)
print("Example completed.")