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

AWS STS: Exchange an OIDC Token for Role Credentials

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.

Provide role_arn, role_session_name and the complete web_identity_token from your OIDC provider. The exchange is unsigned: no AWS access key or SigV4 header is sent. Configure the IAM provider and role trust for the expected issuer, audience and subject. STS validates the token; this sample does not treat decoding a JWT as verification. Refresh expired input through your identity provider.

AWS references: AssumeRoleWithWebIdentity

Chilkat Delphi ActiveX Downloads

Delphi ActiveX
var
success: Integer;
stringCompare: TChilkatStringBuilder;
credentials: TChilkatJsonObject;
expires: TCkDateTime;
now: TCkDateTime;
region: WideString;
stringMatch1: Integer;
stringMatch2: Integer;
identifier: TChilkatStringBuilder;
allowed: TChilkatStringBuilder;
charIndex: Integer;
stringMatch3: Integer;
endpoint: TChilkatStringBuilder;
rest: TChilkatRest;
connection: TChilkatSocket;
xml: TChilkatXml;
value: WideString;
accessKey: WideString;
secretKey: WideString;
sessionToken: WideString;
expiration: WideString;
responseXml: WideString;
stringMatch4: Integer;
stringMatch5: Integer;
stringMatch6: Integer;
stringMatch7: Integer;
stringMatch8: Integer;
stringMatch9: Integer;
stringMatch10: Integer;
stringMatch11: Integer;
session: TChilkatJsonObject;

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;
expires := TCkDateTime.Create(Self);
now := TCkDateTime.Create(Self);
region := 'us-west-2';
stringCompare.SetString(credentials.StringOf('role_arn'));
stringMatch1 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('role_arn') <> 1) or (stringMatch1 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid role_arn.');
    Exit;
  end;
stringCompare.SetString(credentials.StringOf('role_session_name'));
stringMatch2 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('role_session_name') <> 1) or (stringMatch2 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid role_session_name.');
    Exit;
  end;
identifier := TChilkatStringBuilder.Create(Self);
identifier.Append(credentials.StringOf('role_session_name'));
if ((identifier.Length < 2) or (identifier.Length > 64)) then
  begin
    Memo1.Lines.Add('role_session_name must have 2-64 characters.');
    Exit;
  end;
allowed := TChilkatStringBuilder.Create(Self);
allowed.Append('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-');
charIndex := 0;
while (charIndex < identifier.Length) do
  begin
    if (allowed.Contains(identifier.GetRange(charIndex,1,0),1) <> 1) then
      begin
        Memo1.Lines.Add('Invalid character in role_session_name.');
        Exit;
      end;
    charIndex := charIndex + 1;
  end;

stringCompare.SetString(credentials.StringOf('web_identity_token'));
stringMatch3 := stringCompare.ContentsEqual('',1);
if ((credentials.JsonTypeOf('web_identity_token') <> 1) or (stringMatch3 = 1)) then
  begin
    Memo1.Lines.Add('Missing or invalid web_identity_token.');
    Exit;
  end;
endpoint := TChilkatStringBuilder.Create(Self);
endpoint.Append('sts.');
endpoint.Append(region);
endpoint.Append('.amazonaws.com');
rest := TChilkatRest.Create(Self);
rest.ConnectTimeoutMs := 20000;
rest.IdleTimeoutMs := 60000;
rest.VerboseLogging := 0;
//  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','AssumeRoleWithWebIdentity');
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('RoleArn',credentials.StringOf('role_arn'));
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set RoleArn.');
    Exit;
  end;
success := rest.AddQueryParam('RoleSessionName',credentials.StringOf('role_session_name'));
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set RoleSessionName.');
    Exit;
  end;
success := rest.AddQueryParam('DurationSeconds','3600');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set DurationSeconds.');
    Exit;
  end;
success := rest.AddQueryParam('WebIdentityToken',credentials.StringOf('web_identity_token'));
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not set WebIdentityToken.');
    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);
stringMatch4 := stringCompare.ContentsEqual('AssumeRoleWithWebIdentityResponse',1);
if (stringMatch4 <> 1) then
  begin
    Memo1.Lines.Add('Unexpected STS response root.');
    Exit;
  end;
value := xml.GetChildContent('ResponseMetadata|RequestId');
stringCompare.SetString(value);
stringMatch5 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch5 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
if (xml.HasChildWithTag('AssumeRoleWithWebIdentityResult') <> 1) then
  begin
    Memo1.Lines.Add('Missing STS result.');
    Exit;
  end;
accessKey := xml.GetChildContent('AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId');
stringCompare.SetString(accessKey);
stringMatch6 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch6 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId.');
    Exit;
  end;
secretKey := xml.GetChildContent('AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey');
stringCompare.SetString(secretKey);
stringMatch7 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch7 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey.');
    Exit;
  end;
sessionToken := xml.GetChildContent('AssumeRoleWithWebIdentityResult|Credentials|SessionToken');
stringCompare.SetString(sessionToken);
stringMatch8 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch8 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SessionToken.');
    Exit;
  end;
expiration := xml.GetChildContent('AssumeRoleWithWebIdentityResult|Credentials|Expiration');
stringCompare.SetString(expiration);
stringMatch9 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch9 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleWithWebIdentityResult|Credentials|Expiration.');
    Exit;
  end;
success := expires.SetFromTimestamp(expiration);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Returned 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('Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.');
    Exit;
  end;
value := xml.GetChildContent('AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn');
stringCompare.SetString(value);
stringMatch10 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch10 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn.');
    Exit;
  end;
value := xml.GetChildContent('AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId');
stringCompare.SetString(value);
stringMatch11 := stringCompare.ContentsEqual('',1);
if ((xml.LastMethodSuccess <> 1) or (stringMatch11 = 1)) then
  begin
    Memo1.Lines.Add('Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId.');
    Exit;
  end;
session := TChilkatJsonObject.Create(Self);
success := session.UpdateString('access_key',accessKey);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not build complete session.');
    Exit;
  end;
success := session.UpdateString('secret_key',secretKey);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not build complete session.');
    Exit;
  end;
success := session.UpdateString('session_token',sessionToken);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not build complete session.');
    Exit;
  end;
success := session.UpdateString('expiration',expiration);
if (success <> 1) 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);
Memo1.Lines.Add('Example completed.');