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

Amazon Cognito: Validate a Cognito JWT

See more Amazon Cognito Examples

Validate an access token (default) or ID token using the configured pool's JWKS and Chilkat.Jwt/PublicKey. Explicitly allow RS256, select one matching kid, verify the signature, then check issuer, token_use, time claims, and the appropriate client claim: aud for ID tokens, client_id for access tokens. The access-token example also requires an exact scope. A JWT header or payload decoded before signature verification is untrusted.

This example targets the standard Cognito user-pool issuer and RS256 signing. If your pool uses another explicitly configured issuer/signing algorithm, adjust the allowlist and trusted configuration deliberately. Cache JWKS in production and refresh once on an unknown kid to handle rotation; never follow a token-supplied key URL. Verify any nonce you requested at sign-in, and any API-specific resource audience when using resource binding. Offline signature checks cannot detect token revocation or user disablement; enforce your API's revocation/session policy separately. M2M access tokens may not represent a user; this example validates user tokens.

Create qa_data/cognito/app.json with string fields region (for example us-west-2), user_pool_id, client_id, and account_key (your local account identifier). OAuth examples also require domain, the trusted HTTPS base URL of your Cognito domain, without a trailing slash. The region and user pool must match the app client. These examples use commercial AWS endpoints.

Sample cache/input files contain secrets. Use an access-controlled directory outside web content and source control, separate each local user/account, and serialize operations that modify the same cache. In a real application obtain passwords and codes through private UI instead of leaving them in files. Cache writes retain a .bak copy; protect and remove obsolete backups and challenge files after the flow. Production storage should provide atomic replacement and OS-backed secret protection. Never restore an old refresh token automatically after rotation. These examples do not require a hosted web server.

Checks transport completion, HTTP status, and required response fields before using results. Cognito often reports throttling, invalid codes, and authentication failures as HTTP 400. Present generic sign-in/recovery errors to users; keep detailed diagnostics private. Retry throttled reads with bounded backoff, but reconcile uncertain writes and refresh rotations before repeating them.

AWS documentation 1

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    //  App settings are trusted configuration. Keep a separate account_key/cache per local user.
    CkJsonObject app = new CkJsonObject();
    app.put_Strict(true);
    success = app.LoadFile("qa_data/cognito/app.json");
    if (success != true) {
        System.out.println("Could not load Cognito app settings.");
        return;
        }

    if ((app.JsonTypeOf("region") != 1) || (app.stringOf("region") == "")) {
        System.out.println("Missing or invalid region.");
        return;
        }

    if ((app.JsonTypeOf("user_pool_id") != 1) || (app.stringOf("user_pool_id") == "")) {
        System.out.println("Missing or invalid user_pool_id.");
        return;
        }

    if ((app.JsonTypeOf("client_id") != 1) || (app.stringOf("client_id") == "")) {
        System.out.println("Missing or invalid client_id.");
        return;
        }

    if ((app.JsonTypeOf("account_key") != 1) || (app.stringOf("account_key") == "")) {
        System.out.println("Missing or invalid account_key.");
        return;
        }

    String clientId = app.stringOf("client_id");
    CkStringBuilder endpoint = new CkStringBuilder();
    endpoint.Append("https://cognito-idp.");
    endpoint.Append(app.stringOf("region"));
    endpoint.Append(".amazonaws.com/");
    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    http.put_ConnectTimeout(20);
    http.put_ReadTimeout(60);
    CkHttpResponse resp = new CkHttpResponse();
    CkJsonObject body = new CkJsonObject();
    CkJsonObject result = new CkJsonObject();
    result.put_Strict(true);
    CkJsonObject cached = new CkJsonObject();
    cached.put_Strict(true);
    success = cached.LoadFile("qa_data/tokens/cognito-user.json");
    if (success != true) {
        System.out.println("Could not load qa_data/tokens/cognito-user.json.");
        return;
        }

    if ((cached.JsonTypeOf("client_id") != 1) || (cached.stringOf("client_id") == "")) {
        System.out.println("Missing or invalid client_id.");
        return;
        }

    if (cached.stringOf("client_id") != app.stringOf("client_id")) {
        System.out.println("Saved data belongs to another client, pool, or local account.");
        return;
        }

    if ((cached.JsonTypeOf("user_pool_id") != 1) || (cached.stringOf("user_pool_id") == "")) {
        System.out.println("Missing or invalid user_pool_id.");
        return;
        }

    if (cached.stringOf("user_pool_id") != app.stringOf("user_pool_id")) {
        System.out.println("Saved data belongs to another client, pool, or local account.");
        return;
        }

    if ((cached.JsonTypeOf("account_key") != 1) || (cached.stringOf("account_key") == "")) {
        System.out.println("Missing or invalid account_key.");
        return;
        }

    if (cached.stringOf("account_key") != app.stringOf("account_key")) {
        System.out.println("Saved data belongs to another client, pool, or local account.");
        return;
        }

    //  Choose the expected token type independently of the incoming JWT.
    String expectedUse = "access";
    String requiredScope = "aws.cognito.signin.user.admin";
    if ((expectedUse != "access") && (expectedUse != "id")) {
        System.out.println("Choose access or id.");
        return;
        }

    String encodedToken = cached.stringOf("access_token");
    if (expectedUse == "id") {
        encodedToken = cached.stringOf("id_token");
        }

    if (((expectedUse == "access") && (cached.JsonTypeOf("access_token") != 1)) || ((expectedUse == "id") && (cached.JsonTypeOf("id_token") != 1)) || (encodedToken == "")) {
        System.out.println("Missing JWT.");
        return;
        }

    CkJwt jwt = new CkJwt();
    CkJsonObject header = new CkJsonObject();
    header.put_Strict(true);
    success = header.Load(jwt.getHeader(encodedToken));
    if (success != true) {
        System.out.println("Invalid JWT header.");
        return;
        }

    if (header.stringOf("alg") != "RS256") {
        System.out.println("Expected RS256; do not trust the token algorithm without an allowlist.");
        return;
        }

    if ((header.JsonTypeOf("kid") != 1) || (header.stringOf("kid") == "")) {
        System.out.println("Missing or invalid kid.");
        return;
        }

    CkStringBuilder issuer = new CkStringBuilder();
    issuer.Append(endpoint.getAsString());
    issuer.Append(app.stringOf("user_pool_id"));
    CkStringBuilder jwksUrl = new CkStringBuilder();
    jwksUrl.Append(issuer.getAsString());
    jwksUrl.Append("/.well-known/jwks.json");
    //  Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
    success = http.HttpNoBody("GET",jwksUrl.getAsString(),resp);
    if (resp.get_StatusCode() != 200) {
        System.out.println("HTTP status: " + resp.get_StatusCode());
        success = result.Load(resp.bodyStr());
        if (success == true) {
            System.out.println("Error type: " + result.stringOf("__type"));
            System.out.println("OAuth error: " + result.stringOf("error"));
            }

        //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        return;
        }

    if (success != true) {
        System.out.println("The HTTP exchange did not complete.");
        return;
        }

    success = result.Load(resp.bodyStr());
    if (success != true) {
        System.out.println("Expected a JSON response.");
        return;
        }

    if (result.JsonTypeOf("keys") != 4) {
        System.out.println("Expected a JWKS keys array.");
        return;
        }

    int i = 0;
    int count = result.SizeOfArray("keys");
    int matches = 0;
    CkJsonObject jwk = new CkJsonObject();
    while (i < count) {
        result.put_I(i);
        if (result.stringOf("keys[i].kid") == header.stringOf("kid")) {
            matches = matches+1;
            success = result.ObjectOf2("keys[i]",jwk);
            if (success != true) {
                System.out.println("Could not read the matching key.");
                return;
                }

            }

        i = i+1;
        }

    if (matches != 1) {
        System.out.println("Expected exactly one matching signing key.");
        return;
        }

    if ((jwk.stringOf("kty") != "RSA") || (jwk.stringOf("use") != "sig") || (jwk.stringOf("alg") != "RS256")) {
        System.out.println("Unexpected signing-key type, use, or algorithm.");
        return;
        }

    CkPublicKey publicKey = new CkPublicKey();
    success = publicKey.LoadFromString(jwk.emit());
    if (success != true) {
        System.out.println("Could not load the RSA JWK.");
        return;
        }

    success = jwt.VerifyJwtPk(encodedToken,publicKey);
    if (success != true) {
        System.out.println("Invalid JWT signature.");
        return;
        }

    //  Only now inspect trusted claims. A valid signature alone is not sufficient.
    CkJsonObject claims = new CkJsonObject();
    claims.put_Strict(true);
    success = claims.Load(jwt.getPayload(encodedToken));
    if (success != true) {
        System.out.println("Invalid JWT claims.");
        return;
        }

    if (claims.stringOf("iss") != issuer.getAsString()) {
        System.out.println("JWT issuer mismatch.");
        return;
        }

    if (claims.stringOf("token_use") != expectedUse) {
        System.out.println("Wrong token purpose.");
        return;
        }

    if ((claims.JsonTypeOf("exp") != 2) || (claims.JsonTypeOf("iat") != 2)) {
        System.out.println("Missing numeric expiration or issue time.");
        return;
        }

    if (jwt.IsTimeValid(encodedToken,60) != true) {
        System.out.println("JWT is expired or not yet valid.");
        return;
        }

    if (expectedUse == "id") {
        if (claims.stringOf("aud") != clientId) {
            System.out.println("ID token audience mismatch.");
            return;
            }

        }
    else {
        if (claims.stringOf("client_id") != clientId) {
            System.out.println("Access token client mismatch.");
            return;
            }

        //  Whole-word scope matching, not a substring match.
        CkStringBuilder scopes = new CkStringBuilder();
        scopes.Append(" ");
        scopes.Append(claims.stringOf("scope"));
        scopes.Append(" ");
        CkStringBuilder wantedScope = new CkStringBuilder();
        wantedScope.Append(" ");
        wantedScope.Append(requiredScope);
        wantedScope.Append(" ");
        if ((requiredScope != "") && (scopes.Contains(wantedScope.getAsString(),true) != true)) {
            System.out.println("Required scope is absent.");
            return;
            }

        }

    if ((claims.JsonTypeOf("sub") != 1) || (claims.stringOf("sub") == "")) {
        System.out.println("Missing or invalid sub.");
        return;
        }

    System.out.println("JWT signature and required claims are valid.");
    //  Apply your application's authorization policy before granting access.
  }
}