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

AWS STS: Refresh an AssumeRole Session Before Expiration

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.

Configure source credentials, role_arn and role_session_name for an unattended role that does not require interactive MFA. Optional qa_data/tokens/sts_session.json holds a previous normalized session for exactly that role, session configuration and workload; keep this cache private and never reuse it across roles. A complete cached set with more than five minutes remaining is reused. Otherwise obtains a new one-hour session, validates it, and publishes one serialized in-memory snapshot. No cache file is overwritten. Existing credentials cannot be extended.

Retries throttling and selected transient HTTP errors at most three times with one- and two-second waits, rebuilding the signed form and checking source expiration on each attempt. Transport, authorization and invalid-response failures stop without publication. Add jitter, synchronization and a credential provider appropriate to your runtime in a concurrent application. This single-thread sample does not implement shared-cache locking or reuse expired sources/MFA codes. Repeat the refresh decision before each unit of work.

AWS references: AssumeRole

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('role_arn'));
  final stringMatch5 = stringCompare.contentsEqual('', true);
  if ((credentials.jsonTypeOf('role_arn') != 1) || (stringMatch5)) {
    print('Missing or invalid role_arn.');
    return;
  }

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

  final identifier = CkStringBuilder();
  identifier.append(credentials.stringOf('role_session_name'));
  if ((identifier.length < 2) || (identifier.length > 64)) {
    print('role_session_name must have 2-64 characters.');
    return;
  }

  final allowed = CkStringBuilder();
  allowed.append('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-');
  var charIndex = 0;
  while (charIndex < identifier.length) {
    if (!allowed.contains(identifier.getRange(charIndex, 1, false), true)) {
      print('Invalid character in role_session_name.');
      return;
    }

    charIndex++;
  }

  if ((credentials.hasMember('mfa_code')) || (credentials.hasMember('mfa_serial'))) {
    print('This unattended refresh example does not reuse MFA codes.');
    return;
  }

  // Optional private cache contains only the four normalized session fields.
  // In an application, keep activeSnapshot in memory between units of work.
  final files = CkFileAccess();
  final cached = CkJsonObject();
  cached.strict = true;
  var activeSnapshot = '';
  var refreshRequired = true;
  if (files.fileExists('qa_data/tokens/sts_session.json')) {
    try {
      cached.loadFile('qa_data/tokens/sts_session.json');
    } on ChilkatException {
      print('Invalid private cache.');
      return;
    }

    stringCompare.setString(cached.stringOf('access_key'));
    final stringMatch7 = stringCompare.contentsEqual('', true);
    if ((cached.jsonTypeOf('access_key') != 1) || (stringMatch7)) {
      print('Incomplete private cache.');
      return;
    }

    stringCompare.setString(cached.stringOf('secret_key'));
    final stringMatch8 = stringCompare.contentsEqual('', true);
    if ((cached.jsonTypeOf('secret_key') != 1) || (stringMatch8)) {
      print('Incomplete private cache.');
      return;
    }

    stringCompare.setString(cached.stringOf('session_token'));
    final stringMatch9 = stringCompare.contentsEqual('', true);
    if ((cached.jsonTypeOf('session_token') != 1) || (stringMatch9)) {
      print('Incomplete private cache.');
      return;
    }

    stringCompare.setString(cached.stringOf('expiration'));
    final stringMatch10 = stringCompare.contentsEqual('', true);
    if ((cached.jsonTypeOf('expiration') != 1) || (stringMatch10)) {
      print('Incomplete private cache.');
      return;
    }

    try {
      expires.setFromTimestamp(cached.stringOf('expiration'));
    } on ChilkatException {
      print('Invalid cached expiration.');
      return;
    }

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

    if (expires.diffSeconds(now) > 300) {
      activeSnapshot = cached.emit();
      refreshRequired = false;
    }
  }

  if (refreshRequired) {
    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 = '';
    var attempt = 0;
    var delayMs = 1000;
    var received = false;
    var retryable = false;
    while ((attempt < 3) && (!received)) {
      if (credentials.hasMember('session_token')) {
        stringCompare.setString(credentials.stringOf('session_token'));
        final stringMatch11 = stringCompare.contentsEqual('', true);
        if ((credentials.jsonTypeOf('session_token') != 1) || (stringMatch11)) {
          print('Missing or invalid session_token.');
          return;
        }

        stringCompare.setString(credentials.stringOf('expiration'));
        final stringMatch12 = stringCompare.contentsEqual('', true);
        if ((credentials.jsonTypeOf('expiration') != 1) || (stringMatch12)) {
          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;
        }
      }

      attempt++;
      try {
        rest.clearAllQueryParams();
      } on ChilkatException {
        print('Could not reset request parameters.');
        return;
      }

      try {
        rest.addQueryParam('Action', 'AssumeRole');
      } 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('RoleArn', credentials.stringOf('role_arn'));
      } on ChilkatException {
        print('Could not set RoleArn.');
        return;
      }

      try {
        rest.addQueryParam('RoleSessionName', credentials.stringOf('role_session_name'));
      } on ChilkatException {
        print('Could not set RoleSessionName.');
        return;
      }

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

      try {
        responseXml = rest.fullRequestFormUrlEncoded('POST', '/');
      } on ChilkatException {
        print('Transport failed; credential refresh was not published.');
        return;
      }

      if (rest.responseStatusCode == 200) {
        received = true;
      }

      if (rest.responseStatusCode != 200) {
        retryable = false;
        value = '';
        try {
          xml.loadXml(responseXml);
          value = xml.getChildContent('Error|Code');
        } on ChilkatException {
          // xml.loadXml() failed; continue anyway.
        }

        stringCompare.setString(value);
        final stringMatch13 = stringCompare.contentsEqual('Throttling', true);
        stringCompare.setString(value);
        final stringMatch14 = stringCompare.contentsEqual('ThrottlingException', true);
        if ((rest.responseStatusCode == 429) || ((rest.responseStatusCode == 500) || ((rest.responseStatusCode == 502) || ((rest.responseStatusCode == 503) || ((rest.responseStatusCode == 504) || ((stringMatch13) || (stringMatch14))))))) {
          retryable = true;
        }

        if ((!retryable) || (attempt == 3)) {
          print('Refresh failed. HTTP status: ${rest.responseStatusCode}');
          print('AWS error code: $value');
          return;
        }

        connection.sleepMs(delayMs);
        delayMs = delayMs * 2;
      }
    }

    if (!received) {
      print('Refresh attempts exhausted.');
      return;
    }

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

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

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

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

    final accessKey = xml.getChildContent('AssumeRoleResult|Credentials|AccessKeyId');
    stringCompare.setString(accessKey);
    final stringMatch17 = stringCompare.contentsEqual('', true);
    if ((!xml.lastMethodSuccess) || (stringMatch17)) {
      print('Missing or empty AssumeRoleResult|Credentials|AccessKeyId.');
      return;
    }

    final secretKey = xml.getChildContent('AssumeRoleResult|Credentials|SecretAccessKey');
    stringCompare.setString(secretKey);
    final stringMatch18 = stringCompare.contentsEqual('', true);
    if ((!xml.lastMethodSuccess) || (stringMatch18)) {
      print('Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.');
      return;
    }

    final sessionToken = xml.getChildContent('AssumeRoleResult|Credentials|SessionToken');
    stringCompare.setString(sessionToken);
    final stringMatch19 = stringCompare.contentsEqual('', true);
    if ((!xml.lastMethodSuccess) || (stringMatch19)) {
      print('Missing or empty AssumeRoleResult|Credentials|SessionToken.');
      return;
    }

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

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

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

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

    value = xml.getChildContent('AssumeRoleResult|AssumedRoleUser|Arn');
    stringCompare.setString(value);
    final stringMatch21 = stringCompare.contentsEqual('', true);
    if ((!xml.lastMethodSuccess) || (stringMatch21)) {
      print('Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.');
      return;
    }

    value = xml.getChildContent('AssumeRoleResult|AssumedRoleUser|AssumedRoleId');
    stringCompare.setString(value);
    final stringMatch22 = stringCompare.contentsEqual('', true);
    if ((!xml.lastMethodSuccess) || (stringMatch22)) {
      print('Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.');
      return;
    }

    final session = CkJsonObject();
    try {
      session.updateString('access_key', accessKey);
    } on ChilkatException {
      print('Could not build complete session.');
      return;
    }

    try {
      session.updateString('secret_key', secretKey);
    } on ChilkatException {
      print('Could not build complete session.');
      return;
    }

    try {
      session.updateString('session_token', sessionToken);
    } on ChilkatException {
      print('Could not build complete session.');
      return;
    }

    try {
      session.updateString('expiration', expiration);
    } on ChilkatException {
      print('Could not build complete session.');
      return;
    }

    // Use session in memory; do not print or log session.Emit().
    print('Session validated; expiration: $expiration');
    // Publish one complete snapshot only after validating every returned field.
    activeSnapshot = session.emit();
  }

  // Rehydrate a complete set for the next unit of work, never four partial updates.
  final usable = CkJsonObject();
  usable.strict = true;
  try {
    usable.load(activeSnapshot);
  } on ChilkatException {
    print('Could not load the complete session snapshot.');
    return;
  }

  // Pass usable to your service client here. Do not log activeSnapshot.
  print('Session ready for the next unit of work; expiration: ${usable.stringOf('expiration')}');
  print('Example completed.');
}