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 Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkXmlW.h>
#include <CkDateTimeW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// Load a privately stored STS XML response; never print its contents.
CkXmlW tokenXml;
tokenXml.put_Strict(true);
success = tokenXml.LoadXmlFile(L"qa_data/tokens/aws_session_token.xml");
if (success != true) {
wprintf(L"Could not load private STS XML.\n");
return;
}
const wchar_t *credentialPath = L"";
stringCompare.SetString(tokenXml.tag());
bool stringMatch1 = stringCompare.ContentsEqual(L"GetSessionTokenResponse",true);
if (stringMatch1 == true) {
credentialPath = L"GetSessionTokenResult|Credentials";
}
stringCompare.SetString(tokenXml.tag());
bool stringMatch2 = stringCompare.ContentsEqual(L"AssumeRoleResponse",true);
if (stringMatch2 == true) {
credentialPath = L"AssumeRoleResult|Credentials";
}
stringCompare.SetString(tokenXml.tag());
bool stringMatch3 = stringCompare.ContentsEqual(L"AssumeRoleWithWebIdentityResponse",true);
if (stringMatch3 == true) {
credentialPath = L"AssumeRoleWithWebIdentityResult|Credentials";
}
stringCompare.SetString(tokenXml.tag());
bool stringMatch4 = stringCompare.ContentsEqual(L"AssumeRoleWithSAMLResponse",true);
if (stringMatch4 == true) {
credentialPath = L"AssumeRoleWithSAMLResult|Credentials";
}
stringCompare.SetString(tokenXml.tag());
bool stringMatch5 = stringCompare.ContentsEqual(L"GetFederationTokenResponse",true);
if (stringMatch5 == true) {
credentialPath = L"GetFederationTokenResult|Credentials";
}
stringCompare.SetString(tokenXml.tag());
bool stringMatch6 = stringCompare.ContentsEqual(L"GetDelegatedAccessTokenResponse",true);
if (stringMatch6 == true) {
credentialPath = L"GetDelegatedAccessTokenResult|Credentials";
}
stringCompare.SetString(tokenXml.tag());
bool stringMatch7 = stringCompare.ContentsEqual(L"AssumeRootResponse",true);
if (stringMatch7 == true) {
credentialPath = L"AssumeRootResult|Credentials";
}
stringCompare.SetString(credentialPath);
bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
if (stringMatch8 == true) {
wprintf(L"Unsupported STS credential response.\n");
return;
}
const wchar_t *accessKey = 0;
const wchar_t *secretKey = 0;
const wchar_t *sessionToken = 0;
const wchar_t *expiration = 0;
CkStringBuilderW path;
success = path.SetString(credentialPath);
if (success != true) {
wprintf(L"Could not construct credential path.\n");
return;
}
success = path.Append(L"|AccessKeyId");
if (success != true) {
wprintf(L"Could not construct credential path.\n");
return;
}
accessKey = tokenXml.getChildContent(path.getAsString());
stringCompare.SetString(accessKey);
bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
if ((tokenXml.get_LastMethodSuccess() != true) || (stringMatch9 == true)) {
wprintf(L"Missing credential field AccessKeyId.\n");
return;
}
success = path.SetString(credentialPath);
if (success != true) {
wprintf(L"Could not construct credential path.\n");
return;
}
success = path.Append(L"|SecretAccessKey");
if (success != true) {
wprintf(L"Could not construct credential path.\n");
return;
}
secretKey = tokenXml.getChildContent(path.getAsString());
stringCompare.SetString(secretKey);
bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
if ((tokenXml.get_LastMethodSuccess() != true) || (stringMatch10 == true)) {
wprintf(L"Missing credential field SecretAccessKey.\n");
return;
}
success = path.SetString(credentialPath);
if (success != true) {
wprintf(L"Could not construct credential path.\n");
return;
}
success = path.Append(L"|SessionToken");
if (success != true) {
wprintf(L"Could not construct credential path.\n");
return;
}
sessionToken = tokenXml.getChildContent(path.getAsString());
stringCompare.SetString(sessionToken);
bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
if ((tokenXml.get_LastMethodSuccess() != true) || (stringMatch11 == true)) {
wprintf(L"Missing credential field SessionToken.\n");
return;
}
success = path.SetString(credentialPath);
if (success != true) {
wprintf(L"Could not construct credential path.\n");
return;
}
success = path.Append(L"|Expiration");
if (success != true) {
wprintf(L"Could not construct credential path.\n");
return;
}
expiration = tokenXml.getChildContent(path.getAsString());
stringCompare.SetString(expiration);
bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
if ((tokenXml.get_LastMethodSuccess() != true) || (stringMatch12 == true)) {
wprintf(L"Missing credential field Expiration.\n");
return;
}
CkDateTimeW expires;
CkDateTimeW now;
success = expires.SetFromTimestamp(expiration);
if (success != true) {
wprintf(L"Stored expiration is invalid.\n");
return;
}
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read current time.\n");
return;
}
if (expires.DiffSeconds(now) <= 60) {
wprintf(L"Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
return;
}
CkJsonObjectW session;
success = session.UpdateString(L"access_key",accessKey);
if (success != true) {
wprintf(L"Could not build normalized session.\n");
return;
}
success = session.UpdateString(L"secret_key",secretKey);
if (success != true) {
wprintf(L"Could not build normalized session.\n");
return;
}
success = session.UpdateString(L"session_token",sessionToken);
if (success != true) {
wprintf(L"Could not build normalized session.\n");
return;
}
success = session.UpdateString(L"expiration",expiration);
if (success != true) {
wprintf(L"Could not build normalized session.\n");
return;
}
const wchar_t *region = L"us-west-2";
CkStringBuilderW endpoint;
endpoint.Append(L"sts.");
endpoint.Append(region);
endpoint.Append(L".amazonaws.com");
CkAuthAwsW aws;
aws.put_AccessKey(session.stringOf(L"access_key"));
aws.put_SecretKey(session.stringOf(L"secret_key"));
aws.put_Region(region);
aws.put_ServiceName(L"sts");
aws.put_SignatureVersion(4);
CkRestW rest;
rest.put_ConnectTimeoutMs(20000);
rest.put_IdleTimeoutMs(60000);
rest.put_VerboseLogging(false);
success = rest.SetAuthAws(aws);
if (success != true) {
wprintf(L"Could not configure request signing.\n");
return;
}
// Keep this verified Socket alive while Rest uses its connection.
CkSocketW connection;
connection.put_RequireSslCertVerify(true);
connection.put_MaxReadIdleMs(60000);
connection.put_MaxSendIdleMs(60000);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
wprintf(L"Could not attach TLS connection.\n");
return;
}
CkXmlW xml;
xml.put_Strict(true);
const wchar_t *value = 0;
const wchar_t *responseXml = 0;
success = rest.ClearAllQueryParams();
if (success != true) {
wprintf(L"Could not reset request parameters.\n");
return;
}
success = rest.AddQueryParam(L"Action",L"GetCallerIdentity");
if (success != true) {
wprintf(L"Could not set Action.\n");
return;
}
success = rest.AddQueryParam(L"Version",L"2011-06-15");
if (success != true) {
wprintf(L"Could not set Version.\n");
return;
}
success = rest.AddQueryParam(L"X-Amz-Security-Token",session.stringOf(L"session_token"));
if (success != true) {
wprintf(L"Could not set X-Amz-Security-Token.\n");
return;
}
responseXml = rest.fullRequestFormUrlEncoded(L"POST",L"/");
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"STS transport failed; inspect diagnostics privately.\n");
return;
}
if (rest.get_ResponseStatusCode() != 200) {
wprintf(L"STS HTTP status: %d\n",rest.get_ResponseStatusCode());
success = xml.LoadXml(responseXml);
if (success == true) {
value = xml.getChildContent(L"Error|Code");
if (xml.get_LastMethodSuccess() == true) {
wprintf(L"AWS error code: %s\n",value);
}
value = xml.getChildContent(L"RequestId");
if (xml.get_LastMethodSuccess() == true) {
wprintf(L"AWS request ID: %s\n",value);
}
}
return;
}
success = xml.LoadXml(responseXml);
if (success != true) {
wprintf(L"Invalid STS XML response.\n");
return;
}
stringCompare.SetString(xml.tag());
bool stringMatch13 = stringCompare.ContentsEqual(L"GetCallerIdentityResponse",true);
if (stringMatch13 != true) {
wprintf(L"Unexpected STS response root.\n");
return;
}
value = xml.getChildContent(L"ResponseMetadata|RequestId");
stringCompare.SetString(value);
bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch14 == true)) {
wprintf(L"Missing or empty ResponseMetadata|RequestId.\n");
return;
}
if (xml.HasChildWithTag(L"GetCallerIdentityResult") != true) {
wprintf(L"Missing STS result.\n");
return;
}
value = xml.getChildContent(L"GetCallerIdentityResult|Arn");
stringCompare.SetString(value);
bool stringMatch15 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch15 == true)) {
wprintf(L"Missing or empty GetCallerIdentityResult|Arn.\n");
return;
}
wprintf(L"Authenticated principal: %s\n",value);
wprintf(L"Example completed.\n");
}