AWS STS: Refresh an AssumeRole Session Before Expiration
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.
Configure source credentials, role_arn and role_session_name for an unattended role that does not require interactive MFA. Optional qa_data/tokens/sts_session.json holds a previous normalized session for exactly that role, session configuration and workload; keep this cache private and never reuse it across roles. A complete cached set with more than five minutes remaining is reused. Otherwise obtains a new one-hour session, validates it, and publishes one serialized in-memory snapshot. No cache file is overwritten. Existing credentials cannot be extended.
Retries throttling and selected transient HTTP errors at most three times with one- and two-second waits, rebuilding the signed form and checking source expiration on each attempt. Transport, authorization and invalid-response failures stop without publication. Add jitter, synchronization and a credential provider appropriate to your runtime in a concurrent application. This single-thread sample does not implement shared-cache locking or reuse expired sources/MFA codes. Repeat the refresh decision before each unit of work.
AWS references: AssumeRole
Chilkat Objective-C Downloads
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoDateTime.h>
#import <NSString.h>
#import <CkoFileAccess.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: @"role_arn"]];
BOOL stringMatch5 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"role_arn"] intValue] != 1) || (stringMatch5 == YES)) {
NSLog(@"%@",@"Missing or invalid role_arn.");
return;
}
[stringCompare SetString: [credentials StringOf: @"role_session_name"]];
BOOL stringMatch6 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"role_session_name"] intValue] != 1) || (stringMatch6 == YES)) {
NSLog(@"%@",@"Missing or invalid role_session_name.");
return;
}
CkoStringBuilder *identifier = [[CkoStringBuilder alloc] init];
[identifier Append: [credentials StringOf: @"role_session_name"]];
if (([identifier.Length intValue] < 2) || ([identifier.Length intValue] > 64)) {
NSLog(@"%@",@"role_session_name must have 2-64 characters.");
return;
}
CkoStringBuilder *allowed = [[CkoStringBuilder alloc] init];
[allowed Append: @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-"];
int charIndex = 0;
while ((charIndex < [identifier.Length intValue])) {
if ([allowed Contains: [identifier GetRange: [NSNumber numberWithInt: charIndex] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
NSLog(@"%@",@"Invalid character in role_session_name.");
return;
}
charIndex = charIndex + 1;
}
if (([credentials HasMember: @"mfa_code"] == YES) || ([credentials HasMember: @"mfa_serial"] == YES)) {
NSLog(@"%@",@"This unattended refresh example does not reuse MFA codes.");
return;
}
// Optional private cache contains only the four normalized session fields.
// In an application, keep activeSnapshot in memory between units of work.
CkoFileAccess *files = [[CkoFileAccess alloc] init];
CkoJsonObject *cached = [[CkoJsonObject alloc] init];
cached.Strict = YES;
NSString *activeSnapshot = @"";
BOOL refreshRequired = YES;
if ([files FileExists: @"qa_data/tokens/sts_session.json"] == YES) {
success = [cached LoadFile: @"qa_data/tokens/sts_session.json"];
if (success != YES) {
NSLog(@"%@",@"Invalid private cache.");
return;
}
[stringCompare SetString: [cached StringOf: @"access_key"]];
BOOL stringMatch7 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[cached JsonTypeOf: @"access_key"] intValue] != 1) || (stringMatch7 == YES)) {
NSLog(@"%@",@"Incomplete private cache.");
return;
}
[stringCompare SetString: [cached StringOf: @"secret_key"]];
BOOL stringMatch8 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[cached JsonTypeOf: @"secret_key"] intValue] != 1) || (stringMatch8 == YES)) {
NSLog(@"%@",@"Incomplete private cache.");
return;
}
[stringCompare SetString: [cached StringOf: @"session_token"]];
BOOL stringMatch9 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[cached JsonTypeOf: @"session_token"] intValue] != 1) || (stringMatch9 == YES)) {
NSLog(@"%@",@"Incomplete private cache.");
return;
}
[stringCompare SetString: [cached StringOf: @"expiration"]];
BOOL stringMatch10 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[cached JsonTypeOf: @"expiration"] intValue] != 1) || (stringMatch10 == YES)) {
NSLog(@"%@",@"Incomplete private cache.");
return;
}
success = [expires SetFromTimestamp: [cached StringOf: @"expiration"]];
if (success != YES) {
NSLog(@"%@",@"Invalid cached expiration.");
return;
}
success = [now SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read current time.");
return;
}
if ([[expires DiffSeconds: now] intValue] > 300) {
activeSnapshot = [cached Emit];
refreshRequired = NO;
}
}
if (refreshRequired == YES) {
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 *accessKey = 0;
NSString *secretKey = 0;
NSString *sessionToken = 0;
NSString *expiration = 0;
NSString *responseXml = @"";
int attempt = 0;
int delayMs = 1000;
BOOL received = NO;
BOOL retryable;
while (((attempt < 3) && (received == NO))) {
if ([credentials HasMember: @"session_token"] == YES) {
[stringCompare SetString: [credentials StringOf: @"session_token"]];
BOOL stringMatch11 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"session_token"] intValue] != 1) || (stringMatch11 == YES)) {
NSLog(@"%@",@"Missing or invalid session_token.");
return;
}
[stringCompare SetString: [credentials StringOf: @"expiration"]];
BOOL stringMatch12 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"expiration"] intValue] != 1) || (stringMatch12 == 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;
}
}
attempt = attempt + 1;
success = [rest ClearAllQueryParams];
if (success != YES) {
NSLog(@"%@",@"Could not reset request parameters.");
return;
}
success = [rest AddQueryParam: @"Action" value: @"AssumeRole"];
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: @"RoleArn" value: [credentials StringOf: @"role_arn"]];
if (success != YES) {
NSLog(@"%@",@"Could not set RoleArn.");
return;
}
success = [rest AddQueryParam: @"RoleSessionName" value: [credentials StringOf: @"role_session_name"]];
if (success != YES) {
NSLog(@"%@",@"Could not set RoleSessionName.");
return;
}
success = [rest AddQueryParam: @"DurationSeconds" value: @"3600"];
if (success != YES) {
NSLog(@"%@",@"Could not set DurationSeconds.");
return;
}
responseXml = [rest FullRequestFormUrlEncoded: @"POST" uriPath: @"/"];
if (rest.LastMethodSuccess != YES) {
NSLog(@"%@",@"Transport failed; credential refresh was not published.");
return;
}
if ([rest.ResponseStatusCode intValue] == 200) {
received = YES;
}
if ([rest.ResponseStatusCode intValue] != 200) {
retryable = NO;
value = @"";
success = [xml LoadXml: responseXml];
if (success == YES) {
value = [xml GetChildContent: @"Error|Code"];
}
[stringCompare SetString: value];
BOOL stringMatch13 = [stringCompare ContentsEqual: @"Throttling" caseSensitive: YES];
[stringCompare SetString: value];
BOOL stringMatch14 = [stringCompare ContentsEqual: @"ThrottlingException" caseSensitive: YES];
if (([rest.ResponseStatusCode intValue] == 429) || ([rest.ResponseStatusCode intValue] == 500) || ([rest.ResponseStatusCode intValue] == 502) || ([rest.ResponseStatusCode intValue] == 503) || ([rest.ResponseStatusCode intValue] == 504) || (stringMatch13 == YES) || (stringMatch14 == YES)) {
retryable = YES;
}
if ((retryable != YES) || (attempt == 3)) {
NSLog(@"%@%d",@"Refresh failed. HTTP status: ",[rest.ResponseStatusCode intValue]);
NSLog(@"%@%@",@"AWS error code: ",value);
return;
}
[connection SleepMs: [NSNumber numberWithInt: delayMs]];
delayMs = delayMs * 2;
}
}
if (received != YES) {
NSLog(@"%@",@"Refresh attempts exhausted.");
return;
}
success = [xml LoadXml: responseXml];
if (success != YES) {
NSLog(@"%@",@"Invalid STS XML response.");
return;
}
[stringCompare SetString: xml.Tag];
BOOL stringMatch15 = [stringCompare ContentsEqual: @"AssumeRoleResponse" caseSensitive: YES];
if (stringMatch15 != YES) {
NSLog(@"%@",@"Unexpected STS response root.");
return;
}
value = [xml GetChildContent: @"ResponseMetadata|RequestId"];
[stringCompare SetString: value];
BOOL stringMatch16 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch16 == YES)) {
NSLog(@"%@",@"Missing or empty ResponseMetadata|RequestId.");
return;
}
if ([xml HasChildWithTag: @"AssumeRoleResult"] != YES) {
NSLog(@"%@",@"Missing STS result.");
return;
}
accessKey = [xml GetChildContent: @"AssumeRoleResult|Credentials|AccessKeyId"];
[stringCompare SetString: accessKey];
BOOL stringMatch17 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch17 == YES)) {
NSLog(@"%@",@"Missing or empty AssumeRoleResult|Credentials|AccessKeyId.");
return;
}
secretKey = [xml GetChildContent: @"AssumeRoleResult|Credentials|SecretAccessKey"];
[stringCompare SetString: secretKey];
BOOL stringMatch18 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch18 == YES)) {
NSLog(@"%@",@"Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.");
return;
}
sessionToken = [xml GetChildContent: @"AssumeRoleResult|Credentials|SessionToken"];
[stringCompare SetString: sessionToken];
BOOL stringMatch19 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch19 == YES)) {
NSLog(@"%@",@"Missing or empty AssumeRoleResult|Credentials|SessionToken.");
return;
}
expiration = [xml GetChildContent: @"AssumeRoleResult|Credentials|Expiration"];
[stringCompare SetString: expiration];
BOOL stringMatch20 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch20 == YES)) {
NSLog(@"%@",@"Missing or empty AssumeRoleResult|Credentials|Expiration.");
return;
}
success = [expires SetFromTimestamp: expiration];
if (success != YES) {
NSLog(@"%@",@"Returned expiration is invalid.");
return;
}
success = [now SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read current time.");
return;
}
if ([[expires DiffSeconds: now] intValue] <= 60) {
NSLog(@"%@",@"Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.");
return;
}
value = [xml GetChildContent: @"AssumeRoleResult|AssumedRoleUser|Arn"];
[stringCompare SetString: value];
BOOL stringMatch21 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch21 == YES)) {
NSLog(@"%@",@"Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.");
return;
}
value = [xml GetChildContent: @"AssumeRoleResult|AssumedRoleUser|AssumedRoleId"];
[stringCompare SetString: value];
BOOL stringMatch22 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch22 == YES)) {
NSLog(@"%@",@"Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.");
return;
}
CkoJsonObject *session = [[CkoJsonObject alloc] init];
success = [session UpdateString: @"access_key" value: accessKey];
if (success != YES) {
NSLog(@"%@",@"Could not build complete session.");
return;
}
success = [session UpdateString: @"secret_key" value: secretKey];
if (success != YES) {
NSLog(@"%@",@"Could not build complete session.");
return;
}
success = [session UpdateString: @"session_token" value: sessionToken];
if (success != YES) {
NSLog(@"%@",@"Could not build complete session.");
return;
}
success = [session UpdateString: @"expiration" value: expiration];
if (success != YES) {
NSLog(@"%@",@"Could not build complete session.");
return;
}
// Use session in memory; do not print or log session.Emit().
NSLog(@"%@%@",@"Session validated; expiration: ",expiration);
// Publish one complete snapshot only after validating every returned field.
activeSnapshot = [session Emit];
}
// Rehydrate a complete set for the next unit of work, never four partial updates.
CkoJsonObject *usable = [[CkoJsonObject alloc] init];
usable.Strict = YES;
success = [usable Load: activeSnapshot];
if (success != YES) {
NSLog(@"%@",@"Could not load the complete session snapshot.");
return;
}
// Pass usable to your service client here. Do not log activeSnapshot.
NSLog(@"%@%@",@"Session ready for the next unit of work; expiration: ",[usable StringOf: @"expiration"]);
NSLog(@"%@",@"Example completed.");