AWS STS: Assume a Role for S3 Bucket Listing
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.
Set role_arn and role_session_name in the private configuration. Names must contain 2–64 allowed characters. The target trust policy and applicable caller authorization must permit AssumeRole. The sample's session policy permits only s3:ListAllMyBuckets, intersected with the role's permissions, for use by the companion S3 listing example; it cannot elevate the role's access. Other policy types, denies and resource-based rules still participate in authorization.
The fixed 3600-second request works within the one-hour role-chaining ceiling and must still fit the role's configured maximum. For temporary source credentials, also provide nonempty session_token and ISO 8601 expiration. The token is included in the signed form body. Optional external_id must be the value agreed with the role owner; it is not a password. Optional source_identity is subject to AWS syntax, trust conditions and sts:SetSourceIdentity permission. Optional MFA uses mfa_serial/mfa_code as a pair. These optional values must satisfy the actual trust policy.
This focused example omits managed session policies and session tags. When adding them, configure the required policies and tagging permissions, and account for inherited transitive tags during role chaining. STS session-token sizes are variable; preserve the complete value without a fixed buffer or truncation.
Chilkat PHP ActiveX Downloads
<?php
$success = 0;
$stringCompare = new COM("Chilkat.StringBuilder");
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this file private and outside public web content/source control.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/sts.json');
if ($success != 1) {
print 'Could not load private STS configuration.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('access_key'));
$stringMatch1 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('access_key') != 1) or ($stringMatch1 == 1)) {
print 'Missing or invalid access_key.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('secret_key'));
$stringMatch2 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('secret_key') != 1) or ($stringMatch2 == 1)) {
print 'Missing or invalid secret_key.' . "\n";
exit;
}
$expires = new COM("Chilkat.CkDateTime");
$now = new COM("Chilkat.CkDateTime");
$region = 'us-west-2';
if ($credentials->HasMember('session_token') == 1) {
$stringCompare->SetString($credentials->stringOf('session_token'));
$stringMatch3 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('session_token') != 1) or ($stringMatch3 == 1)) {
print 'Missing or invalid session_token.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('expiration'));
$stringMatch4 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('expiration') != 1) or ($stringMatch4 == 1)) {
print 'Missing or invalid expiration.' . "\n";
exit;
}
$success = $expires->SetFromTimestamp($credentials->stringOf('expiration'));
if ($success != 1) {
print 'Source expiration is invalid.' . "\n";
exit;
}
$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
print 'Could not read current time.' . "\n";
exit;
}
if ($expires->DiffSeconds($now) <= 60) {
print 'Source credentials are expired or expire within 60 seconds; obtain fresh credentials.' . "\n";
exit;
}
}
$stringCompare->SetString($credentials->stringOf('role_arn'));
$stringMatch5 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('role_arn') != 1) or ($stringMatch5 == 1)) {
print 'Missing or invalid role_arn.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('role_session_name'));
$stringMatch6 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('role_session_name') != 1) or ($stringMatch6 == 1)) {
print 'Missing or invalid role_session_name.' . "\n";
exit;
}
$identifier = new COM("Chilkat.StringBuilder");
$identifier->Append($credentials->stringOf('role_session_name'));
if (($identifier->Length < 2) or ($identifier->Length > 64)) {
print 'role_session_name must have 2-64 characters.' . "\n";
exit;
}
$allowed = new COM("Chilkat.StringBuilder");
$allowed->Append('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-');
$charIndex = 0;
while (($charIndex < $identifier->Length)) {
if ($allowed->Contains($identifier->getRange($charIndex,1,0),1) != 1) {
print 'Invalid character in role_session_name.' . "\n";
exit;
}
$charIndex = $charIndex + 1;
}
$roleArn = new COM("Chilkat.StringBuilder");
$roleArn->Append($credentials->stringOf('role_arn'));
if (($roleArn->StartsWith('arn:aws:iam::',1) != 1) or ($roleArn->Contains(':role/',1) != 1)) {
print 'Use an IAM role ARN in the commercial AWS partition.' . "\n";
exit;
}
if ($credentials->HasMember('external_id') == 1) {
$stringCompare->SetString($credentials->stringOf('external_id'));
$stringMatch7 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('external_id') != 1) or ($stringMatch7 == 1)) {
print 'Missing or invalid external_id.' . "\n";
exit;
}
}
if ($credentials->HasMember('source_identity') == 1) {
$stringCompare->SetString($credentials->stringOf('source_identity'));
$stringMatch8 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('source_identity') != 1) or ($stringMatch8 == 1)) {
print 'Missing or invalid source_identity.' . "\n";
exit;
}
}
// MFA fields are optional as a pair. Preserve a leading zero in the code.
if (($credentials->HasMember('mfa_serial') == 1) or ($credentials->HasMember('mfa_code') == 1)) {
$stringCompare->SetString($credentials->stringOf('mfa_serial'));
$stringMatch9 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('mfa_serial') != 1) or ($stringMatch9 == 1)) {
print 'Missing or invalid mfa_serial.' . "\n";
exit;
}
$stringCompare->SetString($credentials->stringOf('mfa_code'));
$stringMatch10 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('mfa_code') != 1) or ($stringMatch10 == 1)) {
print 'Missing or invalid mfa_code.' . "\n";
exit;
}
$mfaCode = new COM("Chilkat.StringBuilder");
$mfaCode->Append($credentials->stringOf('mfa_code'));
if ($mfaCode->Length != 6) {
print 'mfa_code must be a six-digit string.' . "\n";
exit;
}
$digits = new COM("Chilkat.StringBuilder");
$digits->Append('0123456789');
$digitIndex = 0;
while (($digitIndex < 6)) {
if ($digits->Contains($mfaCode->getRange($digitIndex,1,0),1) != 1) {
print 'mfa_code must contain only ASCII digits.' . "\n";
exit;
}
$digitIndex = $digitIndex + 1;
}
}
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('sts.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$aws = new COM("Chilkat.AuthAws");
$aws->AccessKey = $credentials->stringOf('access_key');
$aws->SecretKey = $credentials->stringOf('secret_key');
$aws->Region = $region;
$aws->ServiceName = 'sts';
$aws->SignatureVersion = 4;
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$rest->VerboseLogging = 0;
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
print 'Could not configure request signing.' . "\n";
exit;
}
// Keep this verified Socket alive while Rest uses its connection.
$connection = new COM("Chilkat.Socket");
$connection->RequireSslCertVerify = 1;
$connection->MaxReadIdleMs = 60000;
$connection->MaxSendIdleMs = 60000;
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
print 'TLS connection failed; inspect diagnostics privately.' . "\n";
exit;
}
$success = $rest->UseConnection($connection,1);
if ($success != 1) {
print 'Could not attach TLS connection.' . "\n";
exit;
}
$xml = new COM("Chilkat.Xml");
$xml->Strict = 1;
$success = $rest->ClearAllQueryParams();
if ($success != 1) {
print 'Could not clear request parameters.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Action','AssumeRole');
if ($success != 1) {
print 'Could not set Action.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Version','2011-06-15');
if ($success != 1) {
print 'Could not set Version.' . "\n";
exit;
}
$success = $rest->AddQueryParam('DurationSeconds','3600');
if ($success != 1) {
print 'Could not set DurationSeconds.' . "\n";
exit;
}
if ($credentials->HasMember('session_token') == 1) {
$success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
if ($success != 1) {
print 'Could not set X-Amz-Security-Token.' . "\n";
exit;
}
}
$success = $rest->AddQueryParam('RoleArn',$credentials->stringOf('role_arn'));
if ($success != 1) {
print 'Could not set RoleArn.' . "\n";
exit;
}
$success = $rest->AddQueryParam('RoleSessionName',$credentials->stringOf('role_session_name'));
if ($success != 1) {
print 'Could not set RoleSessionName.' . "\n";
exit;
}
// A session policy only restricts the role; it cannot add permissions.
$policy = new COM("Chilkat.JsonObject");
$success = $policy->UpdateString('Version','2012-10-17');
if ($success != 1) {
print 'Could not set policy version.' . "\n";
exit;
}
$success = $policy->UpdateString('Statement[0].Effect','Allow');
if ($success != 1) {
print 'Could not set policy effect.' . "\n";
exit;
}
$success = $policy->UpdateString('Statement[0].Action','s3:ListAllMyBuckets');
if ($success != 1) {
print 'Could not set policy action.' . "\n";
exit;
}
$success = $policy->UpdateString('Statement[0].Resource','*');
if ($success != 1) {
print 'Could not set policy resource.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Policy',$policy->emit());
if ($success != 1) {
print 'Could not set Policy.' . "\n";
exit;
}
if ($credentials->HasMember('external_id') == 1) {
$success = $rest->AddQueryParam('ExternalId',$credentials->stringOf('external_id'));
if ($success != 1) {
print 'Could not set ExternalId.' . "\n";
exit;
}
}
if ($credentials->HasMember('source_identity') == 1) {
$success = $rest->AddQueryParam('SourceIdentity',$credentials->stringOf('source_identity'));
if ($success != 1) {
print 'Could not set SourceIdentity.' . "\n";
exit;
}
}
if ($credentials->HasMember('mfa_serial') == 1) {
$success = $rest->AddQueryParam('SerialNumber',$credentials->stringOf('mfa_serial'));
if ($success != 1) {
print 'Could not set SerialNumber.' . "\n";
exit;
}
$success = $rest->AddQueryParam('TokenCode',$credentials->stringOf('mfa_code'));
if ($success != 1) {
print 'Could not set TokenCode.' . "\n";
exit;
}
}
$responseXml = $rest->fullRequestFormUrlEncoded('POST','/');
if ($rest->LastMethodSuccess != 1) {
print 'STS request did not complete; no credentials were saved. Inspect diagnostics privately.' . "\n";
exit;
}
$success = $xml->LoadXml($responseXml);
if ($rest->ResponseStatusCode != 200) {
print 'STS HTTP status: ' . $rest->ResponseStatusCode . "\n";
if ($success == 1) {
$value = $xml->getChildContent('Error|Code');
if ($xml->LastMethodSuccess == 1) {
print 'AWS error code: ' . $value . "\n";
}
$value = $xml->getChildContent('RequestId');
if ($xml->LastMethodSuccess == 1) {
print 'AWS request ID: ' . $value . "\n";
}
}
// Full bodies, headers, and diagnostics can contain sensitive data.
exit;
}
if ($success != 1) {
print 'Invalid STS XML response; no credentials were saved.' . "\n";
exit;
}
$stringCompare->SetString($xml->Tag);
$stringMatch11 = $stringCompare->ContentsEqual('AssumeRoleResponse',1);
if ($stringMatch11 != 1) {
print 'Unexpected STS response root.' . "\n";
exit;
}
$value = $xml->getChildContent('ResponseMetadata|RequestId');
$stringCompare->SetString($value);
$stringMatch12 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch12 == 1)) {
print 'Missing or empty ResponseMetadata|RequestId.' . "\n";
exit;
}
print 'AWS request ID: ' . $value . "\n";
$accessKey = $xml->getChildContent('AssumeRoleResult|Credentials|AccessKeyId');
$stringCompare->SetString($accessKey);
$stringMatch13 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch13 == 1)) {
print 'Missing or empty AssumeRoleResult|Credentials|AccessKeyId.' . "\n";
exit;
}
$secretKey = $xml->getChildContent('AssumeRoleResult|Credentials|SecretAccessKey');
$stringCompare->SetString($secretKey);
$stringMatch14 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch14 == 1)) {
print 'Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.' . "\n";
exit;
}
$sessionToken = $xml->getChildContent('AssumeRoleResult|Credentials|SessionToken');
$stringCompare->SetString($sessionToken);
$stringMatch15 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch15 == 1)) {
print 'Missing or empty AssumeRoleResult|Credentials|SessionToken.' . "\n";
exit;
}
$expiration = $xml->getChildContent('AssumeRoleResult|Credentials|Expiration');
$stringCompare->SetString($expiration);
$stringMatch16 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch16 == 1)) {
print 'Missing or empty AssumeRoleResult|Credentials|Expiration.' . "\n";
exit;
}
$success = $expires->SetFromTimestamp($expiration);
if ($success != 1) {
print 'Returned expiration is invalid.' . "\n";
exit;
}
$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
print 'Could not read current time.' . "\n";
exit;
}
if ($expires->DiffSeconds($now) <= 60) {
print 'Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.' . "\n";
exit;
}
$value = $xml->getChildContent('AssumeRoleResult|AssumedRoleUser|Arn');
$stringCompare->SetString($value);
$stringMatch17 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch17 == 1)) {
print 'Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.' . "\n";
exit;
}
$value = $xml->getChildContent('AssumeRoleResult|AssumedRoleUser|AssumedRoleId');
$stringCompare->SetString($value);
$stringMatch18 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch18 == 1)) {
print 'Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.' . "\n";
exit;
}
// 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 != 1) {
print 'Could not save the private credential file; do not assume it was updated.' . "\n";
exit;
}
print 'Temporary credentials saved privately; expiration: ' . $expiration . "\n";
?>