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

AWS STS: Obtain an AWS-Signed JWT for an External Service

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.

Set audience to the intended external service. Requests RS256 with a five-minute lifetime from a regional STS endpoint; outbound federation must be enabled for the account. Optional subject_mode is AWSIdentity or OriginIdentity. OriginIdentity requires the caller's trusted identity propagation context. Optional scope is permitted only for OriginIdentity and this single audience, and requires sts:SetWebIdentityTokenScope in addition to sts:GetWebIdentityToken. Validates scope spacing, characters and duplicate values.

The returned token is an external identity JWT, not an AWS access key/session-token credential set. The recipient must validate its signature using the trusted issuer's JWKS, issuer, audience and lifetime; merely decoding it is insufficient. The request cannot extend the calling session's lifetime.

AWS references: GetWebIdentityToken

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;
subjectMode: WideString;
stringMatch6: Integer;
stringMatch7: Integer;
stringMatch8: Integer;
stringMatch9: Integer;
stringMatch10: Integer;
scopeText: TChilkatStringBuilder;
allowedScope: TChilkatStringBuilder;
scopeIndex: Integer;
scopeValues: TChilkatStringTable;
seenScopes: TChilkatHashtable;
scopeValue: WideString;
endpoint: TChilkatStringBuilder;
aws: TChilkatAuthAws;
rest: TChilkatRest;
connection: TChilkatSocket;
xml: TChilkatXml;
value: WideString;
sessionToken: WideString;
expiration: WideString;
responseXml: WideString;
stringMatch11: Integer;
stringMatch12: Integer;
stringMatch13: Integer;
stringMatch14: Integer;

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('audience'));
stringMatch5 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('audience') <> 1) or (stringMatch5 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid audience.');
    Exit;
  end;
//  Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
subjectMode := 'AWSIdentity';
if (credentials.HasMember('subject_mode') = 1) then
  begin
    stringCompare.SetString(credentials.StringOf('subject_mode'));
    stringMatch6 := stringCompare.ContentsEqual('',1);
    if ((credentials.JsonTypeOf('subject_mode') <> 1) or (stringMatch6 = 1)) then
      begin
        Memo1.Lines.Add('Missing or invalid subject_mode.');
        Exit;
      end;
    subjectMode := credentials.StringOf('subject_mode');
  end;
stringCompare.SetString(subjectMode);
stringMatch7 := stringCompare.ContentsEqual('AWSIdentity',1);
stringCompare.SetString(subjectMode);
stringMatch8 := stringCompare.ContentsEqual('OriginIdentity',1);
if ((stringMatch7 <> 1) and (stringMatch8 <> 1)) then
  begin
    Memo1.Lines.Add('Invalid subject_mode.');
    Exit;
  end;
if (credentials.HasMember('scope') = 1) then
  begin
    stringCompare.SetString(credentials.StringOf('scope'));
    stringMatch9 := stringCompare.ContentsEqual('',1);
    if ((credentials.JsonTypeOf('scope') <> 1) or (stringMatch9 = 1)) then
      begin
        Memo1.Lines.Add('Missing or invalid scope.');
        Exit;
      end;
    stringCompare.SetString(subjectMode);
    stringMatch10 := stringCompare.ContentsEqual('OriginIdentity',1);
    if (stringMatch10 <> 1) then
      begin
        Memo1.Lines.Add('scope requires OriginIdentity.');
        Exit;
      end;
    scopeText := TChilkatStringBuilder.Create(Self);
    scopeText.Append(credentials.StringOf('scope'));
    if ((scopeText.Length > 256) or (scopeText.StartsWith(' ',1) = 1) or (scopeText.EndsWith(' ',1) = 1) or (scopeText.Contains('  ',1) = 1)) then
      begin
        Memo1.Lines.Add('Invalid scope length or spacing.');
        Exit;
      end;
    allowedScope := TChilkatStringBuilder.Create(Self);
    allowedScope.Append('!#$%&''()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ');
    scopeIndex := 0;
    while (scopeIndex < scopeText.Length) do
      begin
        if (allowedScope.Contains(scopeText.GetRange(scopeIndex,1,0),1) <> 1) then
          begin
            Memo1.Lines.Add('Invalid scope character.');
            Exit;
          end;
        scopeIndex := scopeIndex + 1;
      end;

    scopeValues := TChilkatStringTable.Create(Self);
    success := scopeValues.SplitAndAppend(scopeText.GetAsString(),' ',0,0);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not split scope values.');
        Exit;
      end;
    seenScopes := TChilkatHashtable.Create(Self);
    scopeIndex := 0;

    while (scopeIndex < scopeValues.Count) do
      begin
        scopeValue := scopeValues.StringAt(scopeIndex);
        if (seenScopes.Contains(scopeValue) = 1) then
          begin
            Memo1.Lines.Add('Duplicate scope value.');
            Exit;
          end;
        success := seenScopes.AddStr(scopeValue,'seen');
        if (success <> 1) then
          begin
            Memo1.Lines.Add('Could not track scope values.');
            Exit;
          end;
        scopeIndex := scopeIndex + 1;
      end;

  end;
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 := '';
success := rest.ClearAllQueryParams();
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not reset request parameters.');
    Exit;
  end;
success := rest.AddQueryParam('Action','GetWebIdentityToken');
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('Audience.member.1',credentials.StringOf('audience'));
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set Audience.member.1.');
    Exit;
  end;
success := rest.AddQueryParam('SigningAlgorithm','RS256');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set SigningAlgorithm.');
    Exit;
  end;
success := rest.AddQueryParam('DurationSeconds','300');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set DurationSeconds.');
    Exit;
  end;
success := rest.AddQueryParam('SubjectMode',subjectMode);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set SubjectMode.');
    Exit;
  end;
if (credentials.HasMember('scope') = 1) then
  begin
    success := rest.AddQueryParam('Scope',credentials.StringOf('scope'));
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not set Scope.');
        Exit;
      end;
  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);
stringMatch11 := stringCompare.ContentsEqual('GetWebIdentityTokenResponse',1);
if (stringMatch11 <> 1) then
  begin
    Memo1.Lines.Add('Unexpected STS response root.');
    Exit;
  end;
value := xml.GetChildContent('ResponseMetadata|RequestId');
stringCompare.SetString(value);
stringMatch12 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch12 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
if (xml.HasChildWithTag('GetWebIdentityTokenResult') <> 1) then
  begin
    Memo1.Lines.Add('Missing STS result.');
    Exit;
  end;
sessionToken := xml.GetChildContent('GetWebIdentityTokenResult|WebIdentityToken');
stringCompare.SetString(sessionToken);
stringMatch13 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch13 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty GetWebIdentityTokenResult|WebIdentityToken.');
    Exit;
  end;
expiration := xml.GetChildContent('GetWebIdentityTokenResult|Expiration');
stringCompare.SetString(expiration);
stringMatch14 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch14 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty GetWebIdentityTokenResult|Expiration.');
    Exit;
  end;
success := expires.SetFromTimestamp(expiration);
if (success <> 1) then
  begin
    Memo1.Lines.Add('JWT 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('JWT credentials are expired or expire within 60 seconds; obtain fresh credentials.');
    Exit;
  end;
//  Hand sessionToken to the intended external service over TLS; never log it.
Memo1.Lines.Add('Web identity token obtained; expiration: ' + expiration);
Memo1.Lines.Add('Example completed.');