AWS STS: Assume a Role for S3 Bucket Listing
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.
Set role_arn and role_session_name in the private configuration. Names must contain 2–64 allowed characters. The target trust policy and applicable caller authorization must permit AssumeRole. The sample's session policy permits only s3:ListAllMyBuckets, intersected with the role's permissions, for use by the companion S3 listing example; it cannot elevate the role's access. Other policy types, denies and resource-based rules still participate in authorization.
The fixed 3600-second request works within the one-hour role-chaining ceiling and must still fit the role's configured maximum. For temporary source credentials, also provide nonempty session_token and ISO 8601 expiration. The token is included in the signed form body. Optional external_id must be the value agreed with the role owner; it is not a password. Optional source_identity is subject to AWS syntax, trust conditions and sts:SetSourceIdentity permission. Optional MFA uses mfa_serial/mfa_code as a pair. These optional values must satisfy the actual trust policy.
This focused example omits managed session policies and session tags. When adding them, configure the required policies and tagging permissions, and account for inherited transitive tags during role chaining. STS session-token sizes are variable; preserve the complete value without a fixed buffer or truncation.
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) {
stringCompare.SetString(credentials.stringOf(L"session_token"));
bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
wprintf(L"Missing or invalid session_token.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"expiration"));
bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"expiration") != 1) || (stringMatch4 == true)) {
wprintf(L"Missing or invalid expiration.\n");
return;
}
success = expires.SetFromTimestamp(credentials.stringOf(L"expiration"));
if (success != true) {
wprintf(L"Source 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"Source credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
return;
}
}
stringCompare.SetString(credentials.stringOf(L"role_arn"));
bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"role_arn") != 1) || (stringMatch5 == true)) {
wprintf(L"Missing or invalid role_arn.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"role_session_name"));
bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"role_session_name") != 1) || (stringMatch6 == true)) {
wprintf(L"Missing or invalid role_session_name.\n");
return;
}
CkStringBuilderW identifier;
identifier.Append(credentials.stringOf(L"role_session_name"));
if ((identifier.get_Length() < 2) || (identifier.get_Length() > 64)) {
wprintf(L"role_session_name must have 2-64 characters.\n");
return;
}
CkStringBuilderW allowed;
allowed.Append(L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-");
int charIndex = 0;
while ((charIndex < identifier.get_Length())) {
if (allowed.Contains(identifier.getRange(charIndex,1,false),true) != true) {
wprintf(L"Invalid character in role_session_name.\n");
return;
}
charIndex = charIndex + 1;
}
CkStringBuilderW roleArn;
roleArn.Append(credentials.stringOf(L"role_arn"));
if ((roleArn.StartsWith(L"arn:aws:iam::",true) != true) || (roleArn.Contains(L":role/",true) != true)) {
wprintf(L"Use an IAM role ARN in the commercial AWS partition.\n");
return;
}
if (credentials.HasMember(L"external_id") == true) {
stringCompare.SetString(credentials.stringOf(L"external_id"));
bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"external_id") != 1) || (stringMatch7 == true)) {
wprintf(L"Missing or invalid external_id.\n");
return;
}
}
if (credentials.HasMember(L"source_identity") == true) {
stringCompare.SetString(credentials.stringOf(L"source_identity"));
bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"source_identity") != 1) || (stringMatch8 == true)) {
wprintf(L"Missing or invalid source_identity.\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 stringMatch9 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"mfa_serial") != 1) || (stringMatch9 == true)) {
wprintf(L"Missing or invalid mfa_serial.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"mfa_code"));
bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"mfa_code") != 1) || (stringMatch10 == 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"AssumeRole");
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"session_token") == true) {
success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
if (success != true) {
wprintf(L"Could not set X-Amz-Security-Token.\n");
return;
}
}
success = rest.AddQueryParam(L"RoleArn",credentials.stringOf(L"role_arn"));
if (success != true) {
wprintf(L"Could not set RoleArn.\n");
return;
}
success = rest.AddQueryParam(L"RoleSessionName",credentials.stringOf(L"role_session_name"));
if (success != true) {
wprintf(L"Could not set RoleSessionName.\n");
return;
}
// A session policy only restricts the role; it cannot add permissions.
CkJsonObjectW policy;
success = policy.UpdateString(L"Version",L"2012-10-17");
if (success != true) {
wprintf(L"Could not set policy version.\n");
return;
}
success = policy.UpdateString(L"Statement[0].Effect",L"Allow");
if (success != true) {
wprintf(L"Could not set policy effect.\n");
return;
}
success = policy.UpdateString(L"Statement[0].Action",L"s3:ListAllMyBuckets");
if (success != true) {
wprintf(L"Could not set policy action.\n");
return;
}
success = policy.UpdateString(L"Statement[0].Resource",L"*");
if (success != true) {
wprintf(L"Could not set policy resource.\n");
return;
}
success = rest.AddQueryParam(L"Policy",policy.emit());
if (success != true) {
wprintf(L"Could not set Policy.\n");
return;
}
if (credentials.HasMember(L"external_id") == true) {
success = rest.AddQueryParam(L"ExternalId",credentials.stringOf(L"external_id"));
if (success != true) {
wprintf(L"Could not set ExternalId.\n");
return;
}
}
if (credentials.HasMember(L"source_identity") == true) {
success = rest.AddQueryParam(L"SourceIdentity",credentials.stringOf(L"source_identity"));
if (success != true) {
wprintf(L"Could not set SourceIdentity.\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 stringMatch11 = stringCompare.ContentsEqual(L"AssumeRoleResponse",true);
if (stringMatch11 != true) {
wprintf(L"Unexpected STS response root.\n");
return;
}
value = xml.getChildContent(L"ResponseMetadata|RequestId");
stringCompare.SetString(value);
bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch12 == true)) {
wprintf(L"Missing or empty ResponseMetadata|RequestId.\n");
return;
}
wprintf(L"AWS request ID: %s\n",value);
accessKey = xml.getChildContent(L"AssumeRoleResult|Credentials|AccessKeyId");
stringCompare.SetString(accessKey);
bool stringMatch13 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch13 == true)) {
wprintf(L"Missing or empty AssumeRoleResult|Credentials|AccessKeyId.\n");
return;
}
secretKey = xml.getChildContent(L"AssumeRoleResult|Credentials|SecretAccessKey");
stringCompare.SetString(secretKey);
bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch14 == true)) {
wprintf(L"Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.\n");
return;
}
sessionToken = xml.getChildContent(L"AssumeRoleResult|Credentials|SessionToken");
stringCompare.SetString(sessionToken);
bool stringMatch15 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch15 == true)) {
wprintf(L"Missing or empty AssumeRoleResult|Credentials|SessionToken.\n");
return;
}
expiration = xml.getChildContent(L"AssumeRoleResult|Credentials|Expiration");
stringCompare.SetString(expiration);
bool stringMatch16 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch16 == true)) {
wprintf(L"Missing or empty AssumeRoleResult|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;
}
value = xml.getChildContent(L"AssumeRoleResult|AssumedRoleUser|Arn");
stringCompare.SetString(value);
bool stringMatch17 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch17 == true)) {
wprintf(L"Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.\n");
return;
}
value = xml.getChildContent(L"AssumeRoleResult|AssumedRoleUser|AssumedRoleId");
stringCompare.SetString(value);
bool stringMatch18 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch18 == true)) {
wprintf(L"Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.\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);
}