AWS STS: Normalize STS Credentials and Use Chilkat.Rest
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 only private qa_data/tokens/aws_session_token.xml; no sts.json is needed. Accepts all seven credential-producing STS response roots, including the existing GetSessionToken/AssumeRole handoff. Builds a complete normalized in-memory session and uses it to sign GetCallerIdentity. The normalized fields are access_key, secret_key, session_token and expiration. Checks expiration with a 60-second margin before connecting. JWT-only GetWebIdentityToken responses are intentionally not credential sets.
AWS references: GetCallerIdentity
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 region = 'us-west-2';
final endpoint = CkStringBuilder();
endpoint.append('sts.');
endpoint.append(region);
endpoint.append('.amazonaws.com');
final aws = CkAuthAws();
aws.accessKey = session.stringOf('access_key');
aws.secretKey = session.stringOf('secret_key');
aws.region = region;
aws.serviceName = 'sts';
aws.signatureVersion = 4;
final rest = CkRest();
rest.connectTimeoutMs = 20000;
rest.idleTimeoutMs = 60000;
rest.verboseLogging = false;
try {
rest.setAuthAws(aws);
} on ChilkatException {
print('Could not configure request signing.');
return;
}
// Keep this verified Socket alive while Rest uses its connection.
final connection = CkSocket();
connection.requireSslCertVerify = true;
connection.maxReadIdleMs = 60000;
connection.maxSendIdleMs = 60000;
try {
connection.connect(endpoint.getAsString(), 443, true, 20000);
} on ChilkatException {
print('TLS connection failed; inspect diagnostics privately.');
return;
}
try {
rest.useConnection(connection, true);
} on ChilkatException {
print('Could not attach TLS connection.');
return;
}
final xml = CkXml();
xml.strict = true;
var value = '';
var responseXml = '';
try {
rest.clearAllQueryParams();
} on ChilkatException {
print('Could not reset request parameters.');
return;
}
try {
rest.addQueryParam('Action', 'GetCallerIdentity');
} on ChilkatException {
print('Could not set Action.');
return;
}
try {
rest.addQueryParam('Version', '2011-06-15');
} on ChilkatException {
print('Could not set Version.');
return;
}
try {
rest.addQueryParam('X-Amz-Security-Token', session.stringOf('session_token'));
} on ChilkatException {
print('Could not set X-Amz-Security-Token.');
return;
}
try {
responseXml = rest.fullRequestFormUrlEncoded('POST', '/');
} on ChilkatException {
print('STS transport failed; inspect diagnostics privately.');
return;
}
if (rest.responseStatusCode != 200) {
print('STS HTTP status: ${rest.responseStatusCode}');
try {
xml.loadXml(responseXml);
try {
value = xml.getChildContent('Error|Code');
print('AWS error code: $value');
} on ChilkatException {
// xml.getChildContent() failed; continue anyway.
}
try {
value = xml.getChildContent('RequestId');
print('AWS request ID: $value');
} on ChilkatException {
// xml.getChildContent() failed; continue anyway.
}
} on ChilkatException {
// xml.loadXml() failed; continue anyway.
}
return;
}
try {
xml.loadXml(responseXml);
} on ChilkatException {
print('Invalid STS XML response.');
return;
}
stringCompare.setString(xml.tag);
final stringMatch13 = stringCompare.contentsEqual('GetCallerIdentityResponse', true);
if (!stringMatch13) {
print('Unexpected STS response root.');
return;
}
value = xml.getChildContent('ResponseMetadata|RequestId');
stringCompare.setString(value);
final stringMatch14 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch14)) {
print('Missing or empty ResponseMetadata|RequestId.');
return;
}
if (!xml.hasChildWithTag('GetCallerIdentityResult')) {
print('Missing STS result.');
return;
}
value = xml.getChildContent('GetCallerIdentityResult|Arn');
stringCompare.setString(value);
final stringMatch15 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch15)) {
print('Missing or empty GetCallerIdentityResult|Arn.');
return;
}
print('Authenticated principal: $value');
print('Example completed.');
}