AWS STS: Assume a Role for S3 Bucket Listing
See more AWS Security Token Service Examples
Uses Chilkat.Rest and AuthAws with AWS Signature Version 4. STS uses the Query API version 2011-06-15; that version date is still current. The examples send URL-encoded POST forms rather than operation parameters in a GET URL. They use the commercial-partition regional endpoint sts.us-west-2.amazonaws.com and matching signing region/service sts, with explicit TLS certificate verification. Choose the appropriate region/partition endpoint for your deployment.
Load private qa_data/aws/sts.json with nonempty string fields access_key and secret_key. These examples do not discover credentials, assume roles implicitly, or refresh credentials automatically. No access key, secret key, token, full XML response or diagnostic dump is printed.
Both credential-producing examples retain the existing handoff file qa_data/tokens/aws_session_token.xml. It contains plaintext credentials: pre-create a private directory with restrictive OS permissions and keep it out of web roots, source control, shared logs and shared storage. The sample checks the write, but does not set ACLs, encrypt the file, perform atomic replacement, or coordinate concurrent writers. Prefer in-memory handoff or an appropriate credential store in production. A failed request can leave an older file in place; do not assume a failed run refreshed it. The consumer validates expiration, allowing a 60-second margin.
Set role_arn and role_session_name in the private configuration. Names must contain 2–64 allowed characters. The target trust policy and applicable caller authorization must permit AssumeRole. The sample's session policy permits only s3:ListAllMyBuckets, intersected with the role's permissions, for use by the companion S3 listing example; it cannot elevate the role's access. Other policy types, denies and resource-based rules still participate in authorization.
The fixed 3600-second request works within the one-hour role-chaining ceiling and must still fit the role's configured maximum. For temporary source credentials, also provide nonempty session_token and ISO 8601 expiration. The token is included in the signed form body. Optional external_id must be the value agreed with the role owner; it is not a password. Optional source_identity is subject to AWS syntax, trust conditions and sts:SetSourceIdentity permission. Optional MFA uses mfa_serial/mfa_code as a pair. These optional values must satisfy the actual trust policy.
This focused example omits managed session policies and session tags. When adding them, configure the required policies and tagging permissions, and account for inherited transitive tags during role chaining. STS session-token sizes are variable; preserve the complete value without a fixed buffer or truncation.
Chilkat Classic ASP Downloads
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
success = 0
set stringCompare = Server.CreateObject("Chilkat.StringBuilder")
' Assumes Chilkat is unlocked. See Global Unlock Sample.
' Keep this file private and outside public web content/source control.
set credentials = Server.CreateObject("Chilkat.JsonObject")
credentials.Strict = 1
success = credentials.LoadFile("qa_data/aws/sts.json")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not load private STS configuration.") & "</pre>"
Response.End
End If
success = stringCompare.SetString(credentials.StringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid access_key.") & "</pre>"
Response.End
End If
success = stringCompare.SetString(credentials.StringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid secret_key.") & "</pre>"
Response.End
End If
set expires = Server.CreateObject("Chilkat.CkDateTime")
set now = Server.CreateObject("Chilkat.CkDateTime")
region = "us-west-2"
If (credentials.HasMember("session_token") = 1) Then
success = stringCompare.SetString(credentials.StringOf("session_token"))
stringMatch3 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid session_token.") & "</pre>"
Response.End
End If
success = stringCompare.SetString(credentials.StringOf("expiration"))
stringMatch4 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("expiration") <> 1) Or (stringMatch4 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid expiration.") & "</pre>"
Response.End
End If
success = expires.SetFromTimestamp(credentials.StringOf("expiration"))
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Source expiration is invalid.") & "</pre>"
Response.End
End If
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not read current time.") & "</pre>"
Response.End
End If
If (expires.DiffSeconds(now) <= 60) Then
Response.Write "<pre>" & Server.HTMLEncode( "Source credentials are expired or expire within 60 seconds; obtain fresh credentials.") & "</pre>"
Response.End
End If
End If
success = stringCompare.SetString(credentials.StringOf("role_arn"))
stringMatch5 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("role_arn") <> 1) Or (stringMatch5 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid role_arn.") & "</pre>"
Response.End
End If
success = stringCompare.SetString(credentials.StringOf("role_session_name"))
stringMatch6 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("role_session_name") <> 1) Or (stringMatch6 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid role_session_name.") & "</pre>"
Response.End
End If
set identifier = Server.CreateObject("Chilkat.StringBuilder")
success = identifier.Append(credentials.StringOf("role_session_name"))
If ((identifier.Length < 2) Or (identifier.Length > 64)) Then
Response.Write "<pre>" & Server.HTMLEncode( "role_session_name must have 2-64 characters.") & "</pre>"
Response.End
End If
set allowed = Server.CreateObject("Chilkat.StringBuilder")
success = allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
charIndex = 0
Do While (charIndex < identifier.Length)
If (allowed.Contains(identifier.GetRange(charIndex,1,0),1) <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Invalid character in role_session_name.") & "</pre>"
Response.End
End If
charIndex = charIndex + 1
Loop
set roleArn = Server.CreateObject("Chilkat.StringBuilder")
success = roleArn.Append(credentials.StringOf("role_arn"))
If ((roleArn.StartsWith("arn:aws:iam::",1) <> 1) Or (roleArn.Contains(":role/",1) <> 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Use an IAM role ARN in the commercial AWS partition.") & "</pre>"
Response.End
End If
If (credentials.HasMember("external_id") = 1) Then
success = stringCompare.SetString(credentials.StringOf("external_id"))
stringMatch7 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("external_id") <> 1) Or (stringMatch7 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid external_id.") & "</pre>"
Response.End
End If
End If
If (credentials.HasMember("source_identity") = 1) Then
success = stringCompare.SetString(credentials.StringOf("source_identity"))
stringMatch8 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("source_identity") <> 1) Or (stringMatch8 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid source_identity.") & "</pre>"
Response.End
End If
End If
' MFA fields are optional as a pair. Preserve a leading zero in the code.
If ((credentials.HasMember("mfa_serial") = 1) Or (credentials.HasMember("mfa_code") = 1)) Then
success = stringCompare.SetString(credentials.StringOf("mfa_serial"))
stringMatch9 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("mfa_serial") <> 1) Or (stringMatch9 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid mfa_serial.") & "</pre>"
Response.End
End If
success = stringCompare.SetString(credentials.StringOf("mfa_code"))
stringMatch10 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("mfa_code") <> 1) Or (stringMatch10 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or invalid mfa_code.") & "</pre>"
Response.End
End If
set mfaCode = Server.CreateObject("Chilkat.StringBuilder")
success = mfaCode.Append(credentials.StringOf("mfa_code"))
If (mfaCode.Length <> 6) Then
Response.Write "<pre>" & Server.HTMLEncode( "mfa_code must be a six-digit string.") & "</pre>"
Response.End
End If
set digits = Server.CreateObject("Chilkat.StringBuilder")
success = digits.Append("0123456789")
digitIndex = 0
Do While (digitIndex < 6)
If (digits.Contains(mfaCode.GetRange(digitIndex,1,0),1) <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "mfa_code must contain only ASCII digits.") & "</pre>"
Response.End
End If
digitIndex = digitIndex + 1
Loop
End If
set endpoint = Server.CreateObject("Chilkat.StringBuilder")
success = endpoint.Append("sts.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
set aws = Server.CreateObject("Chilkat.AuthAws")
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "sts"
aws.SignatureVersion = 4
set rest = Server.CreateObject("Chilkat.Rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = 0
success = rest.SetAuthAws(aws)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not configure request signing.") & "</pre>"
Response.End
End If
' Keep this verified Socket alive while Rest uses its connection.
set connection = Server.CreateObject("Chilkat.Socket")
connection.RequireSslCertVerify = 1
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,1,20000)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "TLS connection failed; inspect diagnostics privately.") & "</pre>"
Response.End
End If
success = rest.UseConnection(connection,1)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not attach TLS connection.") & "</pre>"
Response.End
End If
set xml = Server.CreateObject("Chilkat.Xml")
xml.Strict = 1
success = rest.ClearAllQueryParams()
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not clear request parameters.") & "</pre>"
Response.End
End If
success = rest.AddQueryParam("Action","AssumeRole")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set Action.") & "</pre>"
Response.End
End If
success = rest.AddQueryParam("Version","2011-06-15")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set Version.") & "</pre>"
Response.End
End If
success = rest.AddQueryParam("DurationSeconds","3600")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set DurationSeconds.") & "</pre>"
Response.End
End If
If (credentials.HasMember("session_token") = 1) Then
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set X-Amz-Security-Token.") & "</pre>"
Response.End
End If
End If
success = rest.AddQueryParam("RoleArn",credentials.StringOf("role_arn"))
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set RoleArn.") & "</pre>"
Response.End
End If
success = rest.AddQueryParam("RoleSessionName",credentials.StringOf("role_session_name"))
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set RoleSessionName.") & "</pre>"
Response.End
End If
' A session policy only restricts the role; it cannot add permissions.
set policy = Server.CreateObject("Chilkat.JsonObject")
success = policy.UpdateString("Version","2012-10-17")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set policy version.") & "</pre>"
Response.End
End If
success = policy.UpdateString("Statement[0].Effect","Allow")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set policy effect.") & "</pre>"
Response.End
End If
success = policy.UpdateString("Statement[0].Action","s3:ListAllMyBuckets")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set policy action.") & "</pre>"
Response.End
End If
success = policy.UpdateString("Statement[0].Resource","*")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set policy resource.") & "</pre>"
Response.End
End If
success = rest.AddQueryParam("Policy",policy.Emit())
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set Policy.") & "</pre>"
Response.End
End If
If (credentials.HasMember("external_id") = 1) Then
success = rest.AddQueryParam("ExternalId",credentials.StringOf("external_id"))
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set ExternalId.") & "</pre>"
Response.End
End If
End If
If (credentials.HasMember("source_identity") = 1) Then
success = rest.AddQueryParam("SourceIdentity",credentials.StringOf("source_identity"))
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set SourceIdentity.") & "</pre>"
Response.End
End If
End If
If (credentials.HasMember("mfa_serial") = 1) Then
success = rest.AddQueryParam("SerialNumber",credentials.StringOf("mfa_serial"))
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set SerialNumber.") & "</pre>"
Response.End
End If
success = rest.AddQueryParam("TokenCode",credentials.StringOf("mfa_code"))
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not set TokenCode.") & "</pre>"
Response.End
End If
End If
responseXml = rest.FullRequestFormUrlEncoded("POST","/")
If (rest.LastMethodSuccess <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "STS request did not complete; no credentials were saved. Inspect diagnostics privately.") & "</pre>"
Response.End
End If
success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
Response.Write "<pre>" & Server.HTMLEncode( "STS HTTP status: " & rest.ResponseStatusCode) & "</pre>"
If (success = 1) Then
value = xml.GetChildContent("Error|Code")
If (xml.LastMethodSuccess = 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "AWS error code: " & value) & "</pre>"
End If
value = xml.GetChildContent("RequestId")
If (xml.LastMethodSuccess = 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "AWS request ID: " & value) & "</pre>"
End If
End If
' Full bodies, headers, and diagnostics can contain sensitive data.
Response.End
End If
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Invalid STS XML response; no credentials were saved.") & "</pre>"
Response.End
End If
success = stringCompare.SetString(xml.Tag)
stringMatch11 = stringCompare.ContentsEqual("AssumeRoleResponse",1)
If (stringMatch11 <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Unexpected STS response root.") & "</pre>"
Response.End
End If
value = xml.GetChildContent("ResponseMetadata|RequestId")
success = stringCompare.SetString(value)
stringMatch12 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch12 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or empty ResponseMetadata|RequestId.") & "</pre>"
Response.End
End If
Response.Write "<pre>" & Server.HTMLEncode( "AWS request ID: " & value) & "</pre>"
accessKey = xml.GetChildContent("AssumeRoleResult|Credentials|AccessKeyId")
success = stringCompare.SetString(accessKey)
stringMatch13 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch13 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or empty AssumeRoleResult|Credentials|AccessKeyId.") & "</pre>"
Response.End
End If
secretKey = xml.GetChildContent("AssumeRoleResult|Credentials|SecretAccessKey")
success = stringCompare.SetString(secretKey)
stringMatch14 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch14 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.") & "</pre>"
Response.End
End If
sessionToken = xml.GetChildContent("AssumeRoleResult|Credentials|SessionToken")
success = stringCompare.SetString(sessionToken)
stringMatch15 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch15 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or empty AssumeRoleResult|Credentials|SessionToken.") & "</pre>"
Response.End
End If
expiration = xml.GetChildContent("AssumeRoleResult|Credentials|Expiration")
success = stringCompare.SetString(expiration)
stringMatch16 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch16 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or empty AssumeRoleResult|Credentials|Expiration.") & "</pre>"
Response.End
End If
success = expires.SetFromTimestamp(expiration)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Returned expiration is invalid.") & "</pre>"
Response.End
End If
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not read current time.") & "</pre>"
Response.End
End If
If (expires.DiffSeconds(now) <= 60) Then
Response.Write "<pre>" & Server.HTMLEncode( "Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.") & "</pre>"
Response.End
End If
value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|Arn")
success = stringCompare.SetString(value)
stringMatch17 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch17 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.") & "</pre>"
Response.End
End If
value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
success = stringCompare.SetString(value)
stringMatch18 = stringCompare.ContentsEqual("",1)
If ((xml.LastMethodSuccess <> 1) Or (stringMatch18 = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.") & "</pre>"
Response.End
End If
' Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
' Reuses the existing handoff filename for the companion S3 example.
success = xml.SaveXml("qa_data/tokens/aws_session_token.xml")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not save the private credential file; do not assume it was updated.") & "</pre>"
Response.End
End If
Response.Write "<pre>" & Server.HTMLEncode( "Temporary credentials saved privately; expiration: " & expiration) & "</pre>"
%>
</body>
</html>