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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
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;
}
DateTime expires = new DateTime();
DateTime now = new DateTime();
String region = "us-west-2";
stringCompare.setString(credentials.stringOf("role_arn"));
boolean stringMatch1 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("role_arn") != 1) || (stringMatch1)) {
System.out.println("Missing or invalid role_arn.");
return;
}
stringCompare.setString(credentials.stringOf("role_session_name"));
boolean stringMatch2 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("role_session_name") != 1) || (stringMatch2)) {
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;
}
stringCompare.setString(credentials.stringOf("web_identity_token"));
boolean stringMatch3 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("web_identity_token") != 1) || (stringMatch3)) {
System.out.println("Missing or invalid web_identity_token.");
return;
}
StringBuilder endpoint = new StringBuilder();
endpoint.append("sts.");
endpoint.append(region);
endpoint.append(".amazonaws.com");
Rest rest = new Rest();
rest.setConnectTimeoutMs(20000);
rest.setIdleTimeoutMs(60000);
rest.setVerboseLogging(false);
// 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 = "";
try {
rest.clearAllQueryParams();
} catch (ChilkatException e) {
System.out.println("Could not reset request parameters.");
return;
}
try {
rest.addQueryParam("Action", "AssumeRoleWithWebIdentity");
} 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;
}
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 {
rest.addQueryParam("WebIdentityToken", credentials.stringOf("web_identity_token"));
} catch (ChilkatException e) {
System.out.println("Could not set WebIdentityToken.");
return;
}
try {
responseXml = rest.fullRequestFormUrlEncoded("POST", "/");
} catch (ChilkatException e) {
System.out.println("STS transport failed; inspect diagnostics privately.");
return;
}
if (rest.getResponseStatusCode() != 200) {
System.out.println("STS HTTP status: " + rest.getResponseStatusCode());
try {
xml.loadXml(responseXml);
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
value = xml.getChildContent("Error|Code");
if (value != null) {
System.out.println("AWS error code: " + value);
}
value = xml.getChildContent("RequestId");
if (value != null) {
System.out.println("AWS request ID: " + value);
}
}
return;
}
try {
xml.loadXml(responseXml);
} catch (ChilkatException e) {
System.out.println("Invalid STS XML response.");
return;
}
stringCompare.setString(xml.getTag());
boolean stringMatch4 = stringCompare.contentsEqual("AssumeRoleWithWebIdentityResponse", true);
if (!stringMatch4) {
System.out.println("Unexpected STS response root.");
return;
}
value = xml.getChildContent("ResponseMetadata|RequestId");
stringCompare.setString(value);
boolean stringMatch5 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch5)) {
System.out.println("Missing or empty ResponseMetadata|RequestId.");
return;
}
if (!xml.hasChildWithTag("AssumeRoleWithWebIdentityResult")) {
System.out.println("Missing STS result.");
return;
}
String accessKey = xml.getChildContent("AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId");
stringCompare.setString(accessKey);
boolean stringMatch6 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch6)) {
System.out.println("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId.");
return;
}
String secretKey = xml.getChildContent("AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey");
stringCompare.setString(secretKey);
boolean stringMatch7 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch7)) {
System.out.println("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey.");
return;
}
String sessionToken = xml.getChildContent("AssumeRoleWithWebIdentityResult|Credentials|SessionToken");
stringCompare.setString(sessionToken);
boolean stringMatch8 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch8)) {
System.out.println("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SessionToken.");
return;
}
String expiration = xml.getChildContent("AssumeRoleWithWebIdentityResult|Credentials|Expiration");
stringCompare.setString(expiration);
boolean stringMatch9 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch9)) {
System.out.println("Missing or empty AssumeRoleWithWebIdentityResult|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("AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn");
stringCompare.setString(value);
boolean stringMatch10 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch10)) {
System.out.println("Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn.");
return;
}
value = xml.getChildContent("AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId");
stringCompare.setString(value);
boolean stringMatch11 = stringCompare.contentsEqual("", true);
if ((!xml.getLastMethodSuccess()) || (stringMatch11)) {
System.out.println("Missing or empty AssumeRoleWithWebIdentityResult|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);
System.out.println("Example completed.");
}
}