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

PHP
<?php

use Chilkat2\AuthAws;
use Chilkat2\DateTime;
use Chilkat2\FileAccess;
use Chilkat2\JsonObject;
use Chilkat2\Rest;
use Chilkat2\Socket;
use Chilkat2\StringBuilder;
use Chilkat2\Xml;

$success = false;

$stringCompare = new StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this file private and outside public web content/source control.
$credentials = new JsonObject();
$credentials->Strict = true;
try {
    $credentials->LoadFile('qa_data/aws/sts.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not load private STS configuration.\n";
    exit;
}

$stringCompare->SetString($credentials->StringOf('access_key'));
$stringMatch1 = $stringCompare->ContentsEqual('', true);
if (($credentials->JsonTypeOf('access_key') != 1) || ($stringMatch1)) {
    echo "Missing or invalid access_key.\n";
    exit;
}

$stringCompare->SetString($credentials->StringOf('secret_key'));
$stringMatch2 = $stringCompare->ContentsEqual('', true);
if (($credentials->JsonTypeOf('secret_key') != 1) || ($stringMatch2)) {
    echo "Missing or invalid secret_key.\n";
    exit;
}

$expires = new DateTime();
$now = new DateTime();
$region = 'us-west-2';
if ($credentials->HasMember('session_token')) {
    $stringCompare->SetString($credentials->StringOf('session_token'));
    $stringMatch3 = $stringCompare->ContentsEqual('', true);
    if (($credentials->JsonTypeOf('session_token') != 1) || ($stringMatch3)) {
        echo "Missing or invalid session_token.\n";
        exit;
    }

    $stringCompare->SetString($credentials->StringOf('expiration'));
    $stringMatch4 = $stringCompare->ContentsEqual('', true);
    if (($credentials->JsonTypeOf('expiration') != 1) || ($stringMatch4)) {
        echo "Missing or invalid expiration.\n";
        exit;
    }

    try {
        $expires->SetFromTimestamp($credentials->StringOf('expiration'));
    } catch (\Chilkat2\Exception $e) {
        echo "Source expiration is invalid.\n";
        exit;
    }

    try {
        $now->SetFromCurrentSystemTime();
    } catch (\Chilkat2\Exception $e) {
        echo "Could not read current time.\n";
        exit;
    }

    if ($expires->DiffSeconds($now) <= 60) {
        echo "Source credentials are expired or expire within 60 seconds; obtain fresh credentials.\n";
        exit;
    }
}

$stringCompare->SetString($credentials->StringOf('role_arn'));
$stringMatch5 = $stringCompare->ContentsEqual('', true);
if (($credentials->JsonTypeOf('role_arn') != 1) || ($stringMatch5)) {
    echo "Missing or invalid role_arn.\n";
    exit;
}

$stringCompare->SetString($credentials->StringOf('role_session_name'));
$stringMatch6 = $stringCompare->ContentsEqual('', true);
if (($credentials->JsonTypeOf('role_session_name') != 1) || ($stringMatch6)) {
    echo "Missing or invalid role_session_name.\n";
    exit;
}

$identifier = new StringBuilder();
$identifier->Append($credentials->StringOf('role_session_name'));
if (($identifier->Length < 2) || ($identifier->Length > 64)) {
    echo "role_session_name must have 2-64 characters.\n";
    exit;
}

$allowed = new StringBuilder();
$allowed->Append('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-');
$charIndex = 0;
while ($charIndex < $identifier->Length) {
    if (!$allowed->Contains($identifier->GetRange($charIndex, 1, false), true)) {
        echo "Invalid character in role_session_name.\n";
        exit;
    }

    $charIndex = $charIndex + 1;
}

if (($credentials->HasMember('mfa_code')) || ($credentials->HasMember('mfa_serial'))) {
    echo "This unattended refresh example does not reuse MFA codes.\n";
    exit;
}

// Optional private cache contains only the four normalized session fields.
// In an application, keep activeSnapshot in memory between units of work.
$files = new FileAccess();
$cached = new JsonObject();
$cached->Strict = true;
$activeSnapshot = '';
$refreshRequired = true;
if ($files->FileExists('qa_data/tokens/sts_session.json')) {
    try {
        $cached->LoadFile('qa_data/tokens/sts_session.json');
    } catch (\Chilkat2\Exception $e) {
        echo "Invalid private cache.\n";
        exit;
    }

    $stringCompare->SetString($cached->StringOf('access_key'));
    $stringMatch7 = $stringCompare->ContentsEqual('', true);
    if (($cached->JsonTypeOf('access_key') != 1) || ($stringMatch7)) {
        echo "Incomplete private cache.\n";
        exit;
    }

    $stringCompare->SetString($cached->StringOf('secret_key'));
    $stringMatch8 = $stringCompare->ContentsEqual('', true);
    if (($cached->JsonTypeOf('secret_key') != 1) || ($stringMatch8)) {
        echo "Incomplete private cache.\n";
        exit;
    }

    $stringCompare->SetString($cached->StringOf('session_token'));
    $stringMatch9 = $stringCompare->ContentsEqual('', true);
    if (($cached->JsonTypeOf('session_token') != 1) || ($stringMatch9)) {
        echo "Incomplete private cache.\n";
        exit;
    }

    $stringCompare->SetString($cached->StringOf('expiration'));
    $stringMatch10 = $stringCompare->ContentsEqual('', true);
    if (($cached->JsonTypeOf('expiration') != 1) || ($stringMatch10)) {
        echo "Incomplete private cache.\n";
        exit;
    }

    try {
        $expires->SetFromTimestamp($cached->StringOf('expiration'));
    } catch (\Chilkat2\Exception $e) {
        echo "Invalid cached expiration.\n";
        exit;
    }

    try {
        $now->SetFromCurrentSystemTime();
    } catch (\Chilkat2\Exception $e) {
        echo "Could not read current time.\n";
        exit;
    }

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

if ($refreshRequired) {
    $endpoint = new StringBuilder();
    $endpoint->Append('sts.');
    $endpoint->Append($region);
    $endpoint->Append('.amazonaws.com');
    $aws = new AuthAws();
    $aws->AccessKey = $credentials->StringOf('access_key');
    $aws->SecretKey = $credentials->StringOf('secret_key');
    $aws->Region = $region;
    $aws->ServiceName = 'sts';
    $aws->SignatureVersion = 4;
    $rest = new Rest();
    $rest->ConnectTimeoutMs = 20000;
    $rest->IdleTimeoutMs = 60000;
    $rest->VerboseLogging = false;
    try {
        $rest->SetAuthAws($aws);
    } catch (\Chilkat2\Exception $e) {
        echo "Could not configure request signing.\n";
        exit;
    }

    // Keep this verified Socket alive while Rest uses its connection.
    $connection = new Socket();
    $connection->RequireSslCertVerify = true;
    $connection->MaxReadIdleMs = 60000;
    $connection->MaxSendIdleMs = 60000;
    try {
        $connection->Connect($endpoint->GetAsString(), 443, true, 20000);
    } catch (\Chilkat2\Exception $e) {
        echo "TLS connection failed; inspect diagnostics privately.\n";
        exit;
    }

    try {
        $rest->UseConnection($connection, true);
    } catch (\Chilkat2\Exception $e) {
        echo "Could not attach TLS connection.\n";
        exit;
    }

    $xml = new Xml();
    $xml->Strict = true;
    $value = '';
    $responseXml = '';
    $attempt = 0;
    $delayMs = 1000;
    $received = false;
    $retryable = false;
    while (($attempt < 3) && (!$received)) {
        if ($credentials->HasMember('session_token')) {
            $stringCompare->SetString($credentials->StringOf('session_token'));
            $stringMatch11 = $stringCompare->ContentsEqual('', true);
            if (($credentials->JsonTypeOf('session_token') != 1) || ($stringMatch11)) {
                echo "Missing or invalid session_token.\n";
                exit;
            }

            $stringCompare->SetString($credentials->StringOf('expiration'));
            $stringMatch12 = $stringCompare->ContentsEqual('', true);
            if (($credentials->JsonTypeOf('expiration') != 1) || ($stringMatch12)) {
                echo "Missing or invalid expiration.\n";
                exit;
            }

            try {
                $expires->SetFromTimestamp($credentials->StringOf('expiration'));
            } catch (\Chilkat2\Exception $e) {
                echo "Source expiration is invalid.\n";
                exit;
            }

            try {
                $now->SetFromCurrentSystemTime();
            } catch (\Chilkat2\Exception $e) {
                echo "Could not read current time.\n";
                exit;
            }

            if ($expires->DiffSeconds($now) <= 60) {
                echo "Source credentials are expired or expire within 60 seconds; obtain fresh credentials.\n";
                exit;
            }
        }

        $attempt = $attempt + 1;
        try {
            $rest->ClearAllQueryParams();
        } catch (\Chilkat2\Exception $e) {
            echo "Could not reset request parameters.\n";
            exit;
        }

        try {
            $rest->AddQueryParam('Action', 'AssumeRole');
        } catch (\Chilkat2\Exception $e) {
            echo "Could not set Action.\n";
            exit;
        }

        try {
            $rest->AddQueryParam('Version', '2011-06-15');
        } catch (\Chilkat2\Exception $e) {
            echo "Could not set Version.\n";
            exit;
        }

        if ($credentials->HasMember('session_token')) {
            try {
                $rest->AddQueryParam('X-Amz-Security-Token', $credentials->StringOf('session_token'));
            } catch (\Chilkat2\Exception $e) {
                echo "Could not set X-Amz-Security-Token.\n";
                exit;
            }
        }

        try {
            $rest->AddQueryParam('RoleArn', $credentials->StringOf('role_arn'));
        } catch (\Chilkat2\Exception $e) {
            echo "Could not set RoleArn.\n";
            exit;
        }

        try {
            $rest->AddQueryParam('RoleSessionName', $credentials->StringOf('role_session_name'));
        } catch (\Chilkat2\Exception $e) {
            echo "Could not set RoleSessionName.\n";
            exit;
        }

        try {
            $rest->AddQueryParam('DurationSeconds', '3600');
        } catch (\Chilkat2\Exception $e) {
            echo "Could not set DurationSeconds.\n";
            exit;
        }

        try {
            $responseXml = $rest->FullRequestFormUrlEncoded('POST', '/');
        } catch (\Chilkat2\Exception $e) {
            echo "Transport failed; credential refresh was not published.\n";
            exit;
        }

        if ($rest->ResponseStatusCode == 200) {
            $received = true;
        }

        if ($rest->ResponseStatusCode != 200) {
            $retryable = false;
            $value = '';
            try {
                $xml->LoadXml($responseXml);
                $success = true;
            } catch (\Chilkat2\Exception $e) {
                $success = false;
            }
            if ($success) {
                $value = $xml->GetChildContent('Error|Code');
            }

            $stringCompare->SetString($value);
            $stringMatch13 = $stringCompare->ContentsEqual('Throttling', true);
            $stringCompare->SetString($value);
            $stringMatch14 = $stringCompare->ContentsEqual('ThrottlingException', true);
            if (($rest->ResponseStatusCode == 429) || (($rest->ResponseStatusCode == 500) || (($rest->ResponseStatusCode == 502) || (($rest->ResponseStatusCode == 503) || (($rest->ResponseStatusCode == 504) || (($stringMatch13) || ($stringMatch14))))))) {
                $retryable = true;
            }

            if ((!$retryable) || ($attempt == 3)) {
                echo 'Refresh failed. HTTP status: ', $rest->ResponseStatusCode, "\n";
                echo 'AWS error code: ', $value, "\n";
                exit;
            }

            $connection->SleepMs($delayMs);
            $delayMs = $delayMs * 2;
        }
    }

    if (!$received) {
        echo "Refresh attempts exhausted.\n";
        exit;
    }

    try {
        $xml->LoadXml($responseXml);
    } catch (\Chilkat2\Exception $e) {
        echo "Invalid STS XML response.\n";
        exit;
    }

    $stringCompare->SetString($xml->Tag);
    $stringMatch15 = $stringCompare->ContentsEqual('AssumeRoleResponse', true);
    if (!$stringMatch15) {
        echo "Unexpected STS response root.\n";
        exit;
    }

    $value = $xml->GetChildContent('ResponseMetadata|RequestId');
    $stringCompare->SetString($value);
    $stringMatch16 = $stringCompare->ContentsEqual('', true);
    if ((!$xml->LastMethodSuccess) || ($stringMatch16)) {
        echo "Missing or empty ResponseMetadata|RequestId.\n";
        exit;
    }

    if (!$xml->HasChildWithTag('AssumeRoleResult')) {
        echo "Missing STS result.\n";
        exit;
    }

    $accessKey = $xml->GetChildContent('AssumeRoleResult|Credentials|AccessKeyId');
    $stringCompare->SetString($accessKey);
    $stringMatch17 = $stringCompare->ContentsEqual('', true);
    if ((!$xml->LastMethodSuccess) || ($stringMatch17)) {
        echo "Missing or empty AssumeRoleResult|Credentials|AccessKeyId.\n";
        exit;
    }

    $secretKey = $xml->GetChildContent('AssumeRoleResult|Credentials|SecretAccessKey');
    $stringCompare->SetString($secretKey);
    $stringMatch18 = $stringCompare->ContentsEqual('', true);
    if ((!$xml->LastMethodSuccess) || ($stringMatch18)) {
        echo "Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.\n";
        exit;
    }

    $sessionToken = $xml->GetChildContent('AssumeRoleResult|Credentials|SessionToken');
    $stringCompare->SetString($sessionToken);
    $stringMatch19 = $stringCompare->ContentsEqual('', true);
    if ((!$xml->LastMethodSuccess) || ($stringMatch19)) {
        echo "Missing or empty AssumeRoleResult|Credentials|SessionToken.\n";
        exit;
    }

    $expiration = $xml->GetChildContent('AssumeRoleResult|Credentials|Expiration');
    $stringCompare->SetString($expiration);
    $stringMatch20 = $stringCompare->ContentsEqual('', true);
    if ((!$xml->LastMethodSuccess) || ($stringMatch20)) {
        echo "Missing or empty AssumeRoleResult|Credentials|Expiration.\n";
        exit;
    }

    try {
        $expires->SetFromTimestamp($expiration);
    } catch (\Chilkat2\Exception $e) {
        echo "Returned expiration is invalid.\n";
        exit;
    }

    try {
        $now->SetFromCurrentSystemTime();
    } catch (\Chilkat2\Exception $e) {
        echo "Could not read current time.\n";
        exit;
    }

    if ($expires->DiffSeconds($now) <= 60) {
        echo "Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.\n";
        exit;
    }

    $value = $xml->GetChildContent('AssumeRoleResult|AssumedRoleUser|Arn');
    $stringCompare->SetString($value);
    $stringMatch21 = $stringCompare->ContentsEqual('', true);
    if ((!$xml->LastMethodSuccess) || ($stringMatch21)) {
        echo "Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.\n";
        exit;
    }

    $value = $xml->GetChildContent('AssumeRoleResult|AssumedRoleUser|AssumedRoleId');
    $stringCompare->SetString($value);
    $stringMatch22 = $stringCompare->ContentsEqual('', true);
    if ((!$xml->LastMethodSuccess) || ($stringMatch22)) {
        echo "Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.\n";
        exit;
    }

    $session = new JsonObject();
    try {
        $session->UpdateString('access_key', $accessKey);

        $session->UpdateString('secret_key', $secretKey);

        $session->UpdateString('session_token', $sessionToken);

        $session->UpdateString('expiration', $expiration);
    } catch (\Chilkat2\Exception $e) {
        echo "Could not build complete session.\n";
        exit;
    }

    // Use session in memory; do not print or log session.Emit().
    echo 'Session validated; expiration: ', $expiration, "\n";
    // 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.
$usable = new JsonObject();
$usable->Strict = true;
try {
    $usable->Load($activeSnapshot);
} catch (\Chilkat2\Exception $e) {
    echo "Could not load the complete session snapshot.\n";
    exit;
}

// Pass usable to your service client here. Do not log activeSnapshot.
echo 'Session ready for the next unit of work; expiration: ', $usable->StringOf('expiration'), "\n";
echo "Example completed.\n";