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

Java
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Hashtable;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Socket;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.StringTable;
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("audience"));
        boolean stringMatch5 = stringCompare.contentsEqual("", true);
        if ((credentials.jsonTypeOf("audience") != 1) || (stringMatch5)) {
            System.out.println("Missing or invalid audience.");
            return;
        }

        // Use AWSIdentity by default. OriginIdentity requires trusted propagation context.
        String subjectMode = "AWSIdentity";
        if (credentials.hasMember("subject_mode")) {
            stringCompare.setString(credentials.stringOf("subject_mode"));
            boolean stringMatch6 = stringCompare.contentsEqual("", true);
            if ((credentials.jsonTypeOf("subject_mode") != 1) || (stringMatch6)) {
                System.out.println("Missing or invalid subject_mode.");
                return;
            }

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

        stringCompare.setString(subjectMode);
        boolean stringMatch7 = stringCompare.contentsEqual("AWSIdentity", true);
        stringCompare.setString(subjectMode);
        boolean stringMatch8 = stringCompare.contentsEqual("OriginIdentity", true);
        if ((!stringMatch7) && (!stringMatch8)) {
            System.out.println("Invalid subject_mode.");
            return;
        }

        if (credentials.hasMember("scope")) {
            stringCompare.setString(credentials.stringOf("scope"));
            boolean stringMatch9 = stringCompare.contentsEqual("", true);
            if ((credentials.jsonTypeOf("scope") != 1) || (stringMatch9)) {
                System.out.println("Missing or invalid scope.");
                return;
            }

            stringCompare.setString(subjectMode);
            boolean stringMatch10 = stringCompare.contentsEqual("OriginIdentity", true);
            if (!stringMatch10) {
                System.out.println("scope requires OriginIdentity.");
                return;
            }

            StringBuilder scopeText = new StringBuilder();
            scopeText.append(credentials.stringOf("scope"));
            if ((scopeText.getLength() > 256) || ((scopeText.startsWith(" ", true)) || ((scopeText.endsWith(" ", true)) || (scopeText.contains("  ", true))))) {
                System.out.println("Invalid scope length or spacing.");
                return;
            }

            StringBuilder allowedScope = new StringBuilder();
            allowedScope.append("!#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~ ");
            int scopeIndex = 0;
            while (scopeIndex < scopeText.getLength()) {
                if (!allowedScope.contains(scopeText.getRange(scopeIndex, 1, false), true)) {
                    System.out.println("Invalid scope character.");
                    return;
                }

                scopeIndex = scopeIndex + 1;
            }

            StringTable scopeValues = new StringTable();
            try {
                scopeValues.splitAndAppend(scopeText.getAsString(), " ", false, false);
            } catch (ChilkatException e) {
                System.out.println("Could not split scope values.");
                return;
            }

            Hashtable seenScopes = new Hashtable();
            scopeIndex = 0;
            String scopeValue = "";
            while (scopeIndex < scopeValues.getCount()) {
                scopeValue = scopeValues.stringAt(scopeIndex);
                if (seenScopes.contains(scopeValue)) {
                    System.out.println("Duplicate scope value.");
                    return;
                }

                try {
                    seenScopes.addStr(scopeValue, "seen");
                } catch (ChilkatException e) {
                    System.out.println("Could not track scope values.");
                    return;
                }

                scopeIndex = scopeIndex + 1;
            }
        }

        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 = "";
        try {
            rest.clearAllQueryParams();
        } catch (ChilkatException e) {
            System.out.println("Could not reset request parameters.");
            return;
        }

        try {
            rest.addQueryParam("Action", "GetWebIdentityToken");
        } 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("Audience.member.1", credentials.stringOf("audience"));
        } catch (ChilkatException e) {
            System.out.println("Could not set Audience.member.1.");
            return;
        }

        try {
            rest.addQueryParam("SigningAlgorithm", "RS256");
        } catch (ChilkatException e) {
            System.out.println("Could not set SigningAlgorithm.");
            return;
        }

        try {
            rest.addQueryParam("DurationSeconds", "300");
        } catch (ChilkatException e) {
            System.out.println("Could not set DurationSeconds.");
            return;
        }

        try {
            rest.addQueryParam("SubjectMode", subjectMode);
        } catch (ChilkatException e) {
            System.out.println("Could not set SubjectMode.");
            return;
        }

        if (credentials.hasMember("scope")) {
            try {
                rest.addQueryParam("Scope", credentials.stringOf("scope"));
            } catch (ChilkatException e) {
                System.out.println("Could not set Scope.");
                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 stringMatch11 = stringCompare.contentsEqual("GetWebIdentityTokenResponse", true);
        if (!stringMatch11) {
            System.out.println("Unexpected STS response root.");
            return;
        }

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

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

        String sessionToken = xml.getChildContent("GetWebIdentityTokenResult|WebIdentityToken");
        stringCompare.setString(sessionToken);
        boolean stringMatch13 = stringCompare.contentsEqual("", true);
        if ((!xml.getLastMethodSuccess()) || (stringMatch13)) {
            System.out.println("Missing or empty GetWebIdentityTokenResult|WebIdentityToken.");
            return;
        }

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

        try {
            expires.setFromTimestamp(expiration);
        } catch (ChilkatException e) {
            System.out.println("JWT 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("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.
        System.out.println("Web identity token obtained; expiration: " + expiration);
        System.out.println("Example completed.");
    }
}