Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.6.0+

AWS STS: Download an S3 Object with STS Credentials and Chilkat.Http

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.

Reads private STS XML as in the normalization example, plus qa_data/aws/sts_download.json with bucket and object_key strings. Uses all three temporary credential components with Chilkat.Http.S3_DownloadBd. Supply the raw object key, not a pre-encoded URL. Choose a small object that fits in memory, a general purpose bucket in us-west-2, and a session authorized for s3:GetObject on that object; the earlier bucket-list-only session policy is insufficient. KMS-encrypted objects may also need kms:Decrypt. The request is read-only and writes no file. Redirects are disabled so a region mismatch fails explicitly.

S3 GetObject

AWS references: AssumeRole

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
'  Load a privately stored STS XML response; never print its contents.
Dim tokenXml As ChilkatXml
tokenXml.Initialize
tokenXml.Strict = True
success = tokenXml.LoadXmlFile("qa_data/tokens/aws_session_token.xml")
If success <> True Then
    Log("Could not load private STS XML.")
    Return
End If

Dim credentialPath As String = ""
stringCompare.SetString(tokenXml.Tag)
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("GetSessionTokenResponse", True)
If stringMatch1 = True Then
    credentialPath = "GetSessionTokenResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("AssumeRoleResponse", True)
If stringMatch2 = True Then
    credentialPath = "AssumeRoleResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("AssumeRoleWithWebIdentityResponse", True)
If stringMatch3 = True Then
    credentialPath = "AssumeRoleWithWebIdentityResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("AssumeRoleWithSAMLResponse", True)
If stringMatch4 = True Then
    credentialPath = "AssumeRoleWithSAMLResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("GetFederationTokenResponse", True)
If stringMatch5 = True Then
    credentialPath = "GetFederationTokenResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("GetDelegatedAccessTokenResponse", True)
If stringMatch6 = True Then
    credentialPath = "GetDelegatedAccessTokenResult|Credentials"
End If

stringCompare.SetString(tokenXml.Tag)
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("AssumeRootResponse", True)
If stringMatch7 = True Then
    credentialPath = "AssumeRootResult|Credentials"
End If

stringCompare.SetString(credentialPath)
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch8 = True Then
    Log("Unsupported STS credential response.")
    Return
End If

Dim accessKey As String
Dim secretKey As String
Dim sessionToken As String
Dim expiration As String
Dim path As ChilkatStringBuilder
path.Initialize
success = path.SetString(credentialPath)
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

success = path.Append("|AccessKeyId")
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

accessKey = tokenXml.GetChildContent(path.GetAsString)
stringCompare.SetString(accessKey)
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("", True)
If (tokenXml.LastMethodSuccess <> True) Or (stringMatch9 = True) Then
    Log("Missing credential field AccessKeyId.")
    Return
End If

success = path.SetString(credentialPath)
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

success = path.Append("|SecretAccessKey")
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

secretKey = tokenXml.GetChildContent(path.GetAsString)
stringCompare.SetString(secretKey)
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("", True)
If (tokenXml.LastMethodSuccess <> True) Or (stringMatch10 = True) Then
    Log("Missing credential field SecretAccessKey.")
    Return
End If

success = path.SetString(credentialPath)
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

success = path.Append("|SessionToken")
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

sessionToken = tokenXml.GetChildContent(path.GetAsString)
stringCompare.SetString(sessionToken)
Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("", True)
If (tokenXml.LastMethodSuccess <> True) Or (stringMatch11 = True) Then
    Log("Missing credential field SessionToken.")
    Return
End If

success = path.SetString(credentialPath)
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

success = path.Append("|Expiration")
If success <> True Then
    Log("Could not construct credential path.")
    Return
End If

expiration = tokenXml.GetChildContent(path.GetAsString)
stringCompare.SetString(expiration)
Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("", True)
If (tokenXml.LastMethodSuccess <> True) Or (stringMatch12 = True) Then
    Log("Missing credential field Expiration.")
    Return
End If

Dim expires As ChilkatDateTime
expires.Initialize
Dim now As ChilkatDateTime
now.Initialize
success = expires.SetFromTimestamp(expiration)
If success <> True Then
    Log("Stored expiration is invalid.")
    Return
End If

success = now.SetFromCurrentSystemTime
If success <> True Then
    Log("Could not read current time.")
    Return
End If

If expires.DiffSeconds(now) <= 60 Then
    Log("Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.")
    Return
End If

Dim session As ChilkatJsonObject
session.Initialize
success = session.UpdateString("access_key", accessKey)
If success <> True Then
    Log("Could not build normalized session.")
    Return
End If

success = session.UpdateString("secret_key", secretKey)
If success <> True Then
    Log("Could not build normalized session.")
    Return
End If

success = session.UpdateString("session_token", sessionToken)
If success <> True Then
    Log("Could not build normalized session.")
    Return
End If

success = session.UpdateString("expiration", expiration)
If success <> True Then
    Log("Could not build normalized session.")
    Return
End If

Dim download As ChilkatJsonObject
download.Initialize
download.Strict = True
success = download.LoadFile("qa_data/aws/sts_download.json")
If success <> True Then
    Log("Could not load download configuration.")
    Return
End If

stringCompare.SetString(download.StringOf("bucket"))
Dim stringMatch13 As Boolean = stringCompare.ContentsEqual("", True)
If (download.JsonTypeOf("bucket") <> 1) Or (stringMatch13 = True) Then
    Log("Missing bucket.")
    Return
End If

stringCompare.SetString(download.StringOf("object_key"))
Dim stringMatch14 As Boolean = stringCompare.ContentsEqual("", True)
If (download.JsonTypeOf("object_key") <> 1) Or (stringMatch14 = True) Then
    Log("Missing object_key.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 60
http.VerboseLogging = False
http.AwsAccessKey = session.StringOf("access_key")
http.AwsSecretKey = session.StringOf("secret_key")
http.AwsSessionToken = session.StringOf("session_token")
http.AwsRegion = "us-west-2"
http.AwsEndpoint = "s3.us-west-2.amazonaws.com"
'  Current Chilkat S3 methods use Signature Version 4.
Dim objectData As ChilkatBinData
objectData.Initialize
success = http.S3_DownloadBd(download.StringOf("bucket"), download.StringOf("object_key"), objectData)
If success <> True Then
    Log("S3 download failed. HTTP status: " & http.LastStatus)
    Return
End If

If http.LastStatus <> 200 Then
    Log("Unexpected S3 status; do not use the data.")
    Return
End If

Log("Downloaded bytes: " & objectData.NumBytes)
'  Consume objectData in memory; no object contents or credentials are logged.
Log("Example completed.")