AWS STS: Decode an Authorization Failure
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 encoded_message to the complete encoded message from a supported AWS failure. Requires sts:DecodeAuthorizationMessage. Parses the JSON contained inside the XML response and displays only its boolean decision flags. Not every access-denied response has an encoded message; do not pass an ordinary error message.
AWS references: DecodeAuthorizationMessage
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("encoded_message"))
stringMatch5 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("encoded_message") != 1) or (stringMatch5 == True)):
print("Missing or invalid encoded_message.")
sys.exit()
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","DecodeAuthorizationMessage")
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("EncodedMessage",credentials.StringOf("encoded_message"))
if (success != True):
print("Could not set EncodedMessage.")
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)
stringMatch6 = stringCompare.ContentsEqual("DecodeAuthorizationMessageResponse",True)
if (stringMatch6 != True):
print("Unexpected STS response root.")
sys.exit()
if (xml.HasChildWithTag("DecodeAuthorizationMessageResult") == True):
value = xml.GetChildContent("ResponseMetadata|RequestId")
stringCompare.SetString(value)
stringMatch7 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch7 == True)):
print("Missing or empty ResponseMetadata|RequestId.")
sys.exit()
else:
value = xml.GetChildContent("requestId")
stringCompare.SetString(value)
stringMatch8 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch8 == True)):
print("Missing or empty requestId.")
sys.exit()
decodedPath = "DecodeAuthorizationMessageResult|DecodedMessage"
# Also accept the top-level form shown in the AWS reference's example response.
if (xml.HasChildWithTag("DecodeAuthorizationMessageResult") != True):
decodedPath = "DecodedMessage"
value = xml.GetChildContent(decodedPath)
stringCompare.SetString(value)
stringMatch9 = stringCompare.ContentsEqual("",True)
if ((xml.LastMethodSuccess != True) or (stringMatch9 == True)):
print("Missing decoded authorization details.")
sys.exit()
decoded = chilkat2.JsonObject()
decoded.Strict = True
success = decoded.Load(value)
if (success != True):
print("Decoded authorization details are not valid JSON.")
sys.exit()
allowed = False
if ((decoded.JsonTypeOf("allowed") != 5) and (decoded.JsonTypeOf("allowed") != 1)):
print("Invalid authorization flag type.")
sys.exit()
if (decoded.JsonTypeOf("allowed") == 5):
allowed = decoded.BoolOf("allowed")
if (decoded.JsonTypeOf("allowed") == 1):
value = decoded.StringOf("allowed")
stringCompare.SetString(value)
stringMatch10 = stringCompare.ContentsEqual("true",True)
stringCompare.SetString(value)
stringMatch11 = stringCompare.ContentsEqual("false",True)
if ((stringMatch10 != True) and (stringMatch11 != True)):
print("Invalid string authorization flag.")
sys.exit()
stringCompare.SetString(value)
stringMatch12 = stringCompare.ContentsEqual("true",True)
if (stringMatch12 == True):
allowed = True
print("allowed: " + str(allowed))
explicitDeny = False
if ((decoded.JsonTypeOf("explicitDeny") != 5) and (decoded.JsonTypeOf("explicitDeny") != 1)):
print("Invalid authorization flag type.")
sys.exit()
if (decoded.JsonTypeOf("explicitDeny") == 5):
explicitDeny = decoded.BoolOf("explicitDeny")
if (decoded.JsonTypeOf("explicitDeny") == 1):
value = decoded.StringOf("explicitDeny")
stringCompare.SetString(value)
stringMatch13 = stringCompare.ContentsEqual("true",True)
stringCompare.SetString(value)
stringMatch14 = stringCompare.ContentsEqual("false",True)
if ((stringMatch13 != True) and (stringMatch14 != True)):
print("Invalid string authorization flag.")
sys.exit()
stringCompare.SetString(value)
stringMatch15 = stringCompare.ContentsEqual("true",True)
if (stringMatch15 == True):
explicitDeny = True
print("explicitDeny: " + str(explicitDeny))
# Inspect other decoded fields privately; they can contain privileged details.
print("Example completed.")