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