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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
final stringCompare = CkStringBuilder();
// Load a privately stored STS XML response; never print its contents.
final tokenXml = CkXml();
tokenXml.strict = true;
try {
tokenXml.loadXmlFile('qa_data/tokens/aws_session_token.xml');
} on ChilkatException {
print('Could not load private STS XML.');
return;
}
var credentialPath = '';
stringCompare.setString(tokenXml.tag);
final stringMatch1 = stringCompare.contentsEqual('GetSessionTokenResponse', true);
if (stringMatch1) {
credentialPath = 'GetSessionTokenResult|Credentials';
}
stringCompare.setString(tokenXml.tag);
final stringMatch2 = stringCompare.contentsEqual('AssumeRoleResponse', true);
if (stringMatch2) {
credentialPath = 'AssumeRoleResult|Credentials';
}
stringCompare.setString(tokenXml.tag);
final stringMatch3 = stringCompare.contentsEqual('AssumeRoleWithWebIdentityResponse', true);
if (stringMatch3) {
credentialPath = 'AssumeRoleWithWebIdentityResult|Credentials';
}
stringCompare.setString(tokenXml.tag);
final stringMatch4 = stringCompare.contentsEqual('AssumeRoleWithSAMLResponse', true);
if (stringMatch4) {
credentialPath = 'AssumeRoleWithSAMLResult|Credentials';
}
stringCompare.setString(tokenXml.tag);
final stringMatch5 = stringCompare.contentsEqual('GetFederationTokenResponse', true);
if (stringMatch5) {
credentialPath = 'GetFederationTokenResult|Credentials';
}
stringCompare.setString(tokenXml.tag);
final stringMatch6 = stringCompare.contentsEqual('GetDelegatedAccessTokenResponse', true);
if (stringMatch6) {
credentialPath = 'GetDelegatedAccessTokenResult|Credentials';
}
stringCompare.setString(tokenXml.tag);
final stringMatch7 = stringCompare.contentsEqual('AssumeRootResponse', true);
if (stringMatch7) {
credentialPath = 'AssumeRootResult|Credentials';
}
stringCompare.setString(credentialPath);
final stringMatch8 = stringCompare.contentsEqual('', true);
if (stringMatch8) {
print('Unsupported STS credential response.');
return;
}
final path = CkStringBuilder();
try {
path.setString(credentialPath);
} on ChilkatException {
print('Could not construct credential path.');
return;
}
try {
path.append('|AccessKeyId');
} on ChilkatException {
print('Could not construct credential path.');
return;
}
final accessKey = tokenXml.getChildContent(path.getAsString());
stringCompare.setString(accessKey);
final stringMatch9 = stringCompare.contentsEqual('', true);
if ((!tokenXml.lastMethodSuccess) || (stringMatch9)) {
print('Missing credential field AccessKeyId.');
return;
}
try {
path.setString(credentialPath);
} on ChilkatException {
print('Could not construct credential path.');
return;
}
try {
path.append('|SecretAccessKey');
} on ChilkatException {
print('Could not construct credential path.');
return;
}
final secretKey = tokenXml.getChildContent(path.getAsString());
stringCompare.setString(secretKey);
final stringMatch10 = stringCompare.contentsEqual('', true);
if ((!tokenXml.lastMethodSuccess) || (stringMatch10)) {
print('Missing credential field SecretAccessKey.');
return;
}
try {
path.setString(credentialPath);
} on ChilkatException {
print('Could not construct credential path.');
return;
}
try {
path.append('|SessionToken');
} on ChilkatException {
print('Could not construct credential path.');
return;
}
final sessionToken = tokenXml.getChildContent(path.getAsString());
stringCompare.setString(sessionToken);
final stringMatch11 = stringCompare.contentsEqual('', true);
if ((!tokenXml.lastMethodSuccess) || (stringMatch11)) {
print('Missing credential field SessionToken.');
return;
}
try {
path.setString(credentialPath);
} on ChilkatException {
print('Could not construct credential path.');
return;
}
try {
path.append('|Expiration');
} on ChilkatException {
print('Could not construct credential path.');
return;
}
final expiration = tokenXml.getChildContent(path.getAsString());
stringCompare.setString(expiration);
final stringMatch12 = stringCompare.contentsEqual('', true);
if ((!tokenXml.lastMethodSuccess) || (stringMatch12)) {
print('Missing credential field Expiration.');
return;
}
final expires = CkDateTime();
final now = CkDateTime();
try {
expires.setFromTimestamp(expiration);
} on ChilkatException {
print('Stored expiration is invalid.');
return;
}
try {
now.setFromCurrentSystemTime();
} on ChilkatException {
print('Could not read current time.');
return;
}
if (expires.diffSeconds(now) <= 60) {
print('Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.');
return;
}
final session = CkJsonObject();
try {
session.updateString('access_key', accessKey);
} on ChilkatException {
print('Could not build normalized session.');
return;
}
try {
session.updateString('secret_key', secretKey);
} on ChilkatException {
print('Could not build normalized session.');
return;
}
try {
session.updateString('session_token', sessionToken);
} on ChilkatException {
print('Could not build normalized session.');
return;
}
try {
session.updateString('expiration', expiration);
} on ChilkatException {
print('Could not build normalized session.');
return;
}
final download = CkJsonObject();
download.strict = true;
try {
download.loadFile('qa_data/aws/sts_download.json');
} on ChilkatException {
print('Could not load download configuration.');
return;
}
stringCompare.setString(download.stringOf('bucket'));
final stringMatch13 = stringCompare.contentsEqual('', true);
if ((download.jsonTypeOf('bucket') != 1) || (stringMatch13)) {
print('Missing bucket.');
return;
}
stringCompare.setString(download.stringOf('object_key'));
final stringMatch14 = stringCompare.contentsEqual('', true);
if ((download.jsonTypeOf('object_key') != 1) || (stringMatch14)) {
print('Missing object_key.');
return;
}
final http = CkHttp();
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.
final objectData = CkBinData();
try {
http.s3DownloadBd(download.stringOf('bucket'), download.stringOf('object_key'), objectData);
} on ChilkatException {
print('S3 download failed. HTTP status: ${http.lastStatus}');
return;
}
if (http.lastStatus != 200) {
print('Unexpected S3 status; do not use the data.');
return;
}
print('Downloaded bytes: ${objectData.numBytes}');
// Consume objectData in memory; no object contents or credentials are logged.
print('Example completed.');
}