Sample code for 30+ languages & platforms
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 C# Downloads

C#
bool success = false;

Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Keep this file private and outside public web content/source control.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/sts.json");
if (success != true) {
    Debug.WriteLine("Could not load private STS configuration.");
    return;
}

stringCompare.SetString(credentials.StringOf("access_key"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
    Debug.WriteLine("Missing or invalid access_key.");
    return;
}

stringCompare.SetString(credentials.StringOf("secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
    Debug.WriteLine("Missing or invalid secret_key.");
    return;
}

Chilkat.CkDateTime expires = new Chilkat.CkDateTime();
Chilkat.CkDateTime now = new Chilkat.CkDateTime();
string region = "us-west-2";
if (credentials.HasMember("session_token") == true) {
    stringCompare.SetString(credentials.StringOf("session_token"));
    bool stringMatch3 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
        Debug.WriteLine("Missing or invalid session_token.");
        return;
    }

    stringCompare.SetString(credentials.StringOf("expiration"));
    bool stringMatch4 = stringCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("expiration") != 1) || (stringMatch4 == true)) {
        Debug.WriteLine("Missing or invalid expiration.");
        return;
    }

    success = expires.SetFromTimestamp(credentials.StringOf("expiration"));
    if (success != true) {
        Debug.WriteLine("Source expiration is invalid.");
        return;
    }

    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        Debug.WriteLine("Could not read current time.");
        return;
    }

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

}

stringCompare.SetString(credentials.StringOf("role_arn"));
bool stringMatch5 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("role_arn") != 1) || (stringMatch5 == true)) {
    Debug.WriteLine("Missing or invalid role_arn.");
    return;
}

stringCompare.SetString(credentials.StringOf("role_session_name"));
bool stringMatch6 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("role_session_name") != 1) || (stringMatch6 == true)) {
    Debug.WriteLine("Missing or invalid role_session_name.");
    return;
}

Chilkat.StringBuilder identifier = new Chilkat.StringBuilder();
identifier.Append(credentials.StringOf("role_session_name"));
if ((identifier.Length < 2) || (identifier.Length > 64)) {
    Debug.WriteLine("role_session_name must have 2-64 characters.");
    return;
}

Chilkat.StringBuilder allowed = new Chilkat.StringBuilder();
allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-");
int charIndex = 0;
while ((charIndex < identifier.Length)) {
    if (allowed.Contains(identifier.GetRange(charIndex,1,false),true) != true) {
        Debug.WriteLine("Invalid character in role_session_name.");
        return;
    }

    charIndex = charIndex + 1;
}

if ((credentials.HasMember("mfa_code") == true) || (credentials.HasMember("mfa_serial") == true)) {
    Debug.WriteLine("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.
Chilkat.FileAccess files = new Chilkat.FileAccess();
Chilkat.JsonObject cached = new Chilkat.JsonObject();
cached.Strict = true;
string activeSnapshot = "";
bool refreshRequired = true;
if (files.FileExists("qa_data/tokens/sts_session.json") == true) {
    success = cached.LoadFile("qa_data/tokens/sts_session.json");
    if (success != true) {
        Debug.WriteLine("Invalid private cache.");
        return;
    }

    stringCompare.SetString(cached.StringOf("access_key"));
    bool stringMatch7 = stringCompare.ContentsEqual("",true);
    if ((cached.JsonTypeOf("access_key") != 1) || (stringMatch7 == true)) {
        Debug.WriteLine("Incomplete private cache.");
        return;
    }

    stringCompare.SetString(cached.StringOf("secret_key"));
    bool stringMatch8 = stringCompare.ContentsEqual("",true);
    if ((cached.JsonTypeOf("secret_key") != 1) || (stringMatch8 == true)) {
        Debug.WriteLine("Incomplete private cache.");
        return;
    }

    stringCompare.SetString(cached.StringOf("session_token"));
    bool stringMatch9 = stringCompare.ContentsEqual("",true);
    if ((cached.JsonTypeOf("session_token") != 1) || (stringMatch9 == true)) {
        Debug.WriteLine("Incomplete private cache.");
        return;
    }

    stringCompare.SetString(cached.StringOf("expiration"));
    bool stringMatch10 = stringCompare.ContentsEqual("",true);
    if ((cached.JsonTypeOf("expiration") != 1) || (stringMatch10 == true)) {
        Debug.WriteLine("Incomplete private cache.");
        return;
    }

    success = expires.SetFromTimestamp(cached.StringOf("expiration"));
    if (success != true) {
        Debug.WriteLine("Invalid cached expiration.");
        return;
    }

    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        Debug.WriteLine("Could not read current time.");
        return;
    }

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

}

if (refreshRequired == true) {
    Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
    endpoint.Append("sts.");
    endpoint.Append(region);
    endpoint.Append(".amazonaws.com");
    Chilkat.AuthAws aws = new Chilkat.AuthAws();
    aws.AccessKey = credentials.StringOf("access_key");
    aws.SecretKey = credentials.StringOf("secret_key");
    aws.Region = region;
    aws.ServiceName = "sts";
    aws.SignatureVersion = 4;
    Chilkat.Rest rest = new Chilkat.Rest();
    rest.ConnectTimeoutMs = 20000;
    rest.IdleTimeoutMs = 60000;
    rest.VerboseLogging = false;
    success = rest.SetAuthAws(aws);
    if (success != true) {
        Debug.WriteLine("Could not configure request signing.");
        return;
    }

    //  Keep this verified Socket alive while Rest uses its connection.
    Chilkat.Socket connection = new Chilkat.Socket();
    connection.RequireSslCertVerify = true;
    connection.MaxReadIdleMs = 60000;
    connection.MaxSendIdleMs = 60000;
    success = connection.Connect(endpoint.GetAsString(),443,true,20000);
    if (success != true) {
        Debug.WriteLine("TLS connection failed; inspect diagnostics privately.");
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        Debug.WriteLine("Could not attach TLS connection.");
        return;
    }

    Chilkat.Xml xml = new Chilkat.Xml();
    xml.Strict = true;
    string value;
    string accessKey;
    string secretKey;
    string sessionToken;
    string expiration;
    string responseXml = "";
    int attempt = 0;
    int delayMs = 1000;
    bool received = false;
    bool retryable;
    while (((attempt < 3) && (received == false))) {
        if (credentials.HasMember("session_token") == true) {
            stringCompare.SetString(credentials.StringOf("session_token"));
            bool stringMatch11 = stringCompare.ContentsEqual("",true);
            if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch11 == true)) {
                Debug.WriteLine("Missing or invalid session_token.");
                return;
            }

            stringCompare.SetString(credentials.StringOf("expiration"));
            bool stringMatch12 = stringCompare.ContentsEqual("",true);
            if ((credentials.JsonTypeOf("expiration") != 1) || (stringMatch12 == true)) {
                Debug.WriteLine("Missing or invalid expiration.");
                return;
            }

            success = expires.SetFromTimestamp(credentials.StringOf("expiration"));
            if (success != true) {
                Debug.WriteLine("Source expiration is invalid.");
                return;
            }

            success = now.SetFromCurrentSystemTime();
            if (success != true) {
                Debug.WriteLine("Could not read current time.");
                return;
            }

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

        }

        attempt = attempt + 1;
        success = rest.ClearAllQueryParams();
        if (success != true) {
            Debug.WriteLine("Could not reset request parameters.");
            return;
        }

        success = rest.AddQueryParam("Action","AssumeRole");
        if (success != true) {
            Debug.WriteLine("Could not set Action.");
            return;
        }

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

        if (credentials.HasMember("session_token") == true) {
            success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"));
            if (success != true) {
                Debug.WriteLine("Could not set X-Amz-Security-Token.");
                return;
            }

        }

        success = rest.AddQueryParam("RoleArn",credentials.StringOf("role_arn"));
        if (success != true) {
            Debug.WriteLine("Could not set RoleArn.");
            return;
        }

        success = rest.AddQueryParam("RoleSessionName",credentials.StringOf("role_session_name"));
        if (success != true) {
            Debug.WriteLine("Could not set RoleSessionName.");
            return;
        }

        success = rest.AddQueryParam("DurationSeconds","3600");
        if (success != true) {
            Debug.WriteLine("Could not set DurationSeconds.");
            return;
        }

        responseXml = rest.FullRequestFormUrlEncoded("POST","/");
        if (rest.LastMethodSuccess != true) {
            Debug.WriteLine("Transport failed; credential refresh was not published.");
            return;
        }

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

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

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

            if ((retryable != true) || (attempt == 3)) {
                Debug.WriteLine("Refresh failed. HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
                Debug.WriteLine("AWS error code: " + value);
                return;
            }

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

    }

    if (received != true) {
        Debug.WriteLine("Refresh attempts exhausted.");
        return;
    }

    success = xml.LoadXml(responseXml);
    if (success != true) {
        Debug.WriteLine("Invalid STS XML response.");
        return;
    }

    stringCompare.SetString(xml.Tag);
    bool stringMatch15 = stringCompare.ContentsEqual("AssumeRoleResponse",true);
    if (stringMatch15 != true) {
        Debug.WriteLine("Unexpected STS response root.");
        return;
    }

    value = xml.GetChildContent("ResponseMetadata|RequestId");
    stringCompare.SetString(value);
    bool stringMatch16 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess != true) || (stringMatch16 == true)) {
        Debug.WriteLine("Missing or empty ResponseMetadata|RequestId.");
        return;
    }

    if (xml.HasChildWithTag("AssumeRoleResult") != true) {
        Debug.WriteLine("Missing STS result.");
        return;
    }

    accessKey = xml.GetChildContent("AssumeRoleResult|Credentials|AccessKeyId");
    stringCompare.SetString(accessKey);
    bool stringMatch17 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess != true) || (stringMatch17 == true)) {
        Debug.WriteLine("Missing or empty AssumeRoleResult|Credentials|AccessKeyId.");
        return;
    }

    secretKey = xml.GetChildContent("AssumeRoleResult|Credentials|SecretAccessKey");
    stringCompare.SetString(secretKey);
    bool stringMatch18 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess != true) || (stringMatch18 == true)) {
        Debug.WriteLine("Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.");
        return;
    }

    sessionToken = xml.GetChildContent("AssumeRoleResult|Credentials|SessionToken");
    stringCompare.SetString(sessionToken);
    bool stringMatch19 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess != true) || (stringMatch19 == true)) {
        Debug.WriteLine("Missing or empty AssumeRoleResult|Credentials|SessionToken.");
        return;
    }

    expiration = xml.GetChildContent("AssumeRoleResult|Credentials|Expiration");
    stringCompare.SetString(expiration);
    bool stringMatch20 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess != true) || (stringMatch20 == true)) {
        Debug.WriteLine("Missing or empty AssumeRoleResult|Credentials|Expiration.");
        return;
    }

    success = expires.SetFromTimestamp(expiration);
    if (success != true) {
        Debug.WriteLine("Returned expiration is invalid.");
        return;
    }

    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        Debug.WriteLine("Could not read current time.");
        return;
    }

    if (expires.DiffSeconds(now) <= 60) {
        Debug.WriteLine("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("",true);
    if ((xml.LastMethodSuccess != true) || (stringMatch21 == true)) {
        Debug.WriteLine("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.");
        return;
    }

    value = xml.GetChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId");
    stringCompare.SetString(value);
    bool stringMatch22 = stringCompare.ContentsEqual("",true);
    if ((xml.LastMethodSuccess != true) || (stringMatch22 == true)) {
        Debug.WriteLine("Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.");
        return;
    }

    Chilkat.JsonObject session = new Chilkat.JsonObject();
    success = session.UpdateString("access_key",accessKey);
    if (success != true) {
        Debug.WriteLine("Could not build complete session.");
        return;
    }

    success = session.UpdateString("secret_key",secretKey);
    if (success != true) {
        Debug.WriteLine("Could not build complete session.");
        return;
    }

    success = session.UpdateString("session_token",sessionToken);
    if (success != true) {
        Debug.WriteLine("Could not build complete session.");
        return;
    }

    success = session.UpdateString("expiration",expiration);
    if (success != true) {
        Debug.WriteLine("Could not build complete session.");
        return;
    }

    //  Use session in memory; do not print or log session.Emit().
    Debug.WriteLine("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.
Chilkat.JsonObject usable = new Chilkat.JsonObject();
usable.Strict = true;
success = usable.Load(activeSnapshot);
if (success != true) {
    Debug.WriteLine("Could not load the complete session snapshot.");
    return;
}

//  Pass usable to your service client here. Do not log activeSnapshot.
Debug.WriteLine("Session ready for the next unit of work; expiration: " + usable.StringOf("expiration"));
Debug.WriteLine("Example completed.");