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.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Jwt;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.StringBuilder;
public class ChilkatExample {
public static void main(String[] args) {
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.
JsonObject app = new JsonObject();
app.setStrict(true);
try {
app.loadFile("qa_data/cognito/app.json");
} catch (ChilkatException e) {
System.out.println("Could not load Cognito app settings.");
return;
}
if ((app.jsonTypeOf("region") != 1) || ("".equals(app.stringOf("region")))) {
System.out.println("Missing or invalid region.");
return;
}
if ((app.jsonTypeOf("user_pool_id") != 1) || ("".equals(app.stringOf("user_pool_id")))) {
System.out.println("Missing or invalid user_pool_id.");
return;
}
if ((app.jsonTypeOf("client_id") != 1) || ("".equals(app.stringOf("client_id")))) {
System.out.println("Missing or invalid client_id.");
return;
}
if ((app.jsonTypeOf("account_key") != 1) || ("".equals(app.stringOf("account_key")))) {
System.out.println("Missing or invalid account_key.");
return;
}
String clientId = app.stringOf("client_id");
StringBuilder endpoint = new StringBuilder();
endpoint.append("https://cognito-idp.");
endpoint.append(app.stringOf("region"));
endpoint.append(".amazonaws.com/");
Http http = new Http();
http.setRequireSslCertVerify(true);
http.setFollowRedirects(false);
http.setConnectTimeout(20);
http.setReadTimeout(60);
HttpResponse resp = new HttpResponse();
JsonObject body = new JsonObject();
JsonObject result = new JsonObject();
result.setStrict(true);
JsonObject cached = new JsonObject();
cached.setStrict(true);
try {
cached.loadFile("qa_data/tokens/cognito-user.json");
} catch (ChilkatException e) {
System.out.println("Could not load qa_data/tokens/cognito-user.json.");
return;
}
if ((cached.jsonTypeOf("client_id") != 1) || ("".equals(cached.stringOf("client_id")))) {
System.out.println("Missing or invalid client_id.");
return;
}
if (!cached.stringOf("client_id").equals(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) || ("".equals(cached.stringOf("user_pool_id")))) {
System.out.println("Missing or invalid user_pool_id.");
return;
}
if (!cached.stringOf("user_pool_id").equals(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) || ("".equals(cached.stringOf("account_key")))) {
System.out.println("Missing or invalid account_key.");
return;
}
if (!cached.stringOf("account_key").equals(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 ((!"access".equals(expectedUse)) && (!"id".equals(expectedUse))) {
System.out.println("Choose access or id.");
return;
}
String encodedToken = cached.stringOf("access_token");
if ("id".equals(expectedUse)) {
encodedToken = cached.stringOf("id_token");
}
if ((("access".equals(expectedUse)) && (cached.jsonTypeOf("access_token") != 1)) || ((("id".equals(expectedUse)) && (cached.jsonTypeOf("id_token") != 1)) || ("".equals(encodedToken)))) {
System.out.println("Missing JWT.");
return;
}
Jwt jwt = new Jwt();
JsonObject header = new JsonObject();
header.setStrict(true);
try {
header.load(jwt.getHeader(encodedToken));
} catch (ChilkatException e) {
System.out.println("Invalid JWT header.");
return;
}
if (!"RS256".equals(header.stringOf("alg"))) {
System.out.println("Expected RS256; do not trust the token algorithm without an allowlist.");
return;
}
if ((header.jsonTypeOf("kid") != 1) || ("".equals(header.stringOf("kid")))) {
System.out.println("Missing or invalid kid.");
return;
}
StringBuilder issuer = new StringBuilder();
issuer.append(endpoint.getAsString());
issuer.append(app.stringOf("user_pool_id"));
StringBuilder jwksUrl = new StringBuilder();
jwksUrl.append(issuer.getAsString());
jwksUrl.append("/.well-known/jwks.json");
// Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
http.httpNoBody("GET", jwksUrl.getAsString(), resp);
if (resp.getStatusCode() != 200) {
System.out.println("HTTP status: " + resp.getStatusCode());
try {
result.load(resp.getBodyStr());
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
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) {
System.out.println("The HTTP exchange did not complete.");
return;
}
try {
result.load(resp.getBodyStr());
} catch (ChilkatException e) {
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;
JsonObject jwk = new JsonObject();
while (i < count) {
result.setI(i);
if (result.stringOf("keys[i].kid").equals(header.stringOf("kid"))) {
matches = matches + 1;
try {
result.objectOf2("keys[i]", jwk);
} catch (ChilkatException e) {
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 ((!"RSA".equals(jwk.stringOf("kty"))) || ((!"sig".equals(jwk.stringOf("use"))) || (!"RS256".equals(jwk.stringOf("alg"))))) {
System.out.println("Unexpected signing-key type, use, or algorithm.");
return;
}
PublicKey publicKey = new PublicKey();
try {
publicKey.loadFromString(jwk.emit());
} catch (ChilkatException e) {
System.out.println("Could not load the RSA JWK.");
return;
}
try {
jwt.verifyJwtPk(encodedToken, publicKey);
} catch (ChilkatException e) {
System.out.println("Invalid JWT signature.");
return;
}
// Only now inspect trusted claims. A valid signature alone is not sufficient.
JsonObject claims = new JsonObject();
claims.setStrict(true);
try {
claims.load(jwt.getPayload(encodedToken));
} catch (ChilkatException e) {
System.out.println("Invalid JWT claims.");
return;
}
if (!claims.stringOf("iss").equals(issuer.getAsString())) {
System.out.println("JWT issuer mismatch.");
return;
}
if (!claims.stringOf("token_use").equals(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)) {
System.out.println("JWT is expired or not yet valid.");
return;
}
if ("id".equals(expectedUse)) {
if (!claims.stringOf("aud").equals(clientId)) {
System.out.println("ID token audience mismatch.");
return;
}
} else {
if (!claims.stringOf("client_id").equals(clientId)) {
System.out.println("Access token client mismatch.");
return;
}
// Whole-word scope matching, not a substring match.
StringBuilder scopes = new StringBuilder();
scopes.append(" ");
scopes.append(claims.stringOf("scope"));
scopes.append(" ");
StringBuilder wantedScope = new StringBuilder();
wantedScope.append(" ");
wantedScope.append(requiredScope);
wantedScope.append(" ");
if ((!"".equals(requiredScope)) && (!scopes.contains(wantedScope.getAsString(), true))) {
System.out.println("Required scope is absent.");
return;
}
}
if ((claims.jsonTypeOf("sub") != 1) || ("".equals(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.
}
}