Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.6.0+

AWS STS: Exchange a SAML Assertion for Role Credentials

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.

Provide role_arn, principal_arn for the IAM SAML provider, and saml_assertion containing the complete base64-encoded SAML response supplied by your IdP. Do not base64-encode it a second time. Uses unsigned POST with no AWS keys. The IdP metadata, role claims and trust must already be configured. STS verifies the assertion. The session can end sooner than the requested hour due to SessionNotOnOrAfter. IAM Identity Center AWSReservedSSO_ roles are not supported by this operation.

AWS references: AssumeRoleWithSAML

Chilkat Objective-C Downloads

Objective-C
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <CkoDateTime.h>
#import <NSString.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;
}

CkoDateTime *expires = [[CkoDateTime alloc] init];
CkoDateTime *now = [[CkoDateTime alloc] init];
NSString *region = @"us-west-2";
[stringCompare SetString: [credentials StringOf: @"role_arn"]];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"role_arn"] intValue] != 1) || (stringMatch1 == YES)) {
    NSLog(@"%@",@"Missing or invalid role_arn.");
    return;
}

[stringCompare SetString: [credentials StringOf: @"principal_arn"]];
BOOL stringMatch2 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"principal_arn"] intValue] != 1) || (stringMatch2 == YES)) {
    NSLog(@"%@",@"Missing or invalid principal_arn.");
    return;
}

[stringCompare SetString: [credentials StringOf: @"saml_assertion"]];
BOOL stringMatch3 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"saml_assertion"] intValue] != 1) || (stringMatch3 == YES)) {
    NSLog(@"%@",@"Missing or invalid saml_assertion.");
    return;
}

CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"sts."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
rest.VerboseLogging = NO;
//  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 = @"";
success = [rest ClearAllQueryParams];
if (success != YES) {
    NSLog(@"%@",@"Could not reset request parameters.");
    return;
}

success = [rest AddQueryParam: @"Action" value: @"AssumeRoleWithSAML"];
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: @"RoleArn" value: [credentials StringOf: @"role_arn"]];
if (success != YES) {
    NSLog(@"%@",@"Could not set RoleArn.");
    return;
}

success = [rest AddQueryParam: @"PrincipalArn" value: [credentials StringOf: @"principal_arn"]];
if (success != YES) {
    NSLog(@"%@",@"Could not set PrincipalArn.");
    return;
}

success = [rest AddQueryParam: @"SAMLAssertion" value: [credentials StringOf: @"saml_assertion"]];
if (success != YES) {
    NSLog(@"%@",@"Could not set SAMLAssertion.");
    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(@"%@",@"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 stringMatch4 = [stringCompare ContentsEqual: @"AssumeRoleWithSAMLResponse" caseSensitive: YES];
if (stringMatch4 != YES) {
    NSLog(@"%@",@"Unexpected STS response root.");
    return;
}

value = [xml GetChildContent: @"ResponseMetadata|RequestId"];
[stringCompare SetString: value];
BOOL stringMatch5 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch5 == YES)) {
    NSLog(@"%@",@"Missing or empty ResponseMetadata|RequestId.");
    return;
}

if ([xml HasChildWithTag: @"AssumeRoleWithSAMLResult"] != YES) {
    NSLog(@"%@",@"Missing STS result.");
    return;
}

accessKey = [xml GetChildContent: @"AssumeRoleWithSAMLResult|Credentials|AccessKeyId"];
[stringCompare SetString: accessKey];
BOOL stringMatch6 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch6 == YES)) {
    NSLog(@"%@",@"Missing or empty AssumeRoleWithSAMLResult|Credentials|AccessKeyId.");
    return;
}

secretKey = [xml GetChildContent: @"AssumeRoleWithSAMLResult|Credentials|SecretAccessKey"];
[stringCompare SetString: secretKey];
BOOL stringMatch7 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch7 == YES)) {
    NSLog(@"%@",@"Missing or empty AssumeRoleWithSAMLResult|Credentials|SecretAccessKey.");
    return;
}

sessionToken = [xml GetChildContent: @"AssumeRoleWithSAMLResult|Credentials|SessionToken"];
[stringCompare SetString: sessionToken];
BOOL stringMatch8 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch8 == YES)) {
    NSLog(@"%@",@"Missing or empty AssumeRoleWithSAMLResult|Credentials|SessionToken.");
    return;
}

expiration = [xml GetChildContent: @"AssumeRoleWithSAMLResult|Credentials|Expiration"];
[stringCompare SetString: expiration];
BOOL stringMatch9 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch9 == YES)) {
    NSLog(@"%@",@"Missing or empty AssumeRoleWithSAMLResult|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: @"AssumeRoleWithSAMLResult|AssumedRoleUser|Arn"];
[stringCompare SetString: value];
BOOL stringMatch10 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch10 == YES)) {
    NSLog(@"%@",@"Missing or empty AssumeRoleWithSAMLResult|AssumedRoleUser|Arn.");
    return;
}

value = [xml GetChildContent: @"AssumeRoleWithSAMLResult|AssumedRoleUser|AssumedRoleId"];
[stringCompare SetString: value];
BOOL stringMatch11 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch11 == YES)) {
    NSLog(@"%@",@"Missing or empty AssumeRoleWithSAMLResult|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);
NSLog(@"%@",@"Example completed.");