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 Perl Downloads
use strict;
use warnings;
use Chilkat2;
my $stringCompare = Chilkat2::StringBuilder->new;
# Load a privately stored STS XML response; never print its contents.
my $tokenXml = Chilkat2::Xml->new;
$tokenXml->Strict(1);
my $success = $tokenXml->LoadXmlFile('qa_data/tokens/aws_session_token.xml');
if (!$success) {
print "Could not load private STS XML.\n";
exit;
}
my $credentialPath = '';
$stringCompare->SetString($tokenXml->Tag);
my $stringMatch1 = $stringCompare->ContentsEqual('GetSessionTokenResponse', 1);
if ($stringMatch1) {
$credentialPath = 'GetSessionTokenResult|Credentials';
}
$stringCompare->SetString($tokenXml->Tag);
my $stringMatch2 = $stringCompare->ContentsEqual('AssumeRoleResponse', 1);
if ($stringMatch2) {
$credentialPath = 'AssumeRoleResult|Credentials';
}
$stringCompare->SetString($tokenXml->Tag);
my $stringMatch3 = $stringCompare->ContentsEqual('AssumeRoleWithWebIdentityResponse', 1);
if ($stringMatch3) {
$credentialPath = 'AssumeRoleWithWebIdentityResult|Credentials';
}
$stringCompare->SetString($tokenXml->Tag);
my $stringMatch4 = $stringCompare->ContentsEqual('AssumeRoleWithSAMLResponse', 1);
if ($stringMatch4) {
$credentialPath = 'AssumeRoleWithSAMLResult|Credentials';
}
$stringCompare->SetString($tokenXml->Tag);
my $stringMatch5 = $stringCompare->ContentsEqual('GetFederationTokenResponse', 1);
if ($stringMatch5) {
$credentialPath = 'GetFederationTokenResult|Credentials';
}
$stringCompare->SetString($tokenXml->Tag);
my $stringMatch6 = $stringCompare->ContentsEqual('GetDelegatedAccessTokenResponse', 1);
if ($stringMatch6) {
$credentialPath = 'GetDelegatedAccessTokenResult|Credentials';
}
$stringCompare->SetString($tokenXml->Tag);
my $stringMatch7 = $stringCompare->ContentsEqual('AssumeRootResponse', 1);
if ($stringMatch7) {
$credentialPath = 'AssumeRootResult|Credentials';
}
$stringCompare->SetString($credentialPath);
my $stringMatch8 = $stringCompare->ContentsEqual('', 1);
if ($stringMatch8) {
print "Unsupported STS credential response.\n";
exit;
}
my $path = Chilkat2::StringBuilder->new;
$success = $path->SetString($credentialPath);
if (!$success) {
print "Could not construct credential path.\n";
exit;
}
$success = $path->Append('|AccessKeyId');
if (!$success) {
print "Could not construct credential path.\n";
exit;
}
my $accessKey = $tokenXml->GetChildContent($path->GetAsString());
$stringCompare->SetString($accessKey);
my $stringMatch9 = $stringCompare->ContentsEqual('', 1);
if ((!$tokenXml->LastMethodSuccess) || ($stringMatch9)) {
print "Missing credential field AccessKeyId.\n";
exit;
}
$success = $path->SetString($credentialPath);
if (!$success) {
print "Could not construct credential path.\n";
exit;
}
$success = $path->Append('|SecretAccessKey');
if (!$success) {
print "Could not construct credential path.\n";
exit;
}
my $secretKey = $tokenXml->GetChildContent($path->GetAsString());
$stringCompare->SetString($secretKey);
my $stringMatch10 = $stringCompare->ContentsEqual('', 1);
if ((!$tokenXml->LastMethodSuccess) || ($stringMatch10)) {
print "Missing credential field SecretAccessKey.\n";
exit;
}
$success = $path->SetString($credentialPath);
if (!$success) {
print "Could not construct credential path.\n";
exit;
}
$success = $path->Append('|SessionToken');
if (!$success) {
print "Could not construct credential path.\n";
exit;
}
my $sessionToken = $tokenXml->GetChildContent($path->GetAsString());
$stringCompare->SetString($sessionToken);
my $stringMatch11 = $stringCompare->ContentsEqual('', 1);
if ((!$tokenXml->LastMethodSuccess) || ($stringMatch11)) {
print "Missing credential field SessionToken.\n";
exit;
}
$success = $path->SetString($credentialPath);
if (!$success) {
print "Could not construct credential path.\n";
exit;
}
$success = $path->Append('|Expiration');
if (!$success) {
print "Could not construct credential path.\n";
exit;
}
my $expiration = $tokenXml->GetChildContent($path->GetAsString());
$stringCompare->SetString($expiration);
my $stringMatch12 = $stringCompare->ContentsEqual('', 1);
if ((!$tokenXml->LastMethodSuccess) || ($stringMatch12)) {
print "Missing credential field Expiration.\n";
exit;
}
my $expires = Chilkat2::DateTime->new;
my $now = Chilkat2::DateTime->new;
$success = $expires->SetFromTimestamp($expiration);
if (!$success) {
print "Stored expiration is invalid.\n";
exit;
}
$success = $now->SetFromCurrentSystemTime();
if (!$success) {
print "Could not read current time.\n";
exit;
}
if ($expires->DiffSeconds($now) <= 60) {
print "Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.\n";
exit;
}
my $session = Chilkat2::JsonObject->new;
$success = $session->UpdateString('access_key', $accessKey);
if (!$success) {
print "Could not build normalized session.\n";
exit;
}
$success = $session->UpdateString('secret_key', $secretKey);
if (!$success) {
print "Could not build normalized session.\n";
exit;
}
$success = $session->UpdateString('session_token', $sessionToken);
if (!$success) {
print "Could not build normalized session.\n";
exit;
}
$success = $session->UpdateString('expiration', $expiration);
if (!$success) {
print "Could not build normalized session.\n";
exit;
}
my $region = 'us-west-2';
my $endpoint = Chilkat2::StringBuilder->new;
$endpoint->Append('sts.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
my $aws = Chilkat2::AuthAws->new;
$aws->AccessKey($session->StringOf('access_key'));
$aws->SecretKey($session->StringOf('secret_key'));
$aws->Region($region);
$aws->ServiceName('sts');
$aws->SignatureVersion(4);
my $rest = Chilkat2::Rest->new;
$rest->ConnectTimeoutMs(20000);
$rest->IdleTimeoutMs(60000);
$rest->VerboseLogging(0);
$success = $rest->SetAuthAws($aws);
if (!$success) {
print "Could not configure request signing.\n";
exit;
}
# Keep this verified Socket alive while Rest uses its connection.
my $connection = Chilkat2::Socket->new;
$connection->RequireSslCertVerify(1);
$connection->MaxReadIdleMs(60000);
$connection->MaxSendIdleMs(60000);
$success = $connection->Connect($endpoint->GetAsString(), 443, 1, 20000);
if (!$success) {
print "TLS connection failed; inspect diagnostics privately.\n";
exit;
}
$success = $rest->UseConnection($connection, 1);
if (!$success) {
print "Could not attach TLS connection.\n";
exit;
}
my $xml = Chilkat2::Xml->new;
$xml->Strict(1);
my $value = '';
$success = $rest->ClearAllQueryParams();
if (!$success) {
print "Could not reset request parameters.\n";
exit;
}
$success = $rest->AddQueryParam('Action', 'GetCallerIdentity');
if (!$success) {
print "Could not set Action.\n";
exit;
}
$success = $rest->AddQueryParam('Version', '2011-06-15');
if (!$success) {
print "Could not set Version.\n";
exit;
}
$success = $rest->AddQueryParam('X-Amz-Security-Token', $session->StringOf('session_token'));
if (!$success) {
print "Could not set X-Amz-Security-Token.\n";
exit;
}
my $responseXml = $rest->FullRequestFormUrlEncoded('POST', '/');
if (!$rest->LastMethodSuccess) {
print "STS transport failed; inspect diagnostics privately.\n";
exit;
}
if ($rest->ResponseStatusCode != 200) {
print 'STS HTTP status: ', $rest->ResponseStatusCode, "\n";
$success = $xml->LoadXml($responseXml);
if ($success) {
$value = $xml->GetChildContent('Error|Code');
if ($xml->LastMethodSuccess) {
print 'AWS error code: ', $value, "\n";
}
$value = $xml->GetChildContent('RequestId');
if ($xml->LastMethodSuccess) {
print 'AWS request ID: ', $value, "\n";
}
}
exit;
}
$success = $xml->LoadXml($responseXml);
if (!$success) {
print "Invalid STS XML response.\n";
exit;
}
$stringCompare->SetString($xml->Tag);
my $stringMatch13 = $stringCompare->ContentsEqual('GetCallerIdentityResponse', 1);
if (!$stringMatch13) {
print "Unexpected STS response root.\n";
exit;
}
$value = $xml->GetChildContent('ResponseMetadata|RequestId');
$stringCompare->SetString($value);
my $stringMatch14 = $stringCompare->ContentsEqual('', 1);
if ((!$xml->LastMethodSuccess) || ($stringMatch14)) {
print "Missing or empty ResponseMetadata|RequestId.\n";
exit;
}
if (!$xml->HasChildWithTag('GetCallerIdentityResult')) {
print "Missing STS result.\n";
exit;
}
$value = $xml->GetChildContent('GetCallerIdentityResult|Arn');
$stringCompare->SetString($value);
my $stringMatch15 = $stringCompare->ContentsEqual('', 1);
if ((!$xml->LastMethodSuccess) || ($stringMatch15)) {
print "Missing or empty GetCallerIdentityResult|Arn.\n";
exit;
}
print 'Authenticated principal: ', $value, "\n";
print "Example completed.\n";