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

Delphi ActiveX
var
success: Integer;
stringCompare: TChilkatStringBuilder;
tokenXml: TChilkatXml;
credentialPath: WideString;
stringMatch1: Integer;
stringMatch2: Integer;
stringMatch3: Integer;
stringMatch4: Integer;
stringMatch5: Integer;
stringMatch6: Integer;
stringMatch7: Integer;
stringMatch8: Integer;
accessKey: WideString;
secretKey: WideString;
sessionToken: WideString;
expiration: WideString;
path: TChilkatStringBuilder;
stringMatch9: Integer;
stringMatch10: Integer;
stringMatch11: Integer;
stringMatch12: Integer;
expires: TCkDateTime;
now: TCkDateTime;
session: TChilkatJsonObject;
region: WideString;
endpoint: TChilkatStringBuilder;
aws: TChilkatAuthAws;
rest: TChilkatRest;
connection: TChilkatSocket;
xml: TChilkatXml;
value: WideString;
responseXml: WideString;
stringMatch13: Integer;
stringMatch14: Integer;
stringMatch15: Integer;

begin
success := 0;

stringCompare := TChilkatStringBuilder.Create(Self);
//  Load a privately stored STS XML response; never print its contents.
tokenXml := TChilkatXml.Create(Self);
tokenXml.Strict := 1;
success := tokenXml.LoadXmlFile('qa_data/tokens/aws_session_token.xml');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not load private STS XML.');
    Exit;
  end;
credentialPath := '';
stringCompare.SetString(tokenXml.Tag);
stringMatch1 := stringCompare.ContentsEqual('GetSessionTokenResponse',1);
if (stringMatch1 = 1) then
  begin
    credentialPath := 'GetSessionTokenResult|Credentials';
  end;
stringCompare.SetString(tokenXml.Tag);
stringMatch2 := stringCompare.ContentsEqual('AssumeRoleResponse',1);
if (stringMatch2 = 1) then
  begin
    credentialPath := 'AssumeRoleResult|Credentials';
  end;
stringCompare.SetString(tokenXml.Tag);
stringMatch3 := stringCompare.ContentsEqual('AssumeRoleWithWebIdentityResponse',1);
if (stringMatch3 = 1) then
  begin
    credentialPath := 'AssumeRoleWithWebIdentityResult|Credentials';
  end;
stringCompare.SetString(tokenXml.Tag);
stringMatch4 := stringCompare.ContentsEqual('AssumeRoleWithSAMLResponse',1);
if (stringMatch4 = 1) then
  begin
    credentialPath := 'AssumeRoleWithSAMLResult|Credentials';
  end;
stringCompare.SetString(tokenXml.Tag);
stringMatch5 := stringCompare.ContentsEqual('GetFederationTokenResponse',1);
if (stringMatch5 = 1) then
  begin
    credentialPath := 'GetFederationTokenResult|Credentials';
  end;
stringCompare.SetString(tokenXml.Tag);
stringMatch6 := stringCompare.ContentsEqual('GetDelegatedAccessTokenResponse',1);
if (stringMatch6 = 1) then
  begin
    credentialPath := 'GetDelegatedAccessTokenResult|Credentials';
  end;
stringCompare.SetString(tokenXml.Tag);
stringMatch7 := stringCompare.ContentsEqual('AssumeRootResponse',1);
if (stringMatch7 = 1) then
  begin
    credentialPath := 'AssumeRootResult|Credentials';
  end;
stringCompare.SetString(credentialPath);
stringMatch8 := stringCompare.ContentsEqual('',1);
if (stringMatch8 = 1) then
  begin
    Memo1.Lines.Add('Unsupported STS credential response.');
    Exit;
  end;

path := TChilkatStringBuilder.Create(Self);
success := path.SetString(credentialPath);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
success := path.Append('|AccessKeyId');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
accessKey := tokenXml.GetChildContent(path.GetAsString());
stringCompare.SetString(accessKey);
stringMatch9 := stringCompare.ContentsEqual('',1);
if ((tokenXml.LastMethodSuccess <> 1) or (stringMatch9 = 1)) then
  begin
    Memo1.Lines.Add('Missing credential field AccessKeyId.');
    Exit;
  end;
success := path.SetString(credentialPath);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
success := path.Append('|SecretAccessKey');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
secretKey := tokenXml.GetChildContent(path.GetAsString());
stringCompare.SetString(secretKey);
stringMatch10 := stringCompare.ContentsEqual('',1);
if ((tokenXml.LastMethodSuccess <> 1) or (stringMatch10 = 1)) then
  begin
    Memo1.Lines.Add('Missing credential field SecretAccessKey.');
    Exit;
  end;
success := path.SetString(credentialPath);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
success := path.Append('|SessionToken');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
sessionToken := tokenXml.GetChildContent(path.GetAsString());
stringCompare.SetString(sessionToken);
stringMatch11 := stringCompare.ContentsEqual('',1);
if ((tokenXml.LastMethodSuccess <> 1) or (stringMatch11 = 1)) then
  begin
    Memo1.Lines.Add('Missing credential field SessionToken.');
    Exit;
  end;
success := path.SetString(credentialPath);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
success := path.Append('|Expiration');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not construct credential path.');
    Exit;
  end;
expiration := tokenXml.GetChildContent(path.GetAsString());
stringCompare.SetString(expiration);
stringMatch12 := stringCompare.ContentsEqual('',1);
if ((tokenXml.LastMethodSuccess <> 1) or (stringMatch12 = 1)) then
  begin
    Memo1.Lines.Add('Missing credential field Expiration.');
    Exit;
  end;
expires := TCkDateTime.Create(Self);
now := TCkDateTime.Create(Self);
success := expires.SetFromTimestamp(expiration);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Stored 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('Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.');
    Exit;
  end;
session := TChilkatJsonObject.Create(Self);
success := session.UpdateString('access_key',accessKey);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not build normalized session.');
    Exit;
  end;
success := session.UpdateString('secret_key',secretKey);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not build normalized session.');
    Exit;
  end;
success := session.UpdateString('session_token',sessionToken);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not build normalized session.');
    Exit;
  end;
success := session.UpdateString('expiration',expiration);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not build normalized session.');
    Exit;
  end;
region := 'us-west-2';
endpoint := TChilkatStringBuilder.Create(Self);
endpoint.Append('sts.');
endpoint.Append(region);
endpoint.Append('.amazonaws.com');
aws := TChilkatAuthAws.Create(Self);
aws.AccessKey := session.StringOf('access_key');
aws.SecretKey := session.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;

success := rest.ClearAllQueryParams();
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not reset request parameters.');
    Exit;
  end;
success := rest.AddQueryParam('Action','GetCallerIdentity');
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;
success := rest.AddQueryParam('X-Amz-Security-Token',session.StringOf('session_token'));
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set X-Amz-Security-Token.');
    Exit;
  end;
responseXml := rest.FullRequestFormUrlEncoded('POST','/');
if (rest.LastMethodSuccess <> 1) then
  begin
    Memo1.Lines.Add('STS transport failed; inspect diagnostics privately.');
    Exit;
  end;
if (rest.ResponseStatusCode <> 200) then
  begin
    Memo1.Lines.Add('STS HTTP status: ' + IntToStr(rest.ResponseStatusCode));
    success := xml.LoadXml(responseXml);
    if (success = 1) then
      begin
        value := xml.GetChildContent('Error|Code');
        if (xml.LastMethodSuccess = 1) then
          begin
            Memo1.Lines.Add('AWS error code: ' + value);
          end;
        value := xml.GetChildContent('RequestId');
        if (xml.LastMethodSuccess = 1) then
          begin
            Memo1.Lines.Add('AWS request ID: ' + value);
          end;
      end;
    Exit;
  end;
success := xml.LoadXml(responseXml);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Invalid STS XML response.');
    Exit;
  end;
stringCompare.SetString(xml.Tag);
stringMatch13 := stringCompare.ContentsEqual('GetCallerIdentityResponse',1);
if (stringMatch13 <> 1) then
  begin
    Memo1.Lines.Add('Unexpected STS response root.');
    Exit;
  end;
value := xml.GetChildContent('ResponseMetadata|RequestId');
stringCompare.SetString(value);
stringMatch14 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch14 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
if (xml.HasChildWithTag('GetCallerIdentityResult') <> 1) then
  begin
    Memo1.Lines.Add('Missing STS result.');
    Exit;
  end;
value := xml.GetChildContent('GetCallerIdentityResult|Arn');
stringCompare.SetString(value);
stringMatch15 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch15 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty GetCallerIdentityResult|Arn.');
    Exit;
  end;
Memo1.Lines.Add('Authenticated principal: ' + value);
Memo1.Lines.Add('Example completed.');