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

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  final stringCompare = CkStringBuilder();
  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  // Keep this file private and outside public web content/source control.
  final credentials = CkJsonObject();
  credentials.strict = true;
  try {
    credentials.loadFile('qa_data/aws/sts.json');
  } on ChilkatException {
    print('Could not load private STS configuration.');
    return;
  }

  stringCompare.setString(credentials.stringOf('access_key'));
  final stringMatch1 = stringCompare.contentsEqual('', true);
  if ((credentials.jsonTypeOf('access_key') != 1) || (stringMatch1)) {
    print('Missing or invalid access_key.');
    return;
  }

  stringCompare.setString(credentials.stringOf('secret_key'));
  final stringMatch2 = stringCompare.contentsEqual('', true);
  if ((credentials.jsonTypeOf('secret_key') != 1) || (stringMatch2)) {
    print('Missing or invalid secret_key.');
    return;
  }

  final expires = CkDateTime();
  final now = CkDateTime();
  final region = 'us-west-2';
  if (credentials.hasMember('session_token')) {
    stringCompare.setString(credentials.stringOf('session_token'));
    final stringMatch3 = stringCompare.contentsEqual('', true);
    if ((credentials.jsonTypeOf('session_token') != 1) || (stringMatch3)) {
      print('Missing or invalid session_token.');
      return;
    }

    stringCompare.setString(credentials.stringOf('expiration'));
    final stringMatch4 = stringCompare.contentsEqual('', true);
    if ((credentials.jsonTypeOf('expiration') != 1) || (stringMatch4)) {
      print('Missing or invalid expiration.');
      return;
    }

    try {
      expires.setFromTimestamp(credentials.stringOf('expiration'));
    } on ChilkatException {
      print('Source expiration is invalid.');
      return;
    }

    try {
      now.setFromCurrentSystemTime();
    } on ChilkatException {
      print('Could not read current time.');
      return;
    }

    if (expires.diffSeconds(now) <= 60) {
      print('Source credentials are expired or expire within 60 seconds; obtain fresh credentials.');
      return;
    }
  }

  stringCompare.setString(credentials.stringOf('audience'));
  final stringMatch5 = stringCompare.contentsEqual('', true);
  if ((credentials.jsonTypeOf('audience') != 1) || (stringMatch5)) {
    print('Missing or invalid audience.');
    return;
  }

  // Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
  var subjectMode = 'AWSIdentity';
  if (credentials.hasMember('subject_mode')) {
    stringCompare.setString(credentials.stringOf('subject_mode'));
    final stringMatch6 = stringCompare.contentsEqual('', true);
    if ((credentials.jsonTypeOf('subject_mode') != 1) || (stringMatch6)) {
      print('Missing or invalid subject_mode.');
      return;
    }

    subjectMode = credentials.stringOf('subject_mode');
  }

  stringCompare.setString(subjectMode);
  final stringMatch7 = stringCompare.contentsEqual('AWSIdentity', true);
  stringCompare.setString(subjectMode);
  final stringMatch8 = stringCompare.contentsEqual('OriginIdentity', true);
  if ((!stringMatch7) && (!stringMatch8)) {
    print('Invalid subject_mode.');
    return;
  }

  if (credentials.hasMember('scope')) {
    stringCompare.setString(credentials.stringOf('scope'));
    final stringMatch9 = stringCompare.contentsEqual('', true);
    if ((credentials.jsonTypeOf('scope') != 1) || (stringMatch9)) {
      print('Missing or invalid scope.');
      return;
    }

    stringCompare.setString(subjectMode);
    final stringMatch10 = stringCompare.contentsEqual('OriginIdentity', true);
    if (!stringMatch10) {
      print('scope requires OriginIdentity.');
      return;
    }

    final scopeText = CkStringBuilder();
    scopeText.append(credentials.stringOf('scope'));
    if ((scopeText.length > 256) || ((scopeText.startsWith(' ', true)) || ((scopeText.endsWith(' ', true)) || (scopeText.contains('  ', true))))) {
      print('Invalid scope length or spacing.');
      return;
    }

    final allowedScope = CkStringBuilder();
    allowedScope.append('!#\$%&\'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ');
    var scopeIndex = 0;
    while (scopeIndex < scopeText.length) {
      if (!allowedScope.contains(scopeText.getRange(scopeIndex, 1, false), true)) {
        print('Invalid scope character.');
        return;
      }

      scopeIndex++;
    }

    final scopeValues = CkStringTable();
    try {
      scopeValues.splitAndAppend(scopeText.getAsString(), ' ', false, false);
    } on ChilkatException {
      print('Could not split scope values.');
      return;
    }

    final seenScopes = CkHashtable();
    scopeIndex = 0;
    var scopeValue = '';
    while (scopeIndex < scopeValues.count) {
      scopeValue = scopeValues.stringAt(scopeIndex);
      if (seenScopes.contains(scopeValue)) {
        print('Duplicate scope value.');
        return;
      }

      try {
        seenScopes.addStr(scopeValue, 'seen');
      } on ChilkatException {
        print('Could not track scope values.');
        return;
      }

      scopeIndex++;
    }
  }

  final endpoint = CkStringBuilder();
  endpoint.append('sts.');
  endpoint.append(region);
  endpoint.append('.amazonaws.com');
  final aws = CkAuthAws();
  aws.accessKey = credentials.stringOf('access_key');
  aws.secretKey = credentials.stringOf('secret_key');
  aws.region = region;
  aws.serviceName = 'sts';
  aws.signatureVersion = 4;
  final rest = CkRest();
  rest.connectTimeoutMs = 20000;
  rest.idleTimeoutMs = 60000;
  rest.verboseLogging = false;
  try {
    rest.setAuthAws(aws);
  } on ChilkatException {
    print('Could not configure request signing.');
    return;
  }

  // Keep this verified Socket alive while Rest uses its connection.
  final connection = CkSocket();
  connection.requireSslCertVerify = true;
  connection.maxReadIdleMs = 60000;
  connection.maxSendIdleMs = 60000;
  try {
    connection.connect(endpoint.getAsString(), 443, true, 20000);
  } on ChilkatException {
    print('TLS connection failed; inspect diagnostics privately.');
    return;
  }

  try {
    rest.useConnection(connection, true);
  } on ChilkatException {
    print('Could not attach TLS connection.');
    return;
  }

  final xml = CkXml();
  xml.strict = true;
  var value = '';
  var responseXml = '';
  try {
    rest.clearAllQueryParams();
  } on ChilkatException {
    print('Could not reset request parameters.');
    return;
  }

  try {
    rest.addQueryParam('Action', 'GetWebIdentityToken');
  } on ChilkatException {
    print('Could not set Action.');
    return;
  }

  try {
    rest.addQueryParam('Version', '2011-06-15');
  } on ChilkatException {
    print('Could not set Version.');
    return;
  }

  if (credentials.hasMember('session_token')) {
    try {
      rest.addQueryParam('X-Amz-Security-Token', credentials.stringOf('session_token'));
    } on ChilkatException {
      print('Could not set X-Amz-Security-Token.');
      return;
    }
  }

  try {
    rest.addQueryParam('Audience.member.1', credentials.stringOf('audience'));
  } on ChilkatException {
    print('Could not set Audience.member.1.');
    return;
  }

  try {
    rest.addQueryParam('SigningAlgorithm', 'RS256');
  } on ChilkatException {
    print('Could not set SigningAlgorithm.');
    return;
  }

  try {
    rest.addQueryParam('DurationSeconds', '300');
  } on ChilkatException {
    print('Could not set DurationSeconds.');
    return;
  }

  try {
    rest.addQueryParam('SubjectMode', subjectMode);
  } on ChilkatException {
    print('Could not set SubjectMode.');
    return;
  }

  if (credentials.hasMember('scope')) {
    try {
      rest.addQueryParam('Scope', credentials.stringOf('scope'));
    } on ChilkatException {
      print('Could not set Scope.');
      return;
    }
  }

  try {
    responseXml = rest.fullRequestFormUrlEncoded('POST', '/');
  } on ChilkatException {
    print('STS transport failed; inspect diagnostics privately.');
    return;
  }

  if (rest.responseStatusCode != 200) {
    print('STS HTTP status: ${rest.responseStatusCode}');
    try {
      xml.loadXml(responseXml);
      try {
        value = xml.getChildContent('Error|Code');
        print('AWS error code: $value');
      } on ChilkatException {
        // xml.getChildContent() failed; continue anyway.
      }

      try {
        value = xml.getChildContent('RequestId');
        print('AWS request ID: $value');
      } on ChilkatException {
        // xml.getChildContent() failed; continue anyway.
      }
    } on ChilkatException {
      // xml.loadXml() failed; continue anyway.
    }

    return;
  }

  try {
    xml.loadXml(responseXml);
  } on ChilkatException {
    print('Invalid STS XML response.');
    return;
  }

  stringCompare.setString(xml.tag);
  final stringMatch11 = stringCompare.contentsEqual('GetWebIdentityTokenResponse', true);
  if (!stringMatch11) {
    print('Unexpected STS response root.');
    return;
  }

  value = xml.getChildContent('ResponseMetadata|RequestId');
  stringCompare.setString(value);
  final stringMatch12 = stringCompare.contentsEqual('', true);
  if ((!xml.lastMethodSuccess) || (stringMatch12)) {
    print('Missing or empty ResponseMetadata|RequestId.');
    return;
  }

  if (!xml.hasChildWithTag('GetWebIdentityTokenResult')) {
    print('Missing STS result.');
    return;
  }

  final sessionToken = xml.getChildContent('GetWebIdentityTokenResult|WebIdentityToken');
  stringCompare.setString(sessionToken);
  final stringMatch13 = stringCompare.contentsEqual('', true);
  if ((!xml.lastMethodSuccess) || (stringMatch13)) {
    print('Missing or empty GetWebIdentityTokenResult|WebIdentityToken.');
    return;
  }

  final expiration = xml.getChildContent('GetWebIdentityTokenResult|Expiration');
  stringCompare.setString(expiration);
  final stringMatch14 = stringCompare.contentsEqual('', true);
  if ((!xml.lastMethodSuccess) || (stringMatch14)) {
    print('Missing or empty GetWebIdentityTokenResult|Expiration.');
    return;
  }

  try {
    expires.setFromTimestamp(expiration);
  } on ChilkatException {
    print('JWT expiration is invalid.');
    return;
  }

  try {
    now.setFromCurrentSystemTime();
  } on ChilkatException {
    print('Could not read current time.');
    return;
  }

  if (expires.diffSeconds(now) <= 60) {
    print('JWT credentials are expired or expire within 60 seconds; obtain fresh credentials.');
    return;
  }

  // Hand sessionToken to the intended external service over TLS; never log it.
  print('Web identity token obtained; expiration: $expiration');
  print('Example completed.');
}