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 Java Downloads
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Socket;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
StringBuilder stringCompare = new StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this file private and outside public web content/source control.
JsonObject credentials = new JsonObject();
credentials.setStrict(true);
try {
credentials.loadFile("qa_data/aws/sts.json");
} catch (ChilkatException e) {
System.out.println("Could not load private STS configuration.");
return;
}
stringCompare.setString(credentials.stringOf("access_key"));
boolean stringMatch1 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("access_key") != 1) || (stringMatch1)) {
System.out.println("Missing or invalid access_key.");
return;
}
stringCompare.setString(credentials.stringOf("secret_key"));
boolean stringMatch2 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("secret_key") != 1) || (stringMatch2)) {
System.out.println("Missing or invalid secret_key.");
return;
}
DateTime expires = new DateTime();
DateTime now = new DateTime();
String region = "us-west-2";
if (credentials.hasMember("session_token")) {
stringCompare.setString(credentials.stringOf("session_token"));
boolean stringMatch3 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("session_token") != 1) || (stringMatch3)) {
System.out.println("Missing or invalid session_token.");
return;
}
stringCompare.setString(credentials.stringOf("expiration"));
boolean stringMatch4 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("expiration") != 1) || (stringMatch4)) {
System.out.println("Missing or invalid expiration.");
return;
}
try {
expires.setFromTimestamp(credentials.stringOf("expiration"));
} catch (ChilkatException e) {
System.out.println("Source expiration is invalid.");
return;
}
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read current time.");
return;
}
if (expires.diffSeconds(now) <= 60) {
System.out.println("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.");
return;
}
}
stringCompare.setString(credentials.stringOf("role_arn"));
boolean stringMatch5 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("role_arn") != 1) || (stringMatch5)) {
System.out.println("Missing or invalid role_arn.");
return;
}
stringCompare.setString(credentials.stringOf("role_session_name"));
boolean stringMatch6 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("role_session_name") != 1) || (stringMatch6)) {
System.out.println("Missing or invalid role_session_name.");
return;
}
StringBuilder identifier = new StringBuilder();
identifier.append(credentials.stringOf("role_session_name"));
if ((identifier.getLength() < 2) || (identifier.getLength() > 64)) {
System.out.println("role_session_name must have 2-64 characters.");
return;
}
StringBuilder allowed = new StringBuilder();
allowed.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-");
int charIndex = 0;
while (charIndex < identifier.getLength()) {
if (!allowed.contains(identifier.getRange(charIndex, 1, false), true)) {
System.out.println("Invalid character in role_session_name.");
return;
}
charIndex = charIndex + 1;
}
if ((credentials.hasMember("mfa_code")) || (credentials.hasMember("mfa_serial"))) {
System.out.println("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.
FileAccess files = new FileAccess();
JsonObject cached = new JsonObject();
cached.setStrict(true);
String activeSnapshot = "";
boolean refreshRequired = true;
if (files.fileExists("qa_data/tokens/sts_session.json")) {
try {
cached.loadFile("qa_data/tokens/sts_session.json");
} catch (ChilkatException e) {
System.out.println("Invalid private cache.");
return;
}
stringCompare.setString(cached.stringOf("access_key"));
boolean stringMatch7 = stringCompare.contentsEqual("", true);
if ((cached.jsonTypeOf("access_key") != 1) || (stringMatch7)) {
System.out.println("Incomplete private cache.");
return;
}
stringCompare.setString(cached.stringOf("secret_key"));
boolean stringMatch8 = stringCompare.contentsEqual("", true);
if ((cached.jsonTypeOf("secret_key") != 1) || (stringMatch8)) {
System.out.println("Incomplete private cache.");
return;
}
stringCompare.setString(cached.stringOf("session_token"));
boolean stringMatch9 = stringCompare.contentsEqual("", true);
if ((cached.jsonTypeOf("session_token") != 1) || (stringMatch9)) {
System.out.println("Incomplete private cache.");
return;
}
stringCompare.setString(cached.stringOf("expiration"));
boolean stringMatch10 = stringCompare.contentsEqual("", true);
if ((cached.jsonTypeOf("expiration") != 1) || (stringMatch10)) {
System.out.println("Incomplete private cache.");
return;
}
try {
expires.setFromTimestamp(cached.stringOf("expiration"));
} catch (ChilkatException e) {
System.out.println("Invalid cached expiration.");
return;
}
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read current time.");
return;
}
if (expires.diffSeconds(now) > 300) {
activeSnapshot = cached.emit();
refreshRequired = false;
}
}
if (refreshRequired) {
StringBuilder endpoint = new StringBuilder();
endpoint.append("sts.");
endpoint.append(region);
endpoint.append(".amazonaws.com");
AuthAws aws = new AuthAws();
aws.setAccessKey(credentials.stringOf("access_key"));
aws.setSecretKey(credentials.stringOf("secret_key"));
aws.setRegion(region);
aws.setServiceName("sts");
aws.setSignatureVersion(4);
Rest rest = new Rest();
rest.setConnectTimeoutMs(20000);
rest.setIdleTimeoutMs(60000);
rest.setVerboseLogging(false);
try {
rest.setAuthAws(aws);
} catch (ChilkatException e) {
System.out.println("Could not configure request signing.");
return;
}
// Keep this verified Socket alive while Rest uses its connection.
Socket connection = new Socket();
connection.setRequireSslCertVerify(true);
connection.setMaxReadIdleMs(60000);
connection.setMaxSendIdleMs(60000);
try {
connection.connect(endpoint.getAsString(), 443, true, 20000);
} catch (ChilkatException e) {
System.out.println("TLS connection failed; inspect diagnostics privately.");
return;
}
try {
rest.useConnection(connection, true);
} catch (ChilkatException e) {
System.out.println("Could not attach TLS connection.");
return;
}
Xml xml = new Xml();
xml.setStrict(true);
String value = "";
String responseXml = "";
int attempt = 0;
int delayMs = 1000;
boolean received = false;
boolean retryable = false;
while ((attempt < 3) && (!received)) {
if (credentials.hasMember("session_token")) {
stringCompare.setString(credentials.stringOf("session_token"));
boolean stringMatch11 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("session_token") != 1) || (stringMatch11)) {
System.out.println("Missing or invalid session_token.");
return;
}
stringCompare.setString(credentials.stringOf("expiration"));
boolean stringMatch12 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("expiration") != 1) || (stringMatch12)) {
System.out.println("Missing or invalid expiration.");
return;
}
try {
expires.setFromTimestamp(credentials.stringOf("expiration"));
} catch (ChilkatException e) {
System.out.println("Source expiration is invalid.");
return;
}
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read current time.");
return;
}
if (expires.diffSeconds(now) <= 60) {
System.out.println("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.");
return;
}
}
attempt = attempt + 1;
try {
rest.clearAllQueryParams();
} catch (ChilkatException e) {
System.out.println("Could not reset request parameters.");
return;
}
try {
rest.addQueryParam("Action", "AssumeRole");
} catch (ChilkatException e) {
System.out.println("Could not set Action.");
return;
}
try {
rest.addQueryParam("Version", "2011-06-15");
} catch (ChilkatException e) {
System.out.println("Could not set Version.");
return;
}
if (credentials.hasMember("session_token")) {
try {
rest.addQueryParam("X-Amz-Security-Token", credentials.stringOf("session_token"));
} catch (ChilkatException e) {
System.out.println("Could not set X-Amz-Security-Token.");
return;
}
}
try {
rest.addQueryParam("RoleArn", credentials.stringOf("role_arn"));
} catch (ChilkatException e) {
System.out.println("Could not set RoleArn.");
return;
}
try {
rest.addQueryParam("RoleSessionName", credentials.stringOf("role_session_name"));
} catch (ChilkatException e) {
System.out.println("Could not set RoleSessionName.");
return;
}
try {
rest.addQueryParam("DurationSeconds", "3600");
} catch (ChilkatException e) {
System.out.println("Could not set DurationSeconds.");
return;
}
try {
responseXml = rest.fullRequestFormUrlEncoded("POST", "/");
} catch (ChilkatException e) {
System.out.println("Transport failed; credential refresh was not published.");
return;
}
if (rest.getResponseStatusCode() == 200) {
received = true;
}
if (rest.getResponseStatusCode() != 200) {
retryable = false;
value = "";
try {
xml.loadXml(responseXml);
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
value = xml.getChildContent("Error|Code");
}
stringCompare.setString(value);
boolean stringMatch13 = stringCompare.contentsEqual("Throttling", true);
stringCompare.setString(value);
boolean stringMatch14 = stringCompare.contentsEqual("ThrottlingException", true);
if ((rest.getResponseStatusCode() == 429) || ((rest.getResponseStatusCode() == 500) || ((rest.getResponseStatusCode() == 502) || ((rest.getResponseStatusCode() == 503) || ((rest.getResponseStatusCode() == 504) || ((stringMatch13) || (stringMatch14))))))) {
retryable = true;
}
if ((!retryable) || (attempt == 3)) {
System.out.println("Refresh failed. HTTP status: " + rest.getResponseStatusCode());
System.out.println("AWS error code: " + value);
return;
}
connection.sleepMs(delayMs);
delayMs = delayMs * 2;
}
}
if (!received) {
System.out.println("Refresh attempts exhausted.");
return;
}
try {
xml.loadXml(responseXml);
} catch (ChilkatException e) {
System.out.println("Invalid STS XML response.");
return;
}
stringCompare.setString(xml.getTag());
boolean stringMatch15 = stringCompare.contentsEqual("AssumeRoleResponse", true);
if (!stringMatch15) {
System.out.println("Unexpected STS response root.");
return;
}
value = xml.getChildContent("ResponseMetadata|RequestId");
stringCompare.setString(value);
boolean stringMatch16 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch16)) {
System.out.println("Missing or empty ResponseMetadata|RequestId.");
return;
}
if (!xml.hasChildWithTag("AssumeRoleResult")) {
System.out.println("Missing STS result.");
return;
}
String accessKey = xml.getChildContent("AssumeRoleResult|Credentials|AccessKeyId");
stringCompare.setString(accessKey);
boolean stringMatch17 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch17)) {
System.out.println("Missing or empty AssumeRoleResult|Credentials|AccessKeyId.");
return;
}
String secretKey = xml.getChildContent("AssumeRoleResult|Credentials|SecretAccessKey");
stringCompare.setString(secretKey);
boolean stringMatch18 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch18)) {
System.out.println("Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.");
return;
}
String sessionToken = xml.getChildContent("AssumeRoleResult|Credentials|SessionToken");
stringCompare.setString(sessionToken);
boolean stringMatch19 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch19)) {
System.out.println("Missing or empty AssumeRoleResult|Credentials|SessionToken.");
return;
}
String expiration = xml.getChildContent("AssumeRoleResult|Credentials|Expiration");
stringCompare.setString(expiration);
boolean stringMatch20 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch20)) {
System.out.println("Missing or empty AssumeRoleResult|Credentials|Expiration.");
return;
}
try {
expires.setFromTimestamp(expiration);
} catch (ChilkatException e) {
System.out.println("Returned expiration is invalid.");
return;
}
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read current time.");
return;
}
if (expires.diffSeconds(now) <= 60) {
System.out.println("Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.");
return;
}
value = xml.getChildContent("AssumeRoleResult|AssumedRoleUser|Arn");
stringCompare.setString(value);
boolean stringMatch21 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch21)) {
System.out.println("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.");
return;
}
value = xml.getChildContent("AssumeRoleResult|AssumedRoleUser|AssumedRoleId");
stringCompare.setString(value);
boolean stringMatch22 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch22)) {
System.out.println("Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.");
return;
}
JsonObject session = new JsonObject();
try {
session.updateString("access_key", accessKey);
session.updateString("secret_key", secretKey);
session.updateString("session_token", sessionToken);
session.updateString("expiration", expiration);
} catch (ChilkatException e) {
System.out.println("Could not build complete session.");
return;
}
// Use session in memory; do not print or log session.Emit().
System.out.println("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.
JsonObject usable = new JsonObject();
usable.setStrict(true);
try {
usable.load(activeSnapshot);
} catch (ChilkatException e) {
System.out.println("Could not load the complete session snapshot.");
return;
}
// Pass usable to your service client here. Do not log activeSnapshot.
System.out.println("Session ready for the next unit of work; expiration: " + usable.stringOf("expiration"));
System.out.println("Example completed.");
}
}