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 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("role_arn"))
stringMatch5 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("role_arn") != 1) or (stringMatch5 == True)):
print("Missing or invalid role_arn.")
sys.exit()
stringCompare.SetString(credentials.StringOf("role_session_name"))
stringMatch6 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("role_session_name") != 1) or (stringMatch6 == True)):
print("Missing or invalid role_session_name.")
sys.exit()
identifier = chilkat2.StringBuilder()
identifier.Append(credentials.StringOf("role_session_name"))
if ((identifier.Length < 2) or (identifier.Length > 64)):
print("role_session_name must have 2-64 characters.")
sys.exit()
allowed = chilkat2.StringBuilder()
allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
charIndex = 0
while (charIndex < identifier.Length) :
if (allowed.Contains(identifier.GetRange(charIndex,1,False),True) != True):
print("Invalid character in role_session_name.")
sys.exit()
charIndex = charIndex + 1
if ((credentials.HasMember("mfa_code") == True) or (credentials.HasMember("mfa_serial") == True)):
print("This unattended refresh example does not reuse MFA codes.")
sys.exit()
# Optional private cache contains only the four normalized session fields.
# In an application, keep activeSnapshot in memory between units of work.
files = chilkat2.FileAccess()
cached = chilkat2.JsonObject()
cached.Strict = True
activeSnapshot = ""
refreshRequired = True
if (files.FileExists("qa_data/tokens/sts_session.json") == True):
success = cached.LoadFile("qa_data/tokens/sts_session.json")
if (success != True):
print("Invalid private cache.")
sys.exit()
stringCompare.SetString(cached.StringOf("access_key"))
stringMatch7 = stringCompare.ContentsEqual("",True)
if ((cached.JsonTypeOf("access_key") != 1) or (stringMatch7 == True)):
print("Incomplete private cache.")
sys.exit()
stringCompare.SetString(cached.StringOf("secret_key"))
stringMatch8 = stringCompare.ContentsEqual("",True)
if ((cached.JsonTypeOf("secret_key") != 1) or (stringMatch8 == True)):
print("Incomplete private cache.")
sys.exit()
stringCompare.SetString(cached.StringOf("session_token"))
stringMatch9 = stringCompare.ContentsEqual("",True)
if ((cached.JsonTypeOf("session_token") != 1) or (stringMatch9 == True)):
print("Incomplete private cache.")
sys.exit()
stringCompare.SetString(cached.StringOf("expiration"))
stringMatch10 = stringCompare.ContentsEqual("",True)
if ((cached.JsonTypeOf("expiration") != 1) or (stringMatch10 == True)):
print("Incomplete private cache.")
sys.exit()
success = expires.SetFromTimestamp(cached.StringOf("expiration"))
if (success != True):
print("Invalid cached expiration.")
sys.exit()
success = now.SetFromCurrentSystemTime()
if (success != True):
print("Could not read current time.")
sys.exit()
if (expires.DiffSeconds(now) > 300):
activeSnapshot = cached.Emit()
refreshRequired = False
if (refreshRequired == True):
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 = ""
attempt = 0
delayMs = 1000
received = False
while ((attempt < 3) and (received == False)) :
if (credentials.HasMember("session_token") == True):
stringCompare.SetString(credentials.StringOf("session_token"))
stringMatch11 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch11 == True)):
print("Missing or invalid session_token.")
sys.exit()
stringCompare.SetString(credentials.StringOf("expiration"))
stringMatch12 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("expiration") != 1) or (stringMatch12 == 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()
attempt = attempt + 1
success = rest.ClearAllQueryParams()
if (success != True):
print("Could not reset request parameters.")
sys.exit()
success = rest.AddQueryParam("Action","AssumeRole")
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("RoleArn",credentials.StringOf("role_arn"))
if (success != True):
print("Could not set RoleArn.")
sys.exit()
success = rest.AddQueryParam("RoleSessionName",credentials.StringOf("role_session_name"))
if (success != True):
print("Could not set RoleSessionName.")
sys.exit()
success = rest.AddQueryParam("DurationSeconds","3600")
if (success != True):
print("Could not set DurationSeconds.")
sys.exit()
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
if (rest.LastMethodSuccess != True):
print("Transport failed; credential refresh was not published.")
sys.exit()
if (rest.ResponseStatusCode == 200):
received = True
if (rest.ResponseStatusCode != 200):
retryable = False
value = ""
success = xml.LoadXml(responseXml)
if (success == True):
value = xml.GetChildContent("Error|Code")
stringCompare.SetString(value)
stringMatch13 = stringCompare.ContentsEqual("Throttling",True)
stringCompare.SetString(value)
stringMatch14 = stringCompare.ContentsEqual("ThrottlingException",True)
if ((rest.ResponseStatusCode == 429) or (rest.ResponseStatusCode == 500) or (rest.ResponseStatusCode == 502) or (rest.ResponseStatusCode == 503) or (rest.ResponseStatusCode == 504) or (stringMatch13 == True) or (stringMatch14 == True)):
retryable = True
if ((retryable != True) or (attempt == 3)):
print("Refresh failed. HTTP status: " + str(rest.ResponseStatusCode))
print("AWS error code: " + value)
sys.exit()
connection.SleepMs(delayMs)
delayMs = delayMs * 2
if (received != True):
print("Refresh attempts exhausted.")
sys.exit()
success = xml.LoadXml(responseXml)
if (success != True):
print("Invalid STS XML response.")
sys.exit()
stringCompare.SetString(xml.Tag)
stringMatch15 = stringCompare.ContentsEqual("AssumeRoleResponse",True)
if (stringMatch15 != True):
print("Unexpected STS response root.")
sys.exit()
value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
stringMatch16 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch16 == True)):
print("Missing or empty ResponseMetadata|RequestId.")
sys.exit()
if (xml.HasChildWithTag("AssumeRoleResult") != True):
print("Missing STS result.")
sys.exit()
accessKey = xml.GetChildContent("AssumeRoleResult|Credentials|AccessKeyId")
stringCompare.SetString(accessKey)
stringMatch17 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch17 == True)):
print("Missing or empty AssumeRoleResult|Credentials|AccessKeyId.")
sys.exit()
secretKey = xml.GetChildContent("AssumeRoleResult|Credentials|SecretAccessKey")
stringCompare.SetString(secretKey)
stringMatch18 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch18 == True)):
print("Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.")
sys.exit()
sessionToken = xml.GetChildContent("AssumeRoleResult|Credentials|SessionToken")
stringCompare.SetString(sessionToken)
stringMatch19 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch19 == True)):
print("Missing or empty AssumeRoleResult|Credentials|SessionToken.")
sys.exit()
expiration = xml.GetChildContent("AssumeRoleResult|Credentials|Expiration")
stringCompare.SetString(expiration)
stringMatch20 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch20 == True)):
print("Missing or empty AssumeRoleResult|Credentials|Expiration.")
sys.exit()
success = expires.SetFromTimestamp(expiration)
if (success != True):
print("Returned 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("Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.")
sys.exit()
value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|Arn")
stringCompare.SetString(value)
stringMatch21 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch21 == True)):
print("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.")
sys.exit()
value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
stringCompare.SetString(value)
stringMatch22 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch22 == True)):
print("Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.")
sys.exit()
session = chilkat2.JsonObject()
success = session.UpdateString("access_key",accessKey)
if (success != True):
print("Could not build complete session.")
sys.exit()
success = session.UpdateString("secret_key",secretKey)
if (success != True):
print("Could not build complete session.")
sys.exit()
success = session.UpdateString("session_token",sessionToken)
if (success != True):
print("Could not build complete session.")
sys.exit()
success = session.UpdateString("expiration",expiration)
if (success != True):
print("Could not build complete session.")
sys.exit()
# 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()
# Rehydrate a complete set for the next unit of work, never four partial updates.
usable = chilkat2.JsonObject()
usable.Strict = True
success = usable.Load(activeSnapshot)
if (success != True):
print("Could not load the complete session snapshot.")
sys.exit()
# Pass usable to your service client here. Do not log activeSnapshot.
print("Session ready for the next unit of work; expiration: " + usable.StringOf("expiration"))
print("Example completed.")