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 DLL Downloads
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;
files: HCkFileAccess;
cached: HCkJsonObject;
activeSnapshot: PWideChar;
refreshRequired: Boolean;
stringMatch7: Boolean;
stringMatch8: Boolean;
stringMatch9: Boolean;
stringMatch10: Boolean;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
value: PWideChar;
accessKey: PWideChar;
secretKey: PWideChar;
sessionToken: PWideChar;
expiration: PWideChar;
responseXml: PWideChar;
attempt: Integer;
delayMs: Integer;
received: Boolean;
retryable: Boolean;
stringMatch11: Boolean;
stringMatch12: Boolean;
stringMatch13: Boolean;
stringMatch14: Boolean;
stringMatch15: Boolean;
stringMatch16: Boolean;
stringMatch17: Boolean;
stringMatch18: Boolean;
stringMatch19: Boolean;
stringMatch20: Boolean;
stringMatch21: Boolean;
stringMatch22: Boolean;
session: HCkJsonObject;
usable: HCkJsonObject;
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;
if ((CkJsonObject_HasMember(credentials,'mfa_code') = True) or (CkJsonObject_HasMember(credentials,'mfa_serial') = True)) 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 := CkFileAccess_Create();
cached := CkJsonObject_Create();
CkJsonObject_putStrict(cached,True);
activeSnapshot := '';
refreshRequired := True;
if (CkFileAccess_FileExists(files,'qa_data/tokens/sts_session.json') = True) then
begin
success := CkJsonObject_LoadFile(cached,'qa_data/tokens/sts_session.json');
if (success <> True) then
begin
Memo1.Lines.Add('Invalid private cache.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(cached,'access_key'));
stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(cached,'access_key') <> 1) or (stringMatch7 = True)) then
begin
Memo1.Lines.Add('Incomplete private cache.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(cached,'secret_key'));
stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(cached,'secret_key') <> 1) or (stringMatch8 = True)) then
begin
Memo1.Lines.Add('Incomplete private cache.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(cached,'session_token'));
stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(cached,'session_token') <> 1) or (stringMatch9 = True)) then
begin
Memo1.Lines.Add('Incomplete private cache.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(cached,'expiration'));
stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(cached,'expiration') <> 1) or (stringMatch10 = True)) then
begin
Memo1.Lines.Add('Incomplete private cache.');
Exit;
end;
success := CkDateTime_SetFromTimestamp(expires,CkJsonObject__stringOf(cached,'expiration'));
if (success <> True) then
begin
Memo1.Lines.Add('Invalid cached expiration.');
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) > 300) then
begin
activeSnapshot := CkJsonObject__emit(cached);
refreshRequired := False;
end;
end;
if (refreshRequired = True) then
begin
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);
responseXml := '';
attempt := 0;
delayMs := 1000;
received := False;
while ((attempt < 3) and (received = False)) do
begin
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'session_token'));
stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) or (stringMatch11 = True)) then
begin
Memo1.Lines.Add('Missing or invalid session_token.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'expiration'));
stringMatch12 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'expiration') <> 1) or (stringMatch12 = 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;
attempt := attempt + 1;
success := CkRest_ClearAllQueryParams(rest);
if (success <> True) then
begin
Memo1.Lines.Add('Could not reset 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;
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;
success := CkRest_AddQueryParam(rest,'DurationSeconds','3600');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set DurationSeconds.');
Exit;
end;
responseXml := CkRest__fullRequestFormUrlEncoded(rest,'POST','/');
if (CkRest_getLastMethodSuccess(rest) <> True) then
begin
Memo1.Lines.Add('Transport failed; credential refresh was not published.');
Exit;
end;
if (CkRest_getResponseStatusCode(rest) = 200) then
begin
received := True;
end;
if (CkRest_getResponseStatusCode(rest) <> 200) then
begin
retryable := False;
value := '';
success := CkXml_LoadXml(xml,responseXml);
if (success = True) then
begin
value := CkXml__getChildContent(xml,'Error|Code');
end;
CkStringBuilder_SetString(stringCompare,value);
stringMatch13 := CkStringBuilder_ContentsEqual(stringCompare,'Throttling',True);
CkStringBuilder_SetString(stringCompare,value);
stringMatch14 := CkStringBuilder_ContentsEqual(stringCompare,'ThrottlingException',True);
if ((CkRest_getResponseStatusCode(rest) = 429) or (CkRest_getResponseStatusCode(rest) = 500) or (CkRest_getResponseStatusCode(rest) = 502) or (CkRest_getResponseStatusCode(rest) = 503) or (CkRest_getResponseStatusCode(rest) = 504) or (stringMatch13 = True) or (stringMatch14 = True)) then
begin
retryable := True;
end;
if ((retryable <> True) or (attempt = 3)) then
begin
Memo1.Lines.Add('Refresh failed. HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
Memo1.Lines.Add('AWS error code: ' + value);
Exit;
end;
CkSocket_SleepMs(connection,delayMs);
delayMs := delayMs * 2;
end;
end;
if (received <> True) then
begin
Memo1.Lines.Add('Refresh attempts exhausted.');
Exit;
end;
success := CkXml_LoadXml(xml,responseXml);
if (success <> True) then
begin
Memo1.Lines.Add('Invalid STS XML response.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(xml));
stringMatch15 := CkStringBuilder_ContentsEqual(stringCompare,'AssumeRoleResponse',True);
if (stringMatch15 <> True) then
begin
Memo1.Lines.Add('Unexpected STS response root.');
Exit;
end;
value := CkXml__getChildContent(xml,'ResponseMetadata|RequestId');
CkStringBuilder_SetString(stringCompare,value);
stringMatch16 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch16 = True)) then
begin
Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
Exit;
end;
if (CkXml_HasChildWithTag(xml,'AssumeRoleResult') <> True) then
begin
Memo1.Lines.Add('Missing STS result.');
Exit;
end;
accessKey := CkXml__getChildContent(xml,'AssumeRoleResult|Credentials|AccessKeyId');
CkStringBuilder_SetString(stringCompare,accessKey);
stringMatch17 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch17 = 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);
stringMatch18 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch18 = 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);
stringMatch19 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch19 = 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);
stringMatch20 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch20 = 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);
stringMatch21 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch21 = 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);
stringMatch22 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch22 = True)) then
begin
Memo1.Lines.Add('Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.');
Exit;
end;
session := CkJsonObject_Create();
success := CkJsonObject_UpdateString(session,'access_key',accessKey);
if (success <> True) then
begin
Memo1.Lines.Add('Could not build complete session.');
Exit;
end;
success := CkJsonObject_UpdateString(session,'secret_key',secretKey);
if (success <> True) then
begin
Memo1.Lines.Add('Could not build complete session.');
Exit;
end;
success := CkJsonObject_UpdateString(session,'session_token',sessionToken);
if (success <> True) then
begin
Memo1.Lines.Add('Could not build complete session.');
Exit;
end;
success := CkJsonObject_UpdateString(session,'expiration',expiration);
if (success <> True) 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 := CkJsonObject__emit(session);
end;
// Rehydrate a complete set for the next unit of work, never four partial updates.
usable := CkJsonObject_Create();
CkJsonObject_putStrict(usable,True);
success := CkJsonObject_Load(usable,activeSnapshot);
if (success <> True) 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: ' + CkJsonObject__stringOf(usable,'expiration'));
Memo1.Lines.Add('Example completed.');
CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkDateTime_Dispose(expires);
CkDateTime_Dispose(now);
CkStringBuilder_Dispose(identifier);
CkStringBuilder_Dispose(allowed);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(cached);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkJsonObject_Dispose(session);
CkJsonObject_Dispose(usable);