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

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
credentials: HCkJsonObject;
stringMatch1: Boolean;
stringMatch2: Boolean;
expires: HCkDateTime;
now: HCkDateTime;
region: PWideChar;
stringMatch3: Boolean;
stringMatch4: Boolean;
stringMatch5: Boolean;
subjectMode: PWideChar;
stringMatch6: Boolean;
stringMatch7: Boolean;
stringMatch8: Boolean;
stringMatch9: Boolean;
stringMatch10: Boolean;
scopeText: HCkStringBuilder;
allowedScope: HCkStringBuilder;
scopeIndex: Integer;
scopeValues: HCkStringTable;
seenScopes: HCkHashtable;
scopeValue: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
value: PWideChar;
sessionToken: PWideChar;
expiration: PWideChar;
responseXml: PWideChar;
stringMatch11: Boolean;
stringMatch12: Boolean;
stringMatch13: Boolean;
stringMatch14: Boolean;

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,'audience'));
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'audience') <> 1) or (stringMatch5 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid audience.');
    Exit;
  end;
//  Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
subjectMode := 'AWSIdentity';
if (CkJsonObject_HasMember(credentials,'subject_mode') = True) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'subject_mode'));
    stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'subject_mode') <> 1) or (stringMatch6 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid subject_mode.');
        Exit;
      end;
    subjectMode := CkJsonObject__stringOf(credentials,'subject_mode');
  end;
CkStringBuilder_SetString(stringCompare,subjectMode);
stringMatch7 := CkStringBuilder_ContentsEqual(stringCompare,'AWSIdentity',True);
CkStringBuilder_SetString(stringCompare,subjectMode);
stringMatch8 := CkStringBuilder_ContentsEqual(stringCompare,'OriginIdentity',True);
if ((stringMatch7 <> True) and (stringMatch8 <> True)) then
  begin
    Memo1.Lines.Add('Invalid subject_mode.');
    Exit;
  end;
if (CkJsonObject_HasMember(credentials,'scope') = True) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'scope'));
    stringMatch9 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'scope') <> 1) or (stringMatch9 = True)) then
      begin
        Memo1.Lines.Add('Missing or invalid scope.');
        Exit;
      end;
    CkStringBuilder_SetString(stringCompare,subjectMode);
    stringMatch10 := CkStringBuilder_ContentsEqual(stringCompare,'OriginIdentity',True);
    if (stringMatch10 <> True) then
      begin
        Memo1.Lines.Add('scope requires OriginIdentity.');
        Exit;
      end;
    scopeText := CkStringBuilder_Create();
    CkStringBuilder_Append(scopeText,CkJsonObject__stringOf(credentials,'scope'));
    if ((CkStringBuilder_getLength(scopeText) > 256) or (CkStringBuilder_StartsWith(scopeText,' ',True) = True) or (CkStringBuilder_EndsWith(scopeText,' ',True) = True) or (CkStringBuilder_Contains(scopeText,'  ',True) = True)) then
      begin
        Memo1.Lines.Add('Invalid scope length or spacing.');
        Exit;
      end;
    allowedScope := CkStringBuilder_Create();
    CkStringBuilder_Append(allowedScope,'!#$%&''()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ');
    scopeIndex := 0;
    while (scopeIndex < CkStringBuilder_getLength(scopeText)) do
      begin
        if (CkStringBuilder_Contains(allowedScope,CkStringBuilder__getRange(scopeText,scopeIndex,1,False),True) <> True) then
          begin
            Memo1.Lines.Add('Invalid scope character.');
            Exit;
          end;
        scopeIndex := scopeIndex + 1;
      end;

    scopeValues := CkStringTable_Create();
    success := CkStringTable_SplitAndAppend(scopeValues,CkStringBuilder__getAsString(scopeText),' ',False,False);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not split scope values.');
        Exit;
      end;
    seenScopes := CkHashtable_Create();
    scopeIndex := 0;

    while (scopeIndex < CkStringTable_getCount(scopeValues)) do
      begin
        scopeValue := CkStringTable__stringAt(scopeValues,scopeIndex);
        if (CkHashtable_Contains(seenScopes,scopeValue) = True) then
          begin
            Memo1.Lines.Add('Duplicate scope value.');
            Exit;
          end;
        success := CkHashtable_AddStr(seenScopes,scopeValue,'seen');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not track scope values.');
            Exit;
          end;
        scopeIndex := scopeIndex + 1;
      end;

  end;
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 := '';
success := CkRest_ClearAllQueryParams(rest);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not reset request parameters.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Action','GetWebIdentityToken');
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,'Audience.member.1',CkJsonObject__stringOf(credentials,'audience'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Audience.member.1.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'SigningAlgorithm','RS256');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set SigningAlgorithm.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'DurationSeconds','300');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set DurationSeconds.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'SubjectMode',subjectMode);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set SubjectMode.');
    Exit;
  end;
if (CkJsonObject_HasMember(credentials,'scope') = True) then
  begin
    success := CkRest_AddQueryParam(rest,'Scope',CkJsonObject__stringOf(credentials,'scope'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set Scope.');
        Exit;
      end;
  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));
stringMatch11 := CkStringBuilder_ContentsEqual(stringCompare,'GetWebIdentityTokenResponse',True);
if (stringMatch11 <> True) then
  begin
    Memo1.Lines.Add('Unexpected STS response root.');
    Exit;
  end;
value := CkXml__getChildContent(xml,'ResponseMetadata|RequestId');
CkStringBuilder_SetString(stringCompare,value);
stringMatch12 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch12 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
if (CkXml_HasChildWithTag(xml,'GetWebIdentityTokenResult') <> True) then
  begin
    Memo1.Lines.Add('Missing STS result.');
    Exit;
  end;
sessionToken := CkXml__getChildContent(xml,'GetWebIdentityTokenResult|WebIdentityToken');
CkStringBuilder_SetString(stringCompare,sessionToken);
stringMatch13 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch13 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty GetWebIdentityTokenResult|WebIdentityToken.');
    Exit;
  end;
expiration := CkXml__getChildContent(xml,'GetWebIdentityTokenResult|Expiration');
CkStringBuilder_SetString(stringCompare,expiration);
stringMatch14 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch14 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty GetWebIdentityTokenResult|Expiration.');
    Exit;
  end;
success := CkDateTime_SetFromTimestamp(expires,expiration);
if (success <> True) then
  begin
    Memo1.Lines.Add('JWT 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('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.');

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkDateTime_Dispose(expires);
CkDateTime_Dispose(now);
    CkStringBuilder_Dispose(scopeText);
    CkStringBuilder_Dispose(allowedScope);
    CkStringTable_Dispose(scopeValues);
    CkHashtable_Dispose(seenScopes);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);