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 C# Downloads
bool success = false;
Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this file private and outside public web content/source control.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/sts.json");
if (success != true) {
Debug.WriteLine("Could not load private STS configuration.");
return;
}
stringCompare.SetString(credentials.StringOf("access_key"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
Debug.WriteLine("Missing or invalid access_key.");
return;
}
stringCompare.SetString(credentials.StringOf("secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
Debug.WriteLine("Missing or invalid secret_key.");
return;
}
Chilkat.CkDateTime expires = new Chilkat.CkDateTime();
Chilkat.CkDateTime now = new Chilkat.CkDateTime();
string region = "us-west-2";
if (credentials.HasMember("session_token") == true) {
stringCompare.SetString(credentials.StringOf("session_token"));
bool stringMatch3 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
Debug.WriteLine("Missing or invalid session_token.");
return;
}
stringCompare.SetString(credentials.StringOf("expiration"));
bool stringMatch4 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("expiration") != 1) || (stringMatch4 == true)) {
Debug.WriteLine("Missing or invalid expiration.");
return;
}
success = expires.SetFromTimestamp(credentials.StringOf("expiration"));
if (success != true) {
Debug.WriteLine("Source expiration is invalid.");
return;
}
success = now.SetFromCurrentSystemTime();
if (success != true) {
Debug.WriteLine("Could not read current time.");
return;
}
if (expires.DiffSeconds(now) <= 60) {
Debug.WriteLine("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.");
return;
}
}
stringCompare.SetString(credentials.StringOf("audience"));
bool stringMatch5 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("audience") != 1) || (stringMatch5 == true)) {
Debug.WriteLine("Missing or invalid audience.");
return;
}
// Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
string subjectMode = "AWSIdentity";
if (credentials.HasMember("subject_mode") == true) {
stringCompare.SetString(credentials.StringOf("subject_mode"));
bool stringMatch6 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("subject_mode") != 1) || (stringMatch6 == true)) {
Debug.WriteLine("Missing or invalid subject_mode.");
return;
}
subjectMode = credentials.StringOf("subject_mode");
}
stringCompare.SetString(subjectMode);
bool stringMatch7 = stringCompare.ContentsEqual("AWSIdentity",true);
stringCompare.SetString(subjectMode);
bool stringMatch8 = stringCompare.ContentsEqual("OriginIdentity",true);
if ((stringMatch7 != true) && (stringMatch8 != true)) {
Debug.WriteLine("Invalid subject_mode.");
return;
}
if (credentials.HasMember("scope") == true) {
stringCompare.SetString(credentials.StringOf("scope"));
bool stringMatch9 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("scope") != 1) || (stringMatch9 == true)) {
Debug.WriteLine("Missing or invalid scope.");
return;
}
stringCompare.SetString(subjectMode);
bool stringMatch10 = stringCompare.ContentsEqual("OriginIdentity",true);
if (stringMatch10 != true) {
Debug.WriteLine("scope requires OriginIdentity.");
return;
}
Chilkat.StringBuilder scopeText = new Chilkat.StringBuilder();
scopeText.Append(credentials.StringOf("scope"));
if ((scopeText.Length > 256) || (scopeText.StartsWith(" ",true) == true) || (scopeText.EndsWith(" ",true) == true) || (scopeText.Contains(" ",true) == true)) {
Debug.WriteLine("Invalid scope length or spacing.");
return;
}
Chilkat.StringBuilder allowedScope = new Chilkat.StringBuilder();
allowedScope.Append("!#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ");
int scopeIndex = 0;
while ((scopeIndex < scopeText.Length)) {
if (allowedScope.Contains(scopeText.GetRange(scopeIndex,1,false),true) != true) {
Debug.WriteLine("Invalid scope character.");
return;
}
scopeIndex = scopeIndex + 1;
}
Chilkat.StringTable scopeValues = new Chilkat.StringTable();
success = scopeValues.SplitAndAppend(scopeText.GetAsString()," ",false,false);
if (success != true) {
Debug.WriteLine("Could not split scope values.");
return;
}
Chilkat.Hashtable seenScopes = new Chilkat.Hashtable();
scopeIndex = 0;
string scopeValue;
while ((scopeIndex < scopeValues.Count)) {
scopeValue = scopeValues.StringAt(scopeIndex);
if (seenScopes.Contains(scopeValue) == true) {
Debug.WriteLine("Duplicate scope value.");
return;
}
success = seenScopes.AddStr(scopeValue,"seen");
if (success != true) {
Debug.WriteLine("Could not track scope values.");
return;
}
scopeIndex = scopeIndex + 1;
}
}
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("sts.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
Chilkat.AuthAws aws = new Chilkat.AuthAws();
aws.AccessKey = credentials.StringOf("access_key");
aws.SecretKey = credentials.StringOf("secret_key");
aws.Region = region;
aws.ServiceName = "sts";
aws.SignatureVersion = 4;
Chilkat.Rest rest = new Chilkat.Rest();
rest.ConnectTimeoutMs = 20000;
rest.IdleTimeoutMs = 60000;
rest.VerboseLogging = false;
success = rest.SetAuthAws(aws);
if (success != true) {
Debug.WriteLine("Could not configure request signing.");
return;
}
// Keep this verified Socket alive while Rest uses its connection.
Chilkat.Socket connection = new Chilkat.Socket();
connection.RequireSslCertVerify = true;
connection.MaxReadIdleMs = 60000;
connection.MaxSendIdleMs = 60000;
success = connection.Connect(endpoint.GetAsString(),443,true,20000);
if (success != true) {
Debug.WriteLine("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
Debug.WriteLine("Could not attach TLS connection.");
return;
}
Chilkat.Xml xml = new Chilkat.Xml();
xml.Strict = true;
string value;
string sessionToken;
string expiration;
string responseXml = "";
success = rest.ClearAllQueryParams();
if (success != true) {
Debug.WriteLine("Could not reset request parameters.");
return;
}
success = rest.AddQueryParam("Action","GetWebIdentityToken");
if (success != true) {
Debug.WriteLine("Could not set Action.");
return;
}
success = rest.AddQueryParam("Version","2011-06-15");
if (success != true) {
Debug.WriteLine("Could not set Version.");
return;
}
if (credentials.HasMember("session_token") == true) {
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"));
if (success != true) {
Debug.WriteLine("Could not set X-Amz-Security-Token.");
return;
}
}
success = rest.AddQueryParam("Audience.member.1",credentials.StringOf("audience"));
if (success != true) {
Debug.WriteLine("Could not set Audience.member.1.");
return;
}
success = rest.AddQueryParam("SigningAlgorithm","RS256");
if (success != true) {
Debug.WriteLine("Could not set SigningAlgorithm.");
return;
}
success = rest.AddQueryParam("DurationSeconds","300");
if (success != true) {
Debug.WriteLine("Could not set DurationSeconds.");
return;
}
success = rest.AddQueryParam("SubjectMode",subjectMode);
if (success != true) {
Debug.WriteLine("Could not set SubjectMode.");
return;
}
if (credentials.HasMember("scope") == true) {
success = rest.AddQueryParam("Scope",credentials.StringOf("scope"));
if (success != true) {
Debug.WriteLine("Could not set Scope.");
return;
}
}
responseXml = rest.FullRequestFormUrlEncoded("POST","/");
if (rest.LastMethodSuccess != true) {
Debug.WriteLine("STS transport failed; inspect diagnostics privately.");
return;
}
if (rest.ResponseStatusCode != 200) {
Debug.WriteLine("STS HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
success = xml.LoadXml(responseXml);
if (success == true) {
value = xml.GetChildContent("Error|Code");
if (xml.LastMethodSuccess == true) {
Debug.WriteLine("AWS error code: " + value);
}
value = xml.GetChildContent("RequestId");
if (xml.LastMethodSuccess == true) {
Debug.WriteLine("AWS request ID: " + value);
}
}
return;
}
success = xml.LoadXml(responseXml);
if (success != true) {
Debug.WriteLine("Invalid STS XML response.");
return;
}
stringCompare.SetString(xml.Tag);
bool stringMatch11 = stringCompare.ContentsEqual("GetWebIdentityTokenResponse",true);
if (stringMatch11 != true) {
Debug.WriteLine("Unexpected STS response root.");
return;
}
value = xml.GetChildContent("ResponseMetadata|RequestId");
stringCompare.SetString(value);
bool stringMatch12 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch12 == true)) {
Debug.WriteLine("Missing or empty ResponseMetadata|RequestId.");
return;
}
if (xml.HasChildWithTag("GetWebIdentityTokenResult") != true) {
Debug.WriteLine("Missing STS result.");
return;
}
sessionToken = xml.GetChildContent("GetWebIdentityTokenResult|WebIdentityToken");
stringCompare.SetString(sessionToken);
bool stringMatch13 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch13 == true)) {
Debug.WriteLine("Missing or empty GetWebIdentityTokenResult|WebIdentityToken.");
return;
}
expiration = xml.GetChildContent("GetWebIdentityTokenResult|Expiration");
stringCompare.SetString(expiration);
bool stringMatch14 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch14 == true)) {
Debug.WriteLine("Missing or empty GetWebIdentityTokenResult|Expiration.");
return;
}
success = expires.SetFromTimestamp(expiration);
if (success != true) {
Debug.WriteLine("JWT expiration is invalid.");
return;
}
success = now.SetFromCurrentSystemTime();
if (success != true) {
Debug.WriteLine("Could not read current time.");
return;
}
if (expires.DiffSeconds(now) <= 60) {
Debug.WriteLine("JWT credentials are expired or expire within 60 seconds; obtain fresh credentials.");
return;
}
// Hand sessionToken to the intended external service over TLS; never log it.
Debug.WriteLine("Web identity token obtained; expiration: " + expiration);
Debug.WriteLine("Example completed.");