Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

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.

AWS API reference

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
credentials: HCkJsonObject;
stringMatch1: Boolean;
stringMatch2: Boolean;
expires: HCkDateTime;
now: HCkDateTime;
region: PWideChar;
stringMatch3: Boolean;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: Boolean;
identifier: HCkStringBuilder;
allowed: HCkStringBuilder;
charIndex: Integer;
roleArn: HCkStringBuilder;
stringMatch7: Boolean;
stringMatch8: Boolean;
stringMatch9: Boolean;
stringMatch10: Boolean;
mfaCode: HCkStringBuilder;
digits: HCkStringBuilder;
digitIndex: Integer;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
value: PWideChar;
accessKey: PWideChar;
secretKey: PWideChar;
sessionToken: PWideChar;
expiration: PWideChar;
policy: HCkJsonObject;
responseXml: PWideChar;
stringMatch11: Boolean;
stringMatch12: Boolean;
stringMatch13: Boolean;
stringMatch14: Boolean;
stringMatch15: Boolean;
stringMatch16: Boolean;
stringMatch17: Boolean;
stringMatch18: Boolean;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Keep this file private and outside public web content/source control.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/sts.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private STS configuration.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'access_key'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (stringMatch1 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'secret_key'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (stringMatch2 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
expires := CkDateTime_Create();
now := CkDateTime_Create();
region := 'us-west-2';
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'session_token'));
    stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) or (stringMatch3 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid session_token.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'expiration'));
    stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'expiration') <> 1) or (stringMatch4 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid expiration.');
        Exit;
      end;
    success := CkDateTime_SetFromTimestamp(expires,CkJsonObject__stringOf(credentials,'expiration'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Source expiration is invalid.');
        Exit;
      end;
    success := CkDateTime_SetFromCurrentSystemTime(now);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not read current time.');
        Exit;
      end;
    if (CkDateTime_DiffSeconds(expires,now) <= 60) then
      begin
        Memo1.Lines.Add('Source credentials are expired or expire within 60 seconds; obtain fresh credentials.');
        Exit;
      end;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'role_arn'));
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'role_arn') <> 1) or (stringMatch5 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid role_arn.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'role_session_name'));
stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'role_session_name') <> 1) or (stringMatch6 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid role_session_name.');
    Exit;
  end;
identifier := CkStringBuilder_Create();
CkStringBuilder_Append(identifier,CkJsonObject__stringOf(credentials,'role_session_name'));
if ((CkStringBuilder_getLength(identifier) < 2) or (CkStringBuilder_getLength(identifier) > 64)) then
  begin
    Memo1.Lines.Add('role_session_name must have 2-64 characters.');
    Exit;
  end;
allowed := CkStringBuilder_Create();
CkStringBuilder_Append(allowed,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-');
charIndex := 0;
while (charIndex < CkStringBuilder_getLength(identifier)) do
  begin
    if (CkStringBuilder_Contains(allowed,CkStringBuilder__getRange(identifier,charIndex,1,False),True) <> True) then
      begin
        Memo1.Lines.Add('Invalid character in role_session_name.');
        Exit;
      end;
    charIndex := charIndex + 1;
  end;

roleArn := CkStringBuilder_Create();
CkStringBuilder_Append(roleArn,CkJsonObject__stringOf(credentials,'role_arn'));
if ((CkStringBuilder_StartsWith(roleArn,'arn:aws:iam::',True) <> True) or (CkStringBuilder_Contains(roleArn,':role/',True) <> True)) then
  begin
    Memo1.Lines.Add('Use an IAM role ARN in the commercial AWS partition.');
    Exit;
  end;
if (CkJsonObject_HasMember(credentials,'external_id') = True) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'external_id'));
    stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'external_id') <> 1) or (stringMatch7 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid external_id.');
        Exit;
      end;
  end;
if (CkJsonObject_HasMember(credentials,'source_identity') = True) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'source_identity'));
    stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'source_identity') <> 1) or (stringMatch8 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid source_identity.');
        Exit;
      end;
  end;
//  MFA fields are optional as a pair. Preserve a leading zero in the code.
if ((CkJsonObject_HasMember(credentials,'mfa_serial') = True) or (CkJsonObject_HasMember(credentials,'mfa_code') = True)) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'mfa_serial'));
    stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'mfa_serial') <> 1) or (stringMatch9 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid mfa_serial.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'mfa_code'));
    stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'mfa_code') <> 1) or (stringMatch10 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid mfa_code.');
        Exit;
      end;
    mfaCode := CkStringBuilder_Create();
    CkStringBuilder_Append(mfaCode,CkJsonObject__stringOf(credentials,'mfa_code'));
    if (CkStringBuilder_getLength(mfaCode) <> 6) then
      begin
        Memo1.Lines.Add('mfa_code must be a six-digit string.');
        Exit;
      end;
    digits := CkStringBuilder_Create();
    CkStringBuilder_Append(digits,'0123456789');
    digitIndex := 0;
    while (digitIndex < 6) do
      begin
        if (CkStringBuilder_Contains(digits,CkStringBuilder__getRange(mfaCode,digitIndex,1,False),True) <> True) then
          begin
            Memo1.Lines.Add('mfa_code must contain only ASCII digits.');
            Exit;
          end;
        digitIndex := digitIndex + 1;
      end;

  end;
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'sts.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'sts');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
CkRest_putVerboseLogging(rest,False);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure request signing.');
    Exit;
  end;
//  Keep this verified Socket alive while Rest uses its connection.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach TLS connection.');
    Exit;
  end;
xml := CkXml_Create();
CkXml_putStrict(xml,True);

success := CkRest_ClearAllQueryParams(rest);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not clear request parameters.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Action','AssumeRole');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Action.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Version','2011-06-15');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Version.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'DurationSeconds','3600');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set DurationSeconds.');
    Exit;
  end;
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set X-Amz-Security-Token.');
        Exit;
      end;
  end;
success := CkRest_AddQueryParam(rest,'RoleArn',CkJsonObject__stringOf(credentials,'role_arn'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set RoleArn.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'RoleSessionName',CkJsonObject__stringOf(credentials,'role_session_name'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set RoleSessionName.');
    Exit;
  end;
//  A session policy only restricts the role; it cannot add permissions.
policy := CkJsonObject_Create();
success := CkJsonObject_UpdateString(policy,'Version','2012-10-17');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set policy version.');
    Exit;
  end;
success := CkJsonObject_UpdateString(policy,'Statement[0].Effect','Allow');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set policy effect.');
    Exit;
  end;
success := CkJsonObject_UpdateString(policy,'Statement[0].Action','s3:ListAllMyBuckets');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set policy action.');
    Exit;
  end;
success := CkJsonObject_UpdateString(policy,'Statement[0].Resource','*');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set policy resource.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Policy',CkJsonObject__emit(policy));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Policy.');
    Exit;
  end;
if (CkJsonObject_HasMember(credentials,'external_id') = True) then
  begin
    success := CkRest_AddQueryParam(rest,'ExternalId',CkJsonObject__stringOf(credentials,'external_id'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set ExternalId.');
        Exit;
      end;
  end;
if (CkJsonObject_HasMember(credentials,'source_identity') = True) then
  begin
    success := CkRest_AddQueryParam(rest,'SourceIdentity',CkJsonObject__stringOf(credentials,'source_identity'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set SourceIdentity.');
        Exit;
      end;
  end;
if (CkJsonObject_HasMember(credentials,'mfa_serial') = True) then
  begin
    success := CkRest_AddQueryParam(rest,'SerialNumber',CkJsonObject__stringOf(credentials,'mfa_serial'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set SerialNumber.');
        Exit;
      end;
    success := CkRest_AddQueryParam(rest,'TokenCode',CkJsonObject__stringOf(credentials,'mfa_code'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set TokenCode.');
        Exit;
      end;
  end;
responseXml := CkRest__fullRequestFormUrlEncoded(rest,'POST','/');
if (CkRest_getLastMethodSuccess(rest) <> True) then
  begin
    Memo1.Lines.Add('STS request did not complete; no credentials were saved. Inspect diagnostics privately.');
    Exit;
  end;
success := CkXml_LoadXml(xml,responseXml);
if (CkRest_getResponseStatusCode(rest) <> 200) then
  begin
    Memo1.Lines.Add('STS HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
    if (success = True) then
      begin
        value := CkXml__getChildContent(xml,'Error|Code');
        if (CkXml_getLastMethodSuccess(xml) = True) then
          begin
            Memo1.Lines.Add('AWS error code: ' + value);
          end;
        value := CkXml__getChildContent(xml,'RequestId');
        if (CkXml_getLastMethodSuccess(xml) = True) then
          begin
            Memo1.Lines.Add('AWS request ID: ' + value);
          end;
      end;
    //  Full bodies, headers, and diagnostics can contain sensitive data.
    Exit;
  end;
if (success <> True) then
  begin
    Memo1.Lines.Add('Invalid STS XML response; no credentials were saved.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(xml));
stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,'AssumeRoleResponse',True);
if (stringMatch11 <> True) then
  begin
    Memo1.Lines.Add('Unexpected STS response root.');
    Exit;
  end;
value := CkXml__getChildContent(xml,'ResponseMetadata|RequestId');
CkStringBuilder_SetString(stringCompare,value);
stringMatch12 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch12 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
Memo1.Lines.Add('AWS request ID: ' + value);
accessKey := CkXml__getChildContent(xml,'AssumeRoleResult|Credentials|AccessKeyId');
CkStringBuilder_SetString(stringCompare,accessKey);
stringMatch13 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch13 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleResult|Credentials|AccessKeyId.');
    Exit;
  end;
secretKey := CkXml__getChildContent(xml,'AssumeRoleResult|Credentials|SecretAccessKey');
CkStringBuilder_SetString(stringCompare,secretKey);
stringMatch14 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch14 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.');
    Exit;
  end;
sessionToken := CkXml__getChildContent(xml,'AssumeRoleResult|Credentials|SessionToken');
CkStringBuilder_SetString(stringCompare,sessionToken);
stringMatch15 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch15 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleResult|Credentials|SessionToken.');
    Exit;
  end;
expiration := CkXml__getChildContent(xml,'AssumeRoleResult|Credentials|Expiration');
CkStringBuilder_SetString(stringCompare,expiration);
stringMatch16 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch16 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleResult|Credentials|Expiration.');
    Exit;
  end;
success := CkDateTime_SetFromTimestamp(expires,expiration);
if (success <> True) then
  begin
    Memo1.Lines.Add('Returned expiration is invalid.');
    Exit;
  end;
success := CkDateTime_SetFromCurrentSystemTime(now);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read current time.');
    Exit;
  end;
if (CkDateTime_DiffSeconds(expires,now) <= 60) then
  begin
    Memo1.Lines.Add('Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.');
    Exit;
  end;
value := CkXml__getChildContent(xml,'AssumeRoleResult|AssumedRoleUser|Arn');
CkStringBuilder_SetString(stringCompare,value);
stringMatch17 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch17 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.');
    Exit;
  end;
value := CkXml__getChildContent(xml,'AssumeRoleResult|AssumedRoleUser|AssumedRoleId');
CkStringBuilder_SetString(stringCompare,value);
stringMatch18 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch18 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.');
    Exit;
  end;
//  Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
//  Reuses the existing handoff filename for the companion S3 example.
success := CkXml_SaveXml(xml,'qa_data/tokens/aws_session_token.xml');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save the private credential file; do not assume it was updated.');
    Exit;
  end;
Memo1.Lines.Add('Temporary credentials saved privately; expiration: ' + expiration);

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkDateTime_Dispose(expires);
CkDateTime_Dispose(now);
CkStringBuilder_Dispose(identifier);
CkStringBuilder_Dispose(allowed);
CkStringBuilder_Dispose(roleArn);
    CkStringBuilder_Dispose(mfaCode);
    CkStringBuilder_Dispose(digits);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkJsonObject_Dispose(policy);