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

Delphi ActiveX
var
success: Integer;
stringCompare: TChilkatStringBuilder;
credentials: TChilkatJsonObject;
stringMatch1: Integer;
stringMatch2: Integer;
expires: TCkDateTime;
now: TCkDateTime;
region: WideString;
stringMatch3: Integer;
stringMatch4: Integer;
stringMatch5: Integer;
stringMatch6: Integer;
identifier: TChilkatStringBuilder;
allowed: TChilkatStringBuilder;
charIndex: Integer;
files: TCkFileAccess;
cached: TChilkatJsonObject;
activeSnapshot: WideString;
refreshRequired: Integer;
stringMatch7: Integer;
stringMatch8: Integer;
stringMatch9: Integer;
stringMatch10: Integer;
endpoint: TChilkatStringBuilder;
aws: TChilkatAuthAws;
rest: TChilkatRest;
connection: TChilkatSocket;
xml: TChilkatXml;
value: WideString;
accessKey: WideString;
secretKey: WideString;
sessionToken: WideString;
expiration: WideString;
responseXml: WideString;
attempt: Integer;
delayMs: Integer;
received: Integer;
retryable: Integer;
stringMatch11: Integer;
stringMatch12: Integer;
stringMatch13: Integer;
stringMatch14: Integer;
stringMatch15: Integer;
stringMatch16: Integer;
stringMatch17: Integer;
stringMatch18: Integer;
stringMatch19: Integer;
stringMatch20: Integer;
stringMatch21: Integer;
stringMatch22: Integer;
session: TChilkatJsonObject;
usable: TChilkatJsonObject;

begin
success := 0;

stringCompare := TChilkatStringBuilder.Create(Self);
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Keep this file private and outside public web content/source control.
credentials := TChilkatJsonObject.Create(Self);
credentials.Strict := 1;
success := credentials.LoadFile('qa_data/aws/sts.json');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not load private STS configuration.');
    Exit;
  end;
stringCompare.SetString(credentials.StringOf('access_key'));
stringMatch1 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('access_key') <> 1) or (stringMatch1 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
stringCompare.SetString(credentials.StringOf('secret_key'));
stringMatch2 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('secret_key') <> 1) or (stringMatch2 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
expires := TCkDateTime.Create(Self);
now := TCkDateTime.Create(Self);
region := 'us-west-2';
if (credentials.HasMember('session_token') = 1) then
  begin
    stringCompare.SetString(credentials.StringOf('session_token'));
    stringMatch3 := stringCompare.ContentsEqual('',1);
    if ((credentials.JsonTypeOf('session_token') <> 1) or (stringMatch3 = 1)) then
      begin
        Memo1.Lines.Add('Missing or invalid session_token.');
        Exit;
      end;
    stringCompare.SetString(credentials.StringOf('expiration'));
    stringMatch4 := stringCompare.ContentsEqual('',1);
    if ((credentials.JsonTypeOf('expiration') <> 1) or (stringMatch4 = 1)) then
      begin
        Memo1.Lines.Add('Missing or invalid expiration.');
        Exit;
      end;
    success := expires.SetFromTimestamp(credentials.StringOf('expiration'));
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Source expiration is invalid.');
        Exit;
      end;
    success := now.SetFromCurrentSystemTime();
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not read current time.');
        Exit;
      end;
    if (expires.DiffSeconds(now.ControlInterface) <= 60) then
      begin
        Memo1.Lines.Add('Source credentials are expired or expire within 60 seconds; obtain fresh credentials.');
        Exit;
      end;
  end;
stringCompare.SetString(credentials.StringOf('role_arn'));
stringMatch5 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('role_arn') <> 1) or (stringMatch5 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid role_arn.');
    Exit;
  end;
stringCompare.SetString(credentials.StringOf('role_session_name'));
stringMatch6 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('role_session_name') <> 1) or (stringMatch6 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid role_session_name.');
    Exit;
  end;
identifier := TChilkatStringBuilder.Create(Self);
identifier.Append(credentials.StringOf('role_session_name'));
if ((identifier.Length < 2) or (identifier.Length > 64)) then
  begin
    Memo1.Lines.Add('role_session_name must have 2-64 characters.');
    Exit;
  end;
allowed := TChilkatStringBuilder.Create(Self);
allowed.Append('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-');
charIndex := 0;
while (charIndex < identifier.Length) do
  begin
    if (allowed.Contains(identifier.GetRange(charIndex,1,0),1) <> 1) then
      begin
        Memo1.Lines.Add('Invalid character in role_session_name.');
        Exit;
      end;
    charIndex := charIndex + 1;
  end;

if ((credentials.HasMember('mfa_code') = 1) or (credentials.HasMember('mfa_serial') = 1)) then
  begin
    Memo1.Lines.Add('This unattended refresh example does not reuse MFA codes.');
    Exit;
  end;
//  Optional private cache contains only the four normalized session fields.
//  In an application, keep activeSnapshot in memory between units of work.
files := TCkFileAccess.Create(Self);
cached := TChilkatJsonObject.Create(Self);
cached.Strict := 1;
activeSnapshot := '';
refreshRequired := 1;
if (files.FileExists('qa_data/tokens/sts_session.json') = 1) then
  begin
    success := cached.LoadFile('qa_data/tokens/sts_session.json');
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Invalid private cache.');
        Exit;
      end;
    stringCompare.SetString(cached.StringOf('access_key'));
    stringMatch7 := stringCompare.ContentsEqual('',1);
    if ((cached.JsonTypeOf('access_key') <> 1) or (stringMatch7 = 1)) then
      begin
        Memo1.Lines.Add('Incomplete private cache.');
        Exit;
      end;
    stringCompare.SetString(cached.StringOf('secret_key'));
    stringMatch8 := stringCompare.ContentsEqual('',1);
    if ((cached.JsonTypeOf('secret_key') <> 1) or (stringMatch8 = 1)) then
      begin
        Memo1.Lines.Add('Incomplete private cache.');
        Exit;
      end;
    stringCompare.SetString(cached.StringOf('session_token'));
    stringMatch9 := stringCompare.ContentsEqual('',1);
    if ((cached.JsonTypeOf('session_token') <> 1) or (stringMatch9 = 1)) then
      begin
        Memo1.Lines.Add('Incomplete private cache.');
        Exit;
      end;
    stringCompare.SetString(cached.StringOf('expiration'));
    stringMatch10 := stringCompare.ContentsEqual('',1);
    if ((cached.JsonTypeOf('expiration') <> 1) or (stringMatch10 = 1)) then
      begin
        Memo1.Lines.Add('Incomplete private cache.');
        Exit;
      end;
    success := expires.SetFromTimestamp(cached.StringOf('expiration'));
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Invalid cached expiration.');
        Exit;
      end;
    success := now.SetFromCurrentSystemTime();
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not read current time.');
        Exit;
      end;
    if (expires.DiffSeconds(now.ControlInterface) > 300) then
      begin
        activeSnapshot := cached.Emit();
        refreshRequired := 0;
      end;
  end;
if (refreshRequired = 1) then
  begin
    endpoint := TChilkatStringBuilder.Create(Self);
    endpoint.Append('sts.');
    endpoint.Append(region);
    endpoint.Append('.amazonaws.com');
    aws := TChilkatAuthAws.Create(Self);
    aws.AccessKey := credentials.StringOf('access_key');
    aws.SecretKey := credentials.StringOf('secret_key');
    aws.Region := region;
    aws.ServiceName := 'sts';
    aws.SignatureVersion := 4;
    rest := TChilkatRest.Create(Self);
    rest.ConnectTimeoutMs := 20000;
    rest.IdleTimeoutMs := 60000;
    rest.VerboseLogging := 0;
    success := rest.SetAuthAws(aws.ControlInterface);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not configure request signing.');
        Exit;
      end;
    //  Keep this verified Socket alive while Rest uses its connection.
    connection := TChilkatSocket.Create(Self);
    connection.RequireSslCertVerify := 1;
    connection.MaxReadIdleMs := 60000;
    connection.MaxSendIdleMs := 60000;
    success := connection.Connect(endpoint.GetAsString(),443,1,20000);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
        Exit;
      end;
    success := rest.UseConnection(connection.ControlInterface,1);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not attach TLS connection.');
        Exit;
      end;
    xml := TChilkatXml.Create(Self);
    xml.Strict := 1;

    responseXml := '';
    attempt := 0;
    delayMs := 1000;
    received := 0;

    while ((attempt < 3) and (received = 0)) do
      begin
        if (credentials.HasMember('session_token') = 1) then
          begin
            stringCompare.SetString(credentials.StringOf('session_token'));
            stringMatch11 := stringCompare.ContentsEqual('',1);
            if ((credentials.JsonTypeOf('session_token') <> 1) or (stringMatch11 = 1)) then
              begin
                Memo1.Lines.Add('Missing or invalid session_token.');
                Exit;
              end;
            stringCompare.SetString(credentials.StringOf('expiration'));
            stringMatch12 := stringCompare.ContentsEqual('',1);
            if ((credentials.JsonTypeOf('expiration') <> 1) or (stringMatch12 = 1)) then
              begin
                Memo1.Lines.Add('Missing or invalid expiration.');
                Exit;
              end;
            success := expires.SetFromTimestamp(credentials.StringOf('expiration'));
            if (success <> 1) then
              begin
                Memo1.Lines.Add('Source expiration is invalid.');
                Exit;
              end;
            success := now.SetFromCurrentSystemTime();
            if (success <> 1) then
              begin
                Memo1.Lines.Add('Could not read current time.');
                Exit;
              end;
            if (expires.DiffSeconds(now.ControlInterface) <= 60) then
              begin
                Memo1.Lines.Add('Source credentials are expired or expire within 60 seconds; obtain fresh credentials.');
                Exit;
              end;
          end;
        attempt := attempt + 1;
        success := rest.ClearAllQueryParams();
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not reset request parameters.');
            Exit;
          end;
        success := rest.AddQueryParam('Action','AssumeRole');
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set Action.');
            Exit;
          end;
        success := rest.AddQueryParam('Version','2011-06-15');
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set Version.');
            Exit;
          end;
        if (credentials.HasMember('session_token') = 1) then
          begin
            success := rest.AddQueryParam('X-Amz-Security-Token',credentials.StringOf('session_token'));
            if (success <> 1) then
              begin
                Memo1.Lines.Add('Could not set X-Amz-Security-Token.');
                Exit;
              end;
          end;
        success := rest.AddQueryParam('RoleArn',credentials.StringOf('role_arn'));
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set RoleArn.');
            Exit;
          end;
        success := rest.AddQueryParam('RoleSessionName',credentials.StringOf('role_session_name'));
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set RoleSessionName.');
            Exit;
          end;
        success := rest.AddQueryParam('DurationSeconds','3600');
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not set DurationSeconds.');
            Exit;
          end;
        responseXml := rest.FullRequestFormUrlEncoded('POST','/');
        if (rest.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Transport failed; credential refresh was not published.');
            Exit;
          end;
        if (rest.ResponseStatusCode = 200) then
          begin
            received := 1;
          end;
        if (rest.ResponseStatusCode <> 200) then
          begin
            retryable := 0;
            value := '';
            success := xml.LoadXml(responseXml);
            if (success = 1) then
              begin
                value := xml.GetChildContent('Error|Code');
              end;
            stringCompare.SetString(value);
            stringMatch13 := stringCompare.ContentsEqual('Throttling',1);
            stringCompare.SetString(value);
            stringMatch14 := stringCompare.ContentsEqual('ThrottlingException',1);
            if ((rest.ResponseStatusCode = 429) or (rest.ResponseStatusCode = 500) or (rest.ResponseStatusCode = 502) or (rest.ResponseStatusCode = 503) or (rest.ResponseStatusCode = 504) or (stringMatch13 = 1) or (stringMatch14 = 1)) then
              begin
                retryable := 1;
              end;
            if ((retryable <> 1) or (attempt = 3)) then
              begin
                Memo1.Lines.Add('Refresh failed. HTTP status: ' + IntToStr(rest.ResponseStatusCode));
                Memo1.Lines.Add('AWS error code: ' + value);
                Exit;
              end;
            connection.SleepMs(delayMs);
            delayMs := delayMs * 2;
          end;
      end;

    if (received <> 1) then
      begin
        Memo1.Lines.Add('Refresh attempts exhausted.');
        Exit;
      end;
    success := xml.LoadXml(responseXml);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Invalid STS XML response.');
        Exit;
      end;
    stringCompare.SetString(xml.Tag);
    stringMatch15 := stringCompare.ContentsEqual('AssumeRoleResponse',1);
    if (stringMatch15 <> 1) then
      begin
        Memo1.Lines.Add('Unexpected STS response root.');
        Exit;
      end;
    value := xml.GetChildContent('ResponseMetadata|RequestId');
    stringCompare.SetString(value);
    stringMatch16 := stringCompare.ContentsEqual('',1);
    if ((xml.LastMethodSuccess <> 1) or (stringMatch16 = 1)) then
      begin
        Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
        Exit;
      end;
    if (xml.HasChildWithTag('AssumeRoleResult') <> 1) then
      begin
        Memo1.Lines.Add('Missing STS result.');
        Exit;
      end;
    accessKey := xml.GetChildContent('AssumeRoleResult|Credentials|AccessKeyId');
    stringCompare.SetString(accessKey);
    stringMatch17 := stringCompare.ContentsEqual('',1);
    if ((xml.LastMethodSuccess <> 1) or (stringMatch17 = 1)) then
      begin
        Memo1.Lines.Add('Missing or empty AssumeRoleResult|Credentials|AccessKeyId.');
        Exit;
      end;
    secretKey := xml.GetChildContent('AssumeRoleResult|Credentials|SecretAccessKey');
    stringCompare.SetString(secretKey);
    stringMatch18 := stringCompare.ContentsEqual('',1);
    if ((xml.LastMethodSuccess <> 1) or (stringMatch18 = 1)) then
      begin
        Memo1.Lines.Add('Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.');
        Exit;
      end;
    sessionToken := xml.GetChildContent('AssumeRoleResult|Credentials|SessionToken');
    stringCompare.SetString(sessionToken);
    stringMatch19 := stringCompare.ContentsEqual('',1);
    if ((xml.LastMethodSuccess <> 1) or (stringMatch19 = 1)) then
      begin
        Memo1.Lines.Add('Missing or empty AssumeRoleResult|Credentials|SessionToken.');
        Exit;
      end;
    expiration := xml.GetChildContent('AssumeRoleResult|Credentials|Expiration');
    stringCompare.SetString(expiration);
    stringMatch20 := stringCompare.ContentsEqual('',1);
    if ((xml.LastMethodSuccess <> 1) or (stringMatch20 = 1)) then
      begin
        Memo1.Lines.Add('Missing or empty AssumeRoleResult|Credentials|Expiration.');
        Exit;
      end;
    success := expires.SetFromTimestamp(expiration);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Returned expiration is invalid.');
        Exit;
      end;
    success := now.SetFromCurrentSystemTime();
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not read current time.');
        Exit;
      end;
    if (expires.DiffSeconds(now.ControlInterface) <= 60) then
      begin
        Memo1.Lines.Add('Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.');
        Exit;
      end;
    value := xml.GetChildContent('AssumeRoleResult|AssumedRoleUser|Arn');
    stringCompare.SetString(value);
    stringMatch21 := stringCompare.ContentsEqual('',1);
    if ((xml.LastMethodSuccess <> 1) or (stringMatch21 = 1)) then
      begin
        Memo1.Lines.Add('Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.');
        Exit;
      end;
    value := xml.GetChildContent('AssumeRoleResult|AssumedRoleUser|AssumedRoleId');
    stringCompare.SetString(value);
    stringMatch22 := stringCompare.ContentsEqual('',1);
    if ((xml.LastMethodSuccess <> 1) or (stringMatch22 = 1)) then
      begin
        Memo1.Lines.Add('Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.');
        Exit;
      end;
    session := TChilkatJsonObject.Create(Self);
    success := session.UpdateString('access_key',accessKey);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not build complete session.');
        Exit;
      end;
    success := session.UpdateString('secret_key',secretKey);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not build complete session.');
        Exit;
      end;
    success := session.UpdateString('session_token',sessionToken);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not build complete session.');
        Exit;
      end;
    success := session.UpdateString('expiration',expiration);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not build complete session.');
        Exit;
      end;
    //  Use session in memory; do not print or log session.Emit().
    Memo1.Lines.Add('Session validated; expiration: ' + expiration);
    //  Publish one complete snapshot only after validating every returned field.
    activeSnapshot := session.Emit();
  end;
//  Rehydrate a complete set for the next unit of work, never four partial updates.
usable := TChilkatJsonObject.Create(Self);
usable.Strict := 1;
success := usable.Load(activeSnapshot);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not load the complete session snapshot.');
    Exit;
  end;
//  Pass usable to your service client here. Do not log activeSnapshot.
Memo1.Lines.Add('Session ready for the next unit of work; expiration: ' + usable.StringOf('expiration'));
Memo1.Lines.Add('Example completed.');