AWS STS: Obtain an AWS-Signed JWT for an External Service
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.
Set audience to the intended external service. Requests RS256 with a five-minute lifetime from a regional STS endpoint; outbound federation must be enabled for the account. Optional subject_mode is AWSIdentity or OriginIdentity. OriginIdentity requires the caller's trusted identity propagation context. Optional scope is permitted only for OriginIdentity and this single audience, and requires sts:SetWebIdentityTokenScope in addition to sts:GetWebIdentityToken. Validates scope spacing, characters and duplicate values.
The returned token is an external identity JWT, not an AWS access key/session-token credential set. The recipient must validate its signature using the trusted issuer's JWKS, issuer, audience and lifetime; merely decoding it is insufficient. The request cannot extend the calling session's lifetime.
AWS references: GetWebIdentityToken
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkDateTimeW.h>
#include <CkStringTableW.h>
#include <CkHashtableW.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"audience"));
bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"audience") != 1) || (stringMatch5 == true)) {
wprintf(L"Missing or invalid audience.\n");
return;
}
// Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
const wchar_t *subjectMode = L"AWSIdentity";
if (credentials.HasMember(L"subject_mode") == true) {
stringCompare.SetString(credentials.stringOf(L"subject_mode"));
bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"subject_mode") != 1) || (stringMatch6 == true)) {
wprintf(L"Missing or invalid subject_mode.\n");
return;
}
subjectMode = credentials.stringOf(L"subject_mode");
}
stringCompare.SetString(subjectMode);
bool stringMatch7 = stringCompare.ContentsEqual(L"AWSIdentity",true);
stringCompare.SetString(subjectMode);
bool stringMatch8 = stringCompare.ContentsEqual(L"OriginIdentity",true);
if ((stringMatch7 != true) && (stringMatch8 != true)) {
wprintf(L"Invalid subject_mode.\n");
return;
}
if (credentials.HasMember(L"scope") == true) {
stringCompare.SetString(credentials.stringOf(L"scope"));
bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"scope") != 1) || (stringMatch9 == true)) {
wprintf(L"Missing or invalid scope.\n");
return;
}
stringCompare.SetString(subjectMode);
bool stringMatch10 = stringCompare.ContentsEqual(L"OriginIdentity",true);
if (stringMatch10 != true) {
wprintf(L"scope requires OriginIdentity.\n");
return;
}
CkStringBuilderW scopeText;
scopeText.Append(credentials.stringOf(L"scope"));
if ((scopeText.get_Length() > 256) || (scopeText.StartsWith(L" ",true) == true) || (scopeText.EndsWith(L" ",true) == true) || (scopeText.Contains(L" ",true) == true)) {
wprintf(L"Invalid scope length or spacing.\n");
return;
}
CkStringBuilderW allowedScope;
allowedScope.Append(L"!#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ");
int scopeIndex = 0;
while ((scopeIndex < scopeText.get_Length())) {
if (allowedScope.Contains(scopeText.getRange(scopeIndex,1,false),true) != true) {
wprintf(L"Invalid scope character.\n");
return;
}
scopeIndex = scopeIndex + 1;
}
CkStringTableW scopeValues;
success = scopeValues.SplitAndAppend(scopeText.getAsString(),L" ",false,false);
if (success != true) {
wprintf(L"Could not split scope values.\n");
return;
}
CkHashtableW seenScopes;
scopeIndex = 0;
const wchar_t *scopeValue = 0;
while ((scopeIndex < scopeValues.get_Count())) {
scopeValue = scopeValues.stringAt(scopeIndex);
if (seenScopes.Contains(scopeValue) == true) {
wprintf(L"Duplicate scope value.\n");
return;
}
success = seenScopes.AddStr(scopeValue,L"seen");
if (success != true) {
wprintf(L"Could not track scope values.\n");
return;
}
scopeIndex = scopeIndex + 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 *sessionToken = 0;
const wchar_t *expiration = 0;
const wchar_t *responseXml = L"";
success = rest.ClearAllQueryParams();
if (success != true) {
wprintf(L"Could not reset request parameters.\n");
return;
}
success = rest.AddQueryParam(L"Action",L"GetWebIdentityToken");
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;
}
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"Audience.member.1",credentials.stringOf(L"audience"));
if (success != true) {
wprintf(L"Could not set Audience.member.1.\n");
return;
}
success = rest.AddQueryParam(L"SigningAlgorithm",L"RS256");
if (success != true) {
wprintf(L"Could not set SigningAlgorithm.\n");
return;
}
success = rest.AddQueryParam(L"DurationSeconds",L"300");
if (success != true) {
wprintf(L"Could not set DurationSeconds.\n");
return;
}
success = rest.AddQueryParam(L"SubjectMode",subjectMode);
if (success != true) {
wprintf(L"Could not set SubjectMode.\n");
return;
}
if (credentials.HasMember(L"scope") == true) {
success = rest.AddQueryParam(L"Scope",credentials.stringOf(L"scope"));
if (success != true) {
wprintf(L"Could not set Scope.\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 stringMatch11 = stringCompare.ContentsEqual(L"GetWebIdentityTokenResponse",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;
}
if (xml.HasChildWithTag(L"GetWebIdentityTokenResult") != true) {
wprintf(L"Missing STS result.\n");
return;
}
sessionToken = xml.getChildContent(L"GetWebIdentityTokenResult|WebIdentityToken");
stringCompare.SetString(sessionToken);
bool stringMatch13 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch13 == true)) {
wprintf(L"Missing or empty GetWebIdentityTokenResult|WebIdentityToken.\n");
return;
}
expiration = xml.getChildContent(L"GetWebIdentityTokenResult|Expiration");
stringCompare.SetString(expiration);
bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
if ((xml.get_LastMethodSuccess() != true) || (stringMatch14 == true)) {
wprintf(L"Missing or empty GetWebIdentityTokenResult|Expiration.\n");
return;
}
success = expires.SetFromTimestamp(expiration);
if (success != true) {
wprintf(L"JWT 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"JWT credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
return;
}
// Hand sessionToken to the intended external service over TLS; never log it.
wprintf(L"Web identity token obtained; expiration: %s\n",expiration);
wprintf(L"Example completed.\n");
}