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 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()
expires = chilkat2.CkDateTime()
now = chilkat2.CkDateTime()
region = "us-west-2"
stringCompare.SetString(credentials.StringOf("role_arn"))
stringMatch1 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("role_arn") != 1) or (stringMatch1 == True)):
print("Missing or invalid role_arn.")
sys.exit()
stringCompare.SetString(credentials.StringOf("role_session_name"))
stringMatch2 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("role_session_name") != 1) or (stringMatch2 == 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
stringCompare.SetString(credentials.StringOf("web_identity_token"))
stringMatch3 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("web_identity_token") != 1) or (stringMatch3 == True)):
print("Missing or invalid web_identity_token.")
sys.exit()
endpoint = chilkat2.StringBuilder()
endpoint.Append("sts.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
rest = chilkat2.Rest()
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
# 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","AssumeRoleWithWebIdentity")
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()
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()
success = rest.AddQueryParam("WebIdentityToken",credentials.StringOf("web_identity_token"))
if (success != True):
print("Could not set WebIdentityToken.")
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)
stringMatch4 = stringCompare.ContentsEqual("AssumeRoleWithWebIdentityResponse",True)
if (stringMatch4 != True):
print("Unexpected STS response root.")
sys.exit()
value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
stringMatch5 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch5 == True)):
print("Missing or empty ResponseMetadata|RequestId.")
sys.exit()
if (xml.HasChildWithTag("AssumeRoleWithWebIdentityResult") != True):
print("Missing STS result.")
sys.exit()
accessKey = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId")
stringCompare.SetString(accessKey)
stringMatch6 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch6 == True)):
print("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId.")
sys.exit()
secretKey = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey")
stringCompare.SetString(secretKey)
stringMatch7 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch7 == True)):
print("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey.")
sys.exit()
sessionToken = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|SessionToken")
stringCompare.SetString(sessionToken)
stringMatch8 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch8 == True)):
print("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SessionToken.")
sys.exit()
expiration = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|Expiration")
stringCompare.SetString(expiration)
stringMatch9 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch9 == True)):
print("Missing or empty AssumeRoleWithWebIdentityResult|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("AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn")
stringCompare.SetString(value)
stringMatch10 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch10 == True)):
print("Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn.")
sys.exit()
value = xml.GetChildContent("AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId")
stringCompare.SetString(value)
stringMatch11 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch11 == True)):
print("Missing or empty AssumeRoleWithWebIdentityResult|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)
print("Example completed.")