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

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 Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkDateTimeW.h>
#include <CkFileAccessW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkXmlW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Keep this file private and outside public web content/source control.
    CkJsonObjectW credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile(L"qa_data/aws/sts.json");
    if (success != true) {
        wprintf(L"Could not load private STS configuration.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"access_key"));
    bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
        wprintf(L"Missing or invalid access_key.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"secret_key"));
    bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
        wprintf(L"Missing or invalid secret_key.\n");
        return;
    }

    CkDateTimeW expires;
    CkDateTimeW now;
    const wchar_t *region = L"us-west-2";
    if (credentials.HasMember(L"session_token") == true) {
        stringCompare.SetString(credentials.stringOf(L"session_token"));
        bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
        if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
            wprintf(L"Missing or invalid session_token.\n");
            return;
        }

        stringCompare.SetString(credentials.stringOf(L"expiration"));
        bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
        if ((credentials.JsonTypeOf(L"expiration") != 1) || (stringMatch4 == true)) {
            wprintf(L"Missing or invalid expiration.\n");
            return;
        }

        success = expires.SetFromTimestamp(credentials.stringOf(L"expiration"));
        if (success != true) {
            wprintf(L"Source expiration is invalid.\n");
            return;
        }

        success = now.SetFromCurrentSystemTime();
        if (success != true) {
            wprintf(L"Could not read current time.\n");
            return;
        }

        if (expires.DiffSeconds(now) <= 60) {
            wprintf(L"Source credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
            return;
        }

    }

    stringCompare.SetString(credentials.stringOf(L"role_arn"));
    bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"role_arn") != 1) || (stringMatch5 == true)) {
        wprintf(L"Missing or invalid role_arn.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"role_session_name"));
    bool stringMatch6 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"role_session_name") != 1) || (stringMatch6 == true)) {
        wprintf(L"Missing or invalid role_session_name.\n");
        return;
    }

    CkStringBuilderW identifier;
    identifier.Append(credentials.stringOf(L"role_session_name"));
    if ((identifier.get_Length() < 2) || (identifier.get_Length() > 64)) {
        wprintf(L"role_session_name must have 2-64 characters.\n");
        return;
    }

    CkStringBuilderW allowed;
    allowed.Append(L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-");
    int charIndex = 0;
    while ((charIndex < identifier.get_Length())) {
        if (allowed.Contains(identifier.getRange(charIndex,1,false),true) != true) {
            wprintf(L"Invalid character in role_session_name.\n");
            return;
        }

        charIndex = charIndex + 1;
    }

    if ((credentials.HasMember(L"mfa_code") == true) || (credentials.HasMember(L"mfa_serial") == true)) {
        wprintf(L"This unattended refresh example does not reuse MFA codes.\n");
        return;
    }

    //  Optional private cache contains only the four normalized session fields.
    //  In an application, keep activeSnapshot in memory between units of work.
    CkFileAccessW files;
    CkJsonObjectW cached;
    cached.put_Strict(true);
    const wchar_t *activeSnapshot = L"";
    bool refreshRequired = true;
    if (files.FileExists(L"qa_data/tokens/sts_session.json") == true) {
        success = cached.LoadFile(L"qa_data/tokens/sts_session.json");
        if (success != true) {
            wprintf(L"Invalid private cache.\n");
            return;
        }

        stringCompare.SetString(cached.stringOf(L"access_key"));
        bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
        if ((cached.JsonTypeOf(L"access_key") != 1) || (stringMatch7 == true)) {
            wprintf(L"Incomplete private cache.\n");
            return;
        }

        stringCompare.SetString(cached.stringOf(L"secret_key"));
        bool stringMatch8 = stringCompare.ContentsEqual(L"",true);
        if ((cached.JsonTypeOf(L"secret_key") != 1) || (stringMatch8 == true)) {
            wprintf(L"Incomplete private cache.\n");
            return;
        }

        stringCompare.SetString(cached.stringOf(L"session_token"));
        bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
        if ((cached.JsonTypeOf(L"session_token") != 1) || (stringMatch9 == true)) {
            wprintf(L"Incomplete private cache.\n");
            return;
        }

        stringCompare.SetString(cached.stringOf(L"expiration"));
        bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
        if ((cached.JsonTypeOf(L"expiration") != 1) || (stringMatch10 == true)) {
            wprintf(L"Incomplete private cache.\n");
            return;
        }

        success = expires.SetFromTimestamp(cached.stringOf(L"expiration"));
        if (success != true) {
            wprintf(L"Invalid cached expiration.\n");
            return;
        }

        success = now.SetFromCurrentSystemTime();
        if (success != true) {
            wprintf(L"Could not read current time.\n");
            return;
        }

        if (expires.DiffSeconds(now) > 300) {
            activeSnapshot = cached.emit();
            refreshRequired = false;
        }

    }

    if (refreshRequired == true) {
        CkStringBuilderW endpoint;
        endpoint.Append(L"sts.");
        endpoint.Append(region);
        endpoint.Append(L".amazonaws.com");
        CkAuthAwsW aws;
        aws.put_AccessKey(credentials.stringOf(L"access_key"));
        aws.put_SecretKey(credentials.stringOf(L"secret_key"));
        aws.put_Region(region);
        aws.put_ServiceName(L"sts");
        aws.put_SignatureVersion(4);
        CkRestW rest;
        rest.put_ConnectTimeoutMs(20000);
        rest.put_IdleTimeoutMs(60000);
        rest.put_VerboseLogging(false);
        success = rest.SetAuthAws(aws);
        if (success != true) {
            wprintf(L"Could not configure request signing.\n");
            return;
        }

        //  Keep this verified Socket alive while Rest uses its connection.
        CkSocketW connection;
        connection.put_RequireSslCertVerify(true);
        connection.put_MaxReadIdleMs(60000);
        connection.put_MaxSendIdleMs(60000);
        success = connection.Connect(endpoint.getAsString(),443,true,20000);
        if (success != true) {
            wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
            return;
        }

        success = rest.UseConnection(connection,true);
        if (success != true) {
            wprintf(L"Could not attach TLS connection.\n");
            return;
        }

        CkXmlW xml;
        xml.put_Strict(true);
        const wchar_t *value = 0;
        const wchar_t *accessKey = 0;
        const wchar_t *secretKey = 0;
        const wchar_t *sessionToken = 0;
        const wchar_t *expiration = 0;
        const wchar_t *responseXml = L"";
        int attempt = 0;
        int delayMs = 1000;
        bool received = false;
        bool retryable;
        while (((attempt < 3) && (received == false))) {
            if (credentials.HasMember(L"session_token") == true) {
                stringCompare.SetString(credentials.stringOf(L"session_token"));
                bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
                if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch11 == true)) {
                    wprintf(L"Missing or invalid session_token.\n");
                    return;
                }

                stringCompare.SetString(credentials.stringOf(L"expiration"));
                bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
                if ((credentials.JsonTypeOf(L"expiration") != 1) || (stringMatch12 == true)) {
                    wprintf(L"Missing or invalid expiration.\n");
                    return;
                }

                success = expires.SetFromTimestamp(credentials.stringOf(L"expiration"));
                if (success != true) {
                    wprintf(L"Source expiration is invalid.\n");
                    return;
                }

                success = now.SetFromCurrentSystemTime();
                if (success != true) {
                    wprintf(L"Could not read current time.\n");
                    return;
                }

                if (expires.DiffSeconds(now) <= 60) {
                    wprintf(L"Source credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
                    return;
                }

            }

            attempt = attempt + 1;
            success = rest.ClearAllQueryParams();
            if (success != true) {
                wprintf(L"Could not reset request parameters.\n");
                return;
            }

            success = rest.AddQueryParam(L"Action",L"AssumeRole");
            if (success != true) {
                wprintf(L"Could not set Action.\n");
                return;
            }

            success = rest.AddQueryParam(L"Version",L"2011-06-15");
            if (success != true) {
                wprintf(L"Could not set Version.\n");
                return;
            }

            if (credentials.HasMember(L"session_token") == true) {
                success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
                if (success != true) {
                    wprintf(L"Could not set X-Amz-Security-Token.\n");
                    return;
                }

            }

            success = rest.AddQueryParam(L"RoleArn",credentials.stringOf(L"role_arn"));
            if (success != true) {
                wprintf(L"Could not set RoleArn.\n");
                return;
            }

            success = rest.AddQueryParam(L"RoleSessionName",credentials.stringOf(L"role_session_name"));
            if (success != true) {
                wprintf(L"Could not set RoleSessionName.\n");
                return;
            }

            success = rest.AddQueryParam(L"DurationSeconds",L"3600");
            if (success != true) {
                wprintf(L"Could not set DurationSeconds.\n");
                return;
            }

            responseXml = rest.fullRequestFormUrlEncoded(L"POST",L"/");
            if (rest.get_LastMethodSuccess() != true) {
                wprintf(L"Transport failed; credential refresh was not published.\n");
                return;
            }

            if (rest.get_ResponseStatusCode() == 200) {
                received = true;
            }

            if (rest.get_ResponseStatusCode() != 200) {
                retryable = false;
                value = L"";
                success = xml.LoadXml(responseXml);
                if (success == true) {
                    value = xml.getChildContent(L"Error|Code");
                }

                stringCompare.SetString(value);
                bool stringMatch13 = stringCompare.ContentsEqual(L"Throttling",true);
                stringCompare.SetString(value);
                bool stringMatch14 = stringCompare.ContentsEqual(L"ThrottlingException",true);
                if ((rest.get_ResponseStatusCode() == 429) || (rest.get_ResponseStatusCode() == 500) || (rest.get_ResponseStatusCode() == 502) || (rest.get_ResponseStatusCode() == 503) || (rest.get_ResponseStatusCode() == 504) || (stringMatch13 == true) || (stringMatch14 == true)) {
                    retryable = true;
                }

                if ((retryable != true) || (attempt == 3)) {
                    wprintf(L"Refresh failed. HTTP status: %d\n",rest.get_ResponseStatusCode());
                    wprintf(L"AWS error code: %s\n",value);
                    return;
                }

                connection.SleepMs(delayMs);
                delayMs = delayMs * 2;
            }

        }

        if (received != true) {
            wprintf(L"Refresh attempts exhausted.\n");
            return;
        }

        success = xml.LoadXml(responseXml);
        if (success != true) {
            wprintf(L"Invalid STS XML response.\n");
            return;
        }

        stringCompare.SetString(xml.tag());
        bool stringMatch15 = stringCompare.ContentsEqual(L"AssumeRoleResponse",true);
        if (stringMatch15 != true) {
            wprintf(L"Unexpected STS response root.\n");
            return;
        }

        value = xml.getChildContent(L"ResponseMetadata|RequestId");
        stringCompare.SetString(value);
        bool stringMatch16 = stringCompare.ContentsEqual(L"",true);
        if ((xml.get_LastMethodSuccess() != true) || (stringMatch16 == true)) {
            wprintf(L"Missing or empty ResponseMetadata|RequestId.\n");
            return;
        }

        if (xml.HasChildWithTag(L"AssumeRoleResult") != true) {
            wprintf(L"Missing STS result.\n");
            return;
        }

        accessKey = xml.getChildContent(L"AssumeRoleResult|Credentials|AccessKeyId");
        stringCompare.SetString(accessKey);
        bool stringMatch17 = stringCompare.ContentsEqual(L"",true);
        if ((xml.get_LastMethodSuccess() != true) || (stringMatch17 == true)) {
            wprintf(L"Missing or empty AssumeRoleResult|Credentials|AccessKeyId.\n");
            return;
        }

        secretKey = xml.getChildContent(L"AssumeRoleResult|Credentials|SecretAccessKey");
        stringCompare.SetString(secretKey);
        bool stringMatch18 = stringCompare.ContentsEqual(L"",true);
        if ((xml.get_LastMethodSuccess() != true) || (stringMatch18 == true)) {
            wprintf(L"Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.\n");
            return;
        }

        sessionToken = xml.getChildContent(L"AssumeRoleResult|Credentials|SessionToken");
        stringCompare.SetString(sessionToken);
        bool stringMatch19 = stringCompare.ContentsEqual(L"",true);
        if ((xml.get_LastMethodSuccess() != true) || (stringMatch19 == true)) {
            wprintf(L"Missing or empty AssumeRoleResult|Credentials|SessionToken.\n");
            return;
        }

        expiration = xml.getChildContent(L"AssumeRoleResult|Credentials|Expiration");
        stringCompare.SetString(expiration);
        bool stringMatch20 = stringCompare.ContentsEqual(L"",true);
        if ((xml.get_LastMethodSuccess() != true) || (stringMatch20 == true)) {
            wprintf(L"Missing or empty AssumeRoleResult|Credentials|Expiration.\n");
            return;
        }

        success = expires.SetFromTimestamp(expiration);
        if (success != true) {
            wprintf(L"Returned expiration is invalid.\n");
            return;
        }

        success = now.SetFromCurrentSystemTime();
        if (success != true) {
            wprintf(L"Could not read current time.\n");
            return;
        }

        if (expires.DiffSeconds(now) <= 60) {
            wprintf(L"Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.\n");
            return;
        }

        value = xml.getChildContent(L"AssumeRoleResult|AssumedRoleUser|Arn");
        stringCompare.SetString(value);
        bool stringMatch21 = stringCompare.ContentsEqual(L"",true);
        if ((xml.get_LastMethodSuccess() != true) || (stringMatch21 == true)) {
            wprintf(L"Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.\n");
            return;
        }

        value = xml.getChildContent(L"AssumeRoleResult|AssumedRoleUser|AssumedRoleId");
        stringCompare.SetString(value);
        bool stringMatch22 = stringCompare.ContentsEqual(L"",true);
        if ((xml.get_LastMethodSuccess() != true) || (stringMatch22 == true)) {
            wprintf(L"Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.\n");
            return;
        }

        CkJsonObjectW session;
        success = session.UpdateString(L"access_key",accessKey);
        if (success != true) {
            wprintf(L"Could not build complete session.\n");
            return;
        }

        success = session.UpdateString(L"secret_key",secretKey);
        if (success != true) {
            wprintf(L"Could not build complete session.\n");
            return;
        }

        success = session.UpdateString(L"session_token",sessionToken);
        if (success != true) {
            wprintf(L"Could not build complete session.\n");
            return;
        }

        success = session.UpdateString(L"expiration",expiration);
        if (success != true) {
            wprintf(L"Could not build complete session.\n");
            return;
        }

        //  Use session in memory; do not print or log session.Emit().
        wprintf(L"Session validated; expiration: %s\n",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.
    CkJsonObjectW usable;
    usable.put_Strict(true);
    success = usable.Load(activeSnapshot);
    if (success != true) {
        wprintf(L"Could not load the complete session snapshot.\n");
        return;
    }

    //  Pass usable to your service client here. Do not log activeSnapshot.
    wprintf(L"Session ready for the next unit of work; expiration: %s\n",usable.stringOf(L"expiration"));
    wprintf(L"Example completed.\n");
    }