AWS STS: GetSessionToken with Optional MFA
See more AWS Security Token Service Examples
Uses Chilkat.Rest and AuthAws with AWS Signature Version 4. STS uses the Query API version 2011-06-15; that version date is still current. The examples send URL-encoded POST forms rather than operation parameters in a GET URL. They use the commercial-partition regional endpoint sts.us-west-2.amazonaws.com and matching signing region/service sts, with explicit TLS certificate verification. Choose the appropriate region/partition endpoint for your deployment.
Load private qa_data/aws/sts.json with nonempty string fields access_key and secret_key. These examples do not discover credentials, assume roles implicitly, or refresh credentials automatically. No access key, secret key, token, full XML response or diagnostic dump is printed.
Both credential-producing examples retain the existing handoff file qa_data/tokens/aws_session_token.xml. It contains plaintext credentials: pre-create a private directory with restrictive OS permissions and keep it out of web roots, source control, shared logs and shared storage. The sample checks the write, but does not set ACLs, encrypt the file, perform atomic replacement, or coordinate concurrent writers. Prefer in-memory handoff or an appropriate credential store in production. A failed request can leave an older file in place; do not assume a failed run refreshed it. The consumer validates expiration, allowing a 60-second margin.
Call with a long-term IAM user access key, not role/session credentials. This example rejects a supplied session_token and requests 3600 seconds. IAM user sessions allow 900–129600 seconds, default 43200. Do not use root credentials. Optional mfa_serial and mfa_code must be supplied together; the code is a six-digit string and can start with zero. Remove the short-lived MFA code from the private configuration after use; production applications should collect it at runtime.
GetSessionToken authenticates the IAM user and needs no permission grant for the GetSessionToken authentication operation. It does not assume a role or restrict the user's permissions via a session policy. The returned credentials inherit the user's permissions; IAM operations require MFA information, and the supported STS calls are limited to AssumeRole and GetCallerIdentity. For other workloads, prefer an appropriate role credential provider.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkDateTimeW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkXmlW.h>
void ChilkatSample(void)
{
bool success = false;
CkStringBuilderW stringCompare;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this file private and outside public web content/source control.
CkJsonObjectW credentials;
credentials.put_Strict(true);
success = credentials.LoadFile(L"qa_data/aws/sts.json");
if (success != true) {
wprintf(L"Could not load private STS configuration.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"access_key"));
bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
wprintf(L"Missing or invalid access_key.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
wprintf(L"Missing or invalid secret_key.\n");
return;
}
CkDateTimeW expires;
CkDateTimeW now;
const wchar_t *region = L"us-west-2";
if (credentials.HasMember(L"session_token") == true) {
wprintf(L"GetSessionToken requires long-term IAM user credentials, not an existing session token.\n");
return;
}
// MFA fields are optional as a pair. Preserve a leading zero in the code.
if ((credentials.HasMember(L"mfa_serial") == true) || (credentials.HasMember(L"mfa_code") == true)) {
stringCompare.SetString(credentials.stringOf(L"mfa_serial"));
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"mfa_serial") != 1) || (stringMatch3 == true)) {
wprintf(L"Missing or invalid mfa_serial.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"mfa_code"));
bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"mfa_code") != 1) || (stringMatch4 == true)) {
wprintf(L"Missing or invalid mfa_code.\n");
return;
}
CkStringBuilderW mfaCode;
mfaCode.Append(credentials.stringOf(L"mfa_code"));
if (mfaCode.get_Length() != 6) {
wprintf(L"mfa_code must be a six-digit string.\n");
return;
}
CkStringBuilderW digits;
digits.Append(L"0123456789");
int digitIndex = 0;
while ((digitIndex < 6)) {
if (digits.Contains(mfaCode.getRange(digitIndex,1,false),true) != true) {
wprintf(L"mfa_code must contain only ASCII digits.\n");
return;
}
digitIndex = digitIndex + 1;
}
}
CkStringBuilderW endpoint;
endpoint.Append(L"sts.");
endpoint.Append(region);
endpoint.Append(L".amazonaws.com");
CkAuthAwsW aws;
aws.put_AccessKey(credentials.stringOf(L"access_key"));
aws.put_SecretKey(credentials.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 *accessKey = 0;
const wchar_t *secretKey = 0;
const wchar_t *sessionToken = 0;
const wchar_t *expiration = 0;
success = rest.ClearAllQueryParams();
if (success != true) {
wprintf(L"Could not clear request parameters.\n");
return;
}
success = rest.AddQueryParam(L"Action",L"GetSessionToken");
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"DurationSeconds",L"3600");
if (success != true) {
wprintf(L"Could not set DurationSeconds.\n");
return;
}
if (credentials.HasMember(L"mfa_serial") == true) {
success = rest.AddQueryParam(L"SerialNumber",credentials.stringOf(L"mfa_serial"));
if (success != true) {
wprintf(L"Could not set SerialNumber.\n");
return;
}
success = rest.AddQueryParam(L"TokenCode",credentials.stringOf(L"mfa_code"));
if (success != true) {
wprintf(L"Could not set TokenCode.\n");
return;
}
}
const wchar_t *responseXml = rest.fullRequestFormUrlEncoded(L"POST",L"/");
if (rest.get_LastMethodSuccess() != true) {
wprintf(L"STS request did not complete; no credentials were saved. Inspect diagnostics privately.\n");
return;
}
success = xml.LoadXml(responseXml);
if (rest.get_ResponseStatusCode() != 200) {
wprintf(L"STS HTTP status: %d\n",rest.get_ResponseStatusCode());
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);
}
}
// Full bodies, headers, and diagnostics can contain sensitive data.
return;
}
if (success != true) {
wprintf(L"Invalid STS XML response; no credentials were saved.\n");
return;
}
stringCompare.SetString(xml.tag());
bool stringMatch5 = stringCompare.ContentsEqual(L"GetSessionTokenResponse",true);
if (stringMatch5 != true) {
wprintf(L"Unexpected STS response root.\n");
return;
}
value = xml.getChildContent(L"ResponseMetadata|RequestId");
stringCompare.SetString(value);
bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch6 == true)) {
wprintf(L"Missing or empty ResponseMetadata|RequestId.\n");
return;
}
wprintf(L"AWS request ID: %s\n",value);
accessKey = xml.getChildContent(L"GetSessionTokenResult|Credentials|AccessKeyId");
stringCompare.SetString(accessKey);
bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch7 == true)) {
wprintf(L"Missing or empty GetSessionTokenResult|Credentials|AccessKeyId.\n");
return;
}
secretKey = xml.getChildContent(L"GetSessionTokenResult|Credentials|SecretAccessKey");
stringCompare.SetString(secretKey);
bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch8 == true)) {
wprintf(L"Missing or empty GetSessionTokenResult|Credentials|SecretAccessKey.\n");
return;
}
sessionToken = xml.getChildContent(L"GetSessionTokenResult|Credentials|SessionToken");
stringCompare.SetString(sessionToken);
bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch9 == true)) {
wprintf(L"Missing or empty GetSessionTokenResult|Credentials|SessionToken.\n");
return;
}
expiration = xml.getChildContent(L"GetSessionTokenResult|Credentials|Expiration");
stringCompare.SetString(expiration);
bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch10 == true)) {
wprintf(L"Missing or empty GetSessionTokenResult|Credentials|Expiration.\n");
return;
}
success = expires.SetFromTimestamp(expiration);
if (success != true) {
wprintf(L"Returned 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"Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
return;
}
// Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
// Reuses the existing handoff filename for the companion S3 example.
success = xml.SaveXml(L"qa_data/tokens/aws_session_token.xml");
if (success != true) {
wprintf(L"Could not save the private credential file; do not assume it was updated.\n");
return;
}
wprintf(L"Temporary credentials saved privately; expiration: %s\n",expiration);
}