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

AWS STS: Normalize STS Credentials and Use Chilkat.Rest

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.

Reads only private qa_data/tokens/aws_session_token.xml; no sts.json is needed. Accepts all seven credential-producing STS response roots, including the existing GetSessionToken/AssumeRole handoff. Builds a complete normalized in-memory session and uses it to sign GetCallerIdentity. The normalized fields are access_key, secret_key, session_token and expiration. Checks expiration with a 60-second margin before connecting. JWT-only GetWebIdentityToken responses are intentionally not credential sets.

AWS references: GetCallerIdentity

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
tokenXml: HCkXml;
credentialPath: PWideChar;
stringMatch1: Boolean;
stringMatch2: Boolean;
stringMatch3: Boolean;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: Boolean;
stringMatch7: Boolean;
stringMatch8: Boolean;
accessKey: PWideChar;
secretKey: PWideChar;
sessionToken: PWideChar;
expiration: PWideChar;
path: HCkStringBuilder;
stringMatch9: Boolean;
stringMatch10: Boolean;
stringMatch11: Boolean;
stringMatch12: Boolean;
expires: HCkDateTime;
now: HCkDateTime;
session: HCkJsonObject;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
value: PWideChar;
responseXml: PWideChar;
stringMatch13: Boolean;
stringMatch14: Boolean;
stringMatch15: Boolean;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  Load a privately stored STS XML response; never print its contents.
tokenXml := CkXml_Create();
CkXml_putStrict(tokenXml,True);
success := CkXml_LoadXmlFile(tokenXml,'qa_data/tokens/aws_session_token.xml');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private STS XML.');
    Exit;
  end;
credentialPath := '';
CkStringBuilder_SetString(stringCompare,CkXml__tag(tokenXml));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'GetSessionTokenResponse',True);
if (stringMatch1 = True) then
  begin
    credentialPath := 'GetSessionTokenResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(tokenXml));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'AssumeRoleResponse',True);
if (stringMatch2 = True) then
  begin
    credentialPath := 'AssumeRoleResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(tokenXml));
stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'AssumeRoleWithWebIdentityResponse',True);
if (stringMatch3 = True) then
  begin
    credentialPath := 'AssumeRoleWithWebIdentityResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(tokenXml));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'AssumeRoleWithSAMLResponse',True);
if (stringMatch4 = True) then
  begin
    credentialPath := 'AssumeRoleWithSAMLResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(tokenXml));
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'GetFederationTokenResponse',True);
if (stringMatch5 = True) then
  begin
    credentialPath := 'GetFederationTokenResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(tokenXml));
stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'GetDelegatedAccessTokenResponse',True);
if (stringMatch6 = True) then
  begin
    credentialPath := 'GetDelegatedAccessTokenResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(tokenXml));
stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'AssumeRootResponse',True);
if (stringMatch7 = True) then
  begin
    credentialPath := 'AssumeRootResult|Credentials';
  end;
CkStringBuilder_SetString(stringCompare,credentialPath);
stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if (stringMatch8 = True) then
  begin
    Memo1.Lines.Add('Unsupported STS credential response.');
    Exit;
  end;

path := CkStringBuilder_Create();
success := CkStringBuilder_SetString(path,credentialPath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
success := CkStringBuilder_Append(path,'|AccessKeyId');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
accessKey := CkXml__getChildContent(tokenXml,CkStringBuilder__getAsString(path));
CkStringBuilder_SetString(stringCompare,accessKey);
stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(tokenXml) <> True) or (stringMatch9 = True)) then
  begin
    Memo1.Lines.Add('Missing credential field AccessKeyId.');
    Exit;
  end;
success := CkStringBuilder_SetString(path,credentialPath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
success := CkStringBuilder_Append(path,'|SecretAccessKey');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
secretKey := CkXml__getChildContent(tokenXml,CkStringBuilder__getAsString(path));
CkStringBuilder_SetString(stringCompare,secretKey);
stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(tokenXml) <> True) or (stringMatch10 = True)) then
  begin
    Memo1.Lines.Add('Missing credential field SecretAccessKey.');
    Exit;
  end;
success := CkStringBuilder_SetString(path,credentialPath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
success := CkStringBuilder_Append(path,'|SessionToken');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
sessionToken := CkXml__getChildContent(tokenXml,CkStringBuilder__getAsString(path));
CkStringBuilder_SetString(stringCompare,sessionToken);
stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(tokenXml) <> True) or (stringMatch11 = True)) then
  begin
    Memo1.Lines.Add('Missing credential field SessionToken.');
    Exit;
  end;
success := CkStringBuilder_SetString(path,credentialPath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
success := CkStringBuilder_Append(path,'|Expiration');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
expiration := CkXml__getChildContent(tokenXml,CkStringBuilder__getAsString(path));
CkStringBuilder_SetString(stringCompare,expiration);
stringMatch12 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(tokenXml) <> True) or (stringMatch12 = True)) then
  begin
    Memo1.Lines.Add('Missing credential field Expiration.');
    Exit;
  end;
expires := CkDateTime_Create();
now := CkDateTime_Create();
success := CkDateTime_SetFromTimestamp(expires,expiration);
if (success <> True) then
  begin
    Memo1.Lines.Add('Stored 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('Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.');
    Exit;
  end;
session := CkJsonObject_Create();
success := CkJsonObject_UpdateString(session,'access_key',accessKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build normalized session.');
    Exit;
  end;
success := CkJsonObject_UpdateString(session,'secret_key',secretKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build normalized session.');
    Exit;
  end;
success := CkJsonObject_UpdateString(session,'session_token',sessionToken);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build normalized session.');
    Exit;
  end;
success := CkJsonObject_UpdateString(session,'expiration',expiration);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build normalized session.');
    Exit;
  end;
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'sts.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(session,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(session,'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 reset request parameters.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Action','GetCallerIdentity');
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,'X-Amz-Security-Token',CkJsonObject__stringOf(session,'session_token'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set X-Amz-Security-Token.');
    Exit;
  end;
responseXml := CkRest__fullRequestFormUrlEncoded(rest,'POST','/');
if (CkRest_getLastMethodSuccess(rest) <> True) then
  begin
    Memo1.Lines.Add('STS transport failed; inspect diagnostics privately.');
    Exit;
  end;
if (CkRest_getResponseStatusCode(rest) <> 200) then
  begin
    Memo1.Lines.Add('STS HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
    success := CkXml_LoadXml(xml,responseXml);
    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;
    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));
stringMatch13 := CkStringBuilder_ContentsEqual(stringCompare,'GetCallerIdentityResponse',True);
if (stringMatch13 <> True) then
  begin
    Memo1.Lines.Add('Unexpected STS response root.');
    Exit;
  end;
value := CkXml__getChildContent(xml,'ResponseMetadata|RequestId');
CkStringBuilder_SetString(stringCompare,value);
stringMatch14 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch14 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
if (CkXml_HasChildWithTag(xml,'GetCallerIdentityResult') <> True) then
  begin
    Memo1.Lines.Add('Missing STS result.');
    Exit;
  end;
value := CkXml__getChildContent(xml,'GetCallerIdentityResult|Arn');
CkStringBuilder_SetString(stringCompare,value);
stringMatch15 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch15 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty GetCallerIdentityResult|Arn.');
    Exit;
  end;
Memo1.Lines.Add('Authenticated principal: ' + value);
Memo1.Lines.Add('Example completed.');

CkStringBuilder_Dispose(stringCompare);
CkXml_Dispose(tokenXml);
CkStringBuilder_Dispose(path);
CkDateTime_Dispose(expires);
CkDateTime_Dispose(now);
CkJsonObject_Dispose(session);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);