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.
AWS references: AssumeRole
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;
public class ChilkatExample {
public static void main(String[] args) {
StringBuilder stringCompare = new StringBuilder();
// Load a privately stored STS XML response; never print its contents.
Xml tokenXml = new Xml();
tokenXml.setStrict(true);
try {
tokenXml.loadXmlFile("qa_data/tokens/aws_session_token.xml");
} catch (ChilkatException e) {
System.out.println("Could not load private STS XML.");
return;
}
String credentialPath = "";
stringCompare.setString(tokenXml.getTag());
boolean stringMatch1 = stringCompare.contentsEqual("GetSessionTokenResponse", true);
if (stringMatch1) {
credentialPath = "GetSessionTokenResult|Credentials";
}
stringCompare.setString(tokenXml.getTag());
boolean stringMatch2 = stringCompare.contentsEqual("AssumeRoleResponse", true);
if (stringMatch2) {
credentialPath = "AssumeRoleResult|Credentials";
}
stringCompare.setString(tokenXml.getTag());
boolean stringMatch3 = stringCompare.contentsEqual("AssumeRoleWithWebIdentityResponse", true);
if (stringMatch3) {
credentialPath = "AssumeRoleWithWebIdentityResult|Credentials";
}
stringCompare.setString(tokenXml.getTag());
boolean stringMatch4 = stringCompare.contentsEqual("AssumeRoleWithSAMLResponse", true);
if (stringMatch4) {
credentialPath = "AssumeRoleWithSAMLResult|Credentials";
}
stringCompare.setString(tokenXml.getTag());
boolean stringMatch5 = stringCompare.contentsEqual("GetFederationTokenResponse", true);
if (stringMatch5) {
credentialPath = "GetFederationTokenResult|Credentials";
}
stringCompare.setString(tokenXml.getTag());
boolean stringMatch6 = stringCompare.contentsEqual("GetDelegatedAccessTokenResponse", true);
if (stringMatch6) {
credentialPath = "GetDelegatedAccessTokenResult|Credentials";
}
stringCompare.setString(tokenXml.getTag());
boolean stringMatch7 = stringCompare.contentsEqual("AssumeRootResponse", true);
if (stringMatch7) {
credentialPath = "AssumeRootResult|Credentials";
}
stringCompare.setString(credentialPath);
boolean stringMatch8 = stringCompare.contentsEqual("", true);
if (stringMatch8) {
System.out.println("Unsupported STS credential response.");
return;
}
StringBuilder path = new StringBuilder();
try {
path.setString(credentialPath);
path.append("|AccessKeyId");
} catch (ChilkatException e) {
System.out.println("Could not construct credential path.");
return;
}
String accessKey = tokenXml.getChildContent(path.getAsString());
stringCompare.setString(accessKey);
boolean stringMatch9 = stringCompare.contentsEqual("", true);
if ((!tokenXml.getLastMethodSuccess()) || (stringMatch9)) {
System.out.println("Missing credential field AccessKeyId.");
return;
}
try {
path.setString(credentialPath);
path.append("|SecretAccessKey");
} catch (ChilkatException e) {
System.out.println("Could not construct credential path.");
return;
}
String secretKey = tokenXml.getChildContent(path.getAsString());
stringCompare.setString(secretKey);
boolean stringMatch10 = stringCompare.contentsEqual("", true);
if ((!tokenXml.getLastMethodSuccess()) || (stringMatch10)) {
System.out.println("Missing credential field SecretAccessKey.");
return;
}
try {
path.setString(credentialPath);
path.append("|SessionToken");
} catch (ChilkatException e) {
System.out.println("Could not construct credential path.");
return;
}
String sessionToken = tokenXml.getChildContent(path.getAsString());
stringCompare.setString(sessionToken);
boolean stringMatch11 = stringCompare.contentsEqual("", true);
if ((!tokenXml.getLastMethodSuccess()) || (stringMatch11)) {
System.out.println("Missing credential field SessionToken.");
return;
}
try {
path.setString(credentialPath);
path.append("|Expiration");
} catch (ChilkatException e) {
System.out.println("Could not construct credential path.");
return;
}
String expiration = tokenXml.getChildContent(path.getAsString());
stringCompare.setString(expiration);
boolean stringMatch12 = stringCompare.contentsEqual("", true);
if ((!tokenXml.getLastMethodSuccess()) || (stringMatch12)) {
System.out.println("Missing credential field Expiration.");
return;
}
DateTime expires = new DateTime();
DateTime now = new DateTime();
try {
expires.setFromTimestamp(expiration);
} catch (ChilkatException e) {
System.out.println("Stored expiration is invalid.");
return;
}
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read current time.");
return;
}
if (expires.diffSeconds(now) <= 60) {
System.out.println("Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.");
return;
}
JsonObject session = new JsonObject();
try {
session.updateString("access_key", accessKey);
session.updateString("secret_key", secretKey);
session.updateString("session_token", sessionToken);
session.updateString("expiration", expiration);
} catch (ChilkatException e) {
System.out.println("Could not build normalized session.");
return;
}
JsonObject download = new JsonObject();
download.setStrict(true);
try {
download.loadFile("qa_data/aws/sts_download.json");
} catch (ChilkatException e) {
System.out.println("Could not load download configuration.");
return;
}
stringCompare.setString(download.stringOf("bucket"));
boolean stringMatch13 = stringCompare.contentsEqual("", true);
if ((download.jsonTypeOf("bucket") != 1) || (stringMatch13)) {
System.out.println("Missing bucket.");
return;
}
stringCompare.setString(download.stringOf("object_key"));
boolean stringMatch14 = stringCompare.contentsEqual("", true);
if ((download.jsonTypeOf("object_key") != 1) || (stringMatch14)) {
System.out.println("Missing object_key.");
return;
}
Http http = new Http();
http.setRequireSslCertVerify(true);
http.setFollowRedirects(false);
http.setConnectTimeout(20);
http.setReadTimeout(60);
http.setVerboseLogging(false);
http.setAwsAccessKey(session.stringOf("access_key"));
http.setAwsSecretKey(session.stringOf("secret_key"));
http.setAwsSessionToken(session.stringOf("session_token"));
http.setAwsRegion("us-west-2");
http.setAwsEndpoint("s3.us-west-2.amazonaws.com");
// Current Chilkat S3 methods use Signature Version 4.
BinData objectData = new BinData();
try {
http.s3DownloadBd(download.stringOf("bucket"), download.stringOf("object_key"), objectData);
} catch (ChilkatException e) {
System.out.println("S3 download failed. HTTP status: " + http.getLastStatus());
return;
}
if (http.getLastStatus() != 200) {
System.out.println("Unexpected S3 status; do not use the data.");
return;
}
System.out.println("Downloaded bytes: " + objectData.getNumBytes());
// Consume objectData in memory; no object contents or credentials are logged.
System.out.println("Example completed.");
}
}