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

AWS STS: Normalize STS Credentials and Use Chilkat.Rest

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.

Reads only private qa_data/tokens/aws_session_token.xml; no sts.json is needed. Accepts all seven credential-producing STS response roots, including the existing GetSessionToken/AssumeRole handoff. Builds a complete normalized in-memory session and uses it to sign GetCallerIdentity. The normalized fields are access_key, secret_key, session_token and expiration. Checks expiration with a 60-second margin before connecting. JWT-only GetWebIdentityToken responses are intentionally not credential sets.

AWS references: GetCallerIdentity

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.AuthAws;
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();
        // Load a privately stored STS XML response; never print its contents.
        Xml tokenXml = new Xml();
        tokenXml.setStrict(true);
        try {
            tokenXml.loadXmlFile("qa_data/tokens/aws_session_token.xml");
        } catch (ChilkatException e) {
            System.out.println("Could not load private STS XML.");
            return;
        }

        String credentialPath = "";
        stringCompare.setString(tokenXml.getTag());
        boolean stringMatch1 = stringCompare.contentsEqual("GetSessionTokenResponse", true);
        if (stringMatch1) {
            credentialPath = "GetSessionTokenResult|Credentials";
        }

        stringCompare.setString(tokenXml.getTag());
        boolean stringMatch2 = stringCompare.contentsEqual("AssumeRoleResponse", true);
        if (stringMatch2) {
            credentialPath = "AssumeRoleResult|Credentials";
        }

        stringCompare.setString(tokenXml.getTag());
        boolean stringMatch3 = stringCompare.contentsEqual("AssumeRoleWithWebIdentityResponse", true);
        if (stringMatch3) {
            credentialPath = "AssumeRoleWithWebIdentityResult|Credentials";
        }

        stringCompare.setString(tokenXml.getTag());
        boolean stringMatch4 = stringCompare.contentsEqual("AssumeRoleWithSAMLResponse", true);
        if (stringMatch4) {
            credentialPath = "AssumeRoleWithSAMLResult|Credentials";
        }

        stringCompare.setString(tokenXml.getTag());
        boolean stringMatch5 = stringCompare.contentsEqual("GetFederationTokenResponse", true);
        if (stringMatch5) {
            credentialPath = "GetFederationTokenResult|Credentials";
        }

        stringCompare.setString(tokenXml.getTag());
        boolean stringMatch6 = stringCompare.contentsEqual("GetDelegatedAccessTokenResponse", true);
        if (stringMatch6) {
            credentialPath = "GetDelegatedAccessTokenResult|Credentials";
        }

        stringCompare.setString(tokenXml.getTag());
        boolean stringMatch7 = stringCompare.contentsEqual("AssumeRootResponse", true);
        if (stringMatch7) {
            credentialPath = "AssumeRootResult|Credentials";
        }

        stringCompare.setString(credentialPath);
        boolean stringMatch8 = stringCompare.contentsEqual("", true);
        if (stringMatch8) {
            System.out.println("Unsupported STS credential response.");
            return;
        }

        StringBuilder path = new StringBuilder();
        try {
            path.setString(credentialPath);

            path.append("|AccessKeyId");
        } catch (ChilkatException e) {
            System.out.println("Could not construct credential path.");
            return;
        }

        String accessKey = tokenXml.getChildContent(path.getAsString());
        stringCompare.setString(accessKey);
        boolean stringMatch9 = stringCompare.contentsEqual("", true);
        if ((!tokenXml.getLastMethodSuccess()) || (stringMatch9)) {
            System.out.println("Missing credential field AccessKeyId.");
            return;
        }

        try {
            path.setString(credentialPath);

            path.append("|SecretAccessKey");
        } catch (ChilkatException e) {
            System.out.println("Could not construct credential path.");
            return;
        }

        String secretKey = tokenXml.getChildContent(path.getAsString());
        stringCompare.setString(secretKey);
        boolean stringMatch10 = stringCompare.contentsEqual("", true);
        if ((!tokenXml.getLastMethodSuccess()) || (stringMatch10)) {
            System.out.println("Missing credential field SecretAccessKey.");
            return;
        }

        try {
            path.setString(credentialPath);

            path.append("|SessionToken");
        } catch (ChilkatException e) {
            System.out.println("Could not construct credential path.");
            return;
        }

        String sessionToken = tokenXml.getChildContent(path.getAsString());
        stringCompare.setString(sessionToken);
        boolean stringMatch11 = stringCompare.contentsEqual("", true);
        if ((!tokenXml.getLastMethodSuccess()) || (stringMatch11)) {
            System.out.println("Missing credential field SessionToken.");
            return;
        }

        try {
            path.setString(credentialPath);

            path.append("|Expiration");
        } catch (ChilkatException e) {
            System.out.println("Could not construct credential path.");
            return;
        }

        String expiration = tokenXml.getChildContent(path.getAsString());
        stringCompare.setString(expiration);
        boolean stringMatch12 = stringCompare.contentsEqual("", true);
        if ((!tokenXml.getLastMethodSuccess()) || (stringMatch12)) {
            System.out.println("Missing credential field Expiration.");
            return;
        }

        DateTime expires = new DateTime();
        DateTime now = new DateTime();
        try {
            expires.setFromTimestamp(expiration);
        } catch (ChilkatException e) {
            System.out.println("Stored 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("Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.");
            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 normalized session.");
            return;
        }

        String region = "us-west-2";
        StringBuilder endpoint = new StringBuilder();
        endpoint.append("sts.");
        endpoint.append(region);
        endpoint.append(".amazonaws.com");
        AuthAws aws = new AuthAws();
        aws.setAccessKey(session.stringOf("access_key"));
        aws.setSecretKey(session.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 = "";
        try {
            rest.clearAllQueryParams();
        } catch (ChilkatException e) {
            System.out.println("Could not reset request parameters.");
            return;
        }

        try {
            rest.addQueryParam("Action", "GetCallerIdentity");
        } 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("X-Amz-Security-Token", session.stringOf("session_token"));
        } catch (ChilkatException e) {
            System.out.println("Could not set X-Amz-Security-Token.");
            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 stringMatch13 = stringCompare.contentsEqual("GetCallerIdentityResponse", true);
        if (!stringMatch13) {
            System.out.println("Unexpected STS response root.");
            return;
        }

        value = xml.getChildContent("ResponseMetadata|RequestId");
        stringCompare.setString(value);
        boolean stringMatch14 = stringCompare.contentsEqual("", true);
        if ((!xml.getLastMethodSuccess()) || (stringMatch14)) {
            System.out.println("Missing or empty ResponseMetadata|RequestId.");
            return;
        }

        if (!xml.hasChildWithTag("GetCallerIdentityResult")) {
            System.out.println("Missing STS result.");
            return;
        }

        value = xml.getChildContent("GetCallerIdentityResult|Arn");
        stringCompare.setString(value);
        boolean stringMatch15 = stringCompare.contentsEqual("", true);
        if ((!xml.getLastMethodSuccess()) || (stringMatch15)) {
            System.out.println("Missing or empty GetCallerIdentityResult|Arn.");
            return;
        }

        System.out.println("Authenticated principal: " + value);
        System.out.println("Example completed.");
    }
}