AWS STS: GetSessionToken with Optional MFA
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.
Call with a long-term IAM user access key, not role/session credentials. This example rejects a supplied session_token and requests 3600 seconds. IAM user sessions allow 900–129600 seconds, default 43200. Do not use root credentials. Optional mfa_serial and mfa_code must be supplied together; the code is a six-digit string and can start with zero. Remove the short-lived MFA code from the private configuration after use; production applications should collect it at runtime.
GetSessionToken authenticates the IAM user and needs no permission grant for the GetSessionToken authentication operation. It does not assume a role or restrict the user's permissions via a session policy. The returned credentials inherit the user's permissions; IAM operations require MFA information, and the supported STS calls are limited to AssumeRole and GetCallerIdentity. For other workloads, prefer an appropriate role credential provider.
Chilkat Objective-C Downloads
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoDateTime.h>
#import <NSString.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) {
NSLog(@"%@",@"GetSessionToken requires long-term IAM user credentials, not an existing session token.");
return;
}
// MFA fields are optional as a pair. Preserve a leading zero in the code.
if (([credentials HasMember: @"mfa_serial"] == YES) || ([credentials HasMember: @"mfa_code"] == YES)) {
[stringCompare SetString: [credentials StringOf: @"mfa_serial"]];
BOOL stringMatch3 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"mfa_serial"] intValue] != 1) || (stringMatch3 == YES)) {
NSLog(@"%@",@"Missing or invalid mfa_serial.");
return;
}
[stringCompare SetString: [credentials StringOf: @"mfa_code"]];
BOOL stringMatch4 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"mfa_code"] intValue] != 1) || (stringMatch4 == YES)) {
NSLog(@"%@",@"Missing or invalid mfa_code.");
return;
}
CkoStringBuilder *mfaCode = [[CkoStringBuilder alloc] init];
[mfaCode Append: [credentials StringOf: @"mfa_code"]];
if ([mfaCode.Length intValue] != 6) {
NSLog(@"%@",@"mfa_code must be a six-digit string.");
return;
}
CkoStringBuilder *digits = [[CkoStringBuilder alloc] init];
[digits Append: @"0123456789"];
int digitIndex = 0;
while ((digitIndex < 6)) {
if ([digits Contains: [mfaCode GetRange: [NSNumber numberWithInt: digitIndex] numChars: [NSNumber numberWithInt: 1] removeFlag: NO] caseSensitive: YES] != YES) {
NSLog(@"%@",@"mfa_code must contain only ASCII digits.");
return;
}
digitIndex = digitIndex + 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 *accessKey = 0;
NSString *secretKey = 0;
NSString *sessionToken = 0;
NSString *expiration = 0;
success = [rest ClearAllQueryParams];
if (success != YES) {
NSLog(@"%@",@"Could not clear request parameters.");
return;
}
success = [rest AddQueryParam: @"Action" value: @"GetSessionToken"];
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;
}
success = [rest AddQueryParam: @"DurationSeconds" value: @"3600"];
if (success != YES) {
NSLog(@"%@",@"Could not set DurationSeconds.");
return;
}
if ([credentials HasMember: @"mfa_serial"] == YES) {
success = [rest AddQueryParam: @"SerialNumber" value: [credentials StringOf: @"mfa_serial"]];
if (success != YES) {
NSLog(@"%@",@"Could not set SerialNumber.");
return;
}
success = [rest AddQueryParam: @"TokenCode" value: [credentials StringOf: @"mfa_code"]];
if (success != YES) {
NSLog(@"%@",@"Could not set TokenCode.");
return;
}
}
NSString *responseXml = [rest FullRequestFormUrlEncoded: @"POST" uriPath: @"/"];
if (rest.LastMethodSuccess != YES) {
NSLog(@"%@",@"STS request did not complete; no credentials were saved. Inspect diagnostics privately.");
return;
}
success = [xml LoadXml: responseXml];
if ([rest.ResponseStatusCode intValue] != 200) {
NSLog(@"%@%d",@"STS HTTP status: ",[rest.ResponseStatusCode intValue]);
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);
}
}
// Full bodies, headers, and diagnostics can contain sensitive data.
return;
}
if (success != YES) {
NSLog(@"%@",@"Invalid STS XML response; no credentials were saved.");
return;
}
[stringCompare SetString: xml.Tag];
BOOL stringMatch5 = [stringCompare ContentsEqual: @"GetSessionTokenResponse" caseSensitive: YES];
if (stringMatch5 != YES) {
NSLog(@"%@",@"Unexpected STS response root.");
return;
}
value = [xml GetChildContent: @"ResponseMetadata|RequestId"];
[stringCompare SetString: value];
BOOL stringMatch6 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch6 == YES)) {
NSLog(@"%@",@"Missing or empty ResponseMetadata|RequestId.");
return;
}
NSLog(@"%@%@",@"AWS request ID: ",value);
accessKey = [xml GetChildContent: @"GetSessionTokenResult|Credentials|AccessKeyId"];
[stringCompare SetString: accessKey];
BOOL stringMatch7 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch7 == YES)) {
NSLog(@"%@",@"Missing or empty GetSessionTokenResult|Credentials|AccessKeyId.");
return;
}
secretKey = [xml GetChildContent: @"GetSessionTokenResult|Credentials|SecretAccessKey"];
[stringCompare SetString: secretKey];
BOOL stringMatch8 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch8 == YES)) {
NSLog(@"%@",@"Missing or empty GetSessionTokenResult|Credentials|SecretAccessKey.");
return;
}
sessionToken = [xml GetChildContent: @"GetSessionTokenResult|Credentials|SessionToken"];
[stringCompare SetString: sessionToken];
BOOL stringMatch9 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch9 == YES)) {
NSLog(@"%@",@"Missing or empty GetSessionTokenResult|Credentials|SessionToken.");
return;
}
expiration = [xml GetChildContent: @"GetSessionTokenResult|Credentials|Expiration"];
[stringCompare SetString: expiration];
BOOL stringMatch10 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch10 == YES)) {
NSLog(@"%@",@"Missing or empty GetSessionTokenResult|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;
}
// Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
// Reuses the existing handoff filename for the companion S3 example.
success = [xml SaveXml: @"qa_data/tokens/aws_session_token.xml"];
if (success != YES) {
NSLog(@"%@",@"Could not save the private credential file; do not assume it was updated.");
return;
}
NSLog(@"%@%@",@"Temporary credentials saved privately; expiration: ",expiration);