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 Unicode C++ Downloads
#include <CkJsonObjectW.h>
#include <CkStringBuilderW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkJwtW.h>
#include <CkPublicKeyW.h>
void ChilkatSample(void)
{
bool 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.
CkJsonObjectW app;
app.put_Strict(true);
success = app.LoadFile(L"qa_data/cognito/app.json");
if (success != true) {
wprintf(L"Could not load Cognito app settings.\n");
return;
}
if ((app.JsonTypeOf(L"region") != 1) || (app.stringOf(L"region") == L"")) {
wprintf(L"Missing or invalid region.\n");
return;
}
if ((app.JsonTypeOf(L"user_pool_id") != 1) || (app.stringOf(L"user_pool_id") == L"")) {
wprintf(L"Missing or invalid user_pool_id.\n");
return;
}
if ((app.JsonTypeOf(L"client_id") != 1) || (app.stringOf(L"client_id") == L"")) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
if ((app.JsonTypeOf(L"account_key") != 1) || (app.stringOf(L"account_key") == L"")) {
wprintf(L"Missing or invalid account_key.\n");
return;
}
const wchar_t *clientId = app.stringOf(L"client_id");
CkStringBuilderW endpoint;
endpoint.Append(L"https://cognito-idp.");
endpoint.Append(app.stringOf(L"region"));
endpoint.Append(L".amazonaws.com/");
CkHttpW http;
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(20);
http.put_ReadTimeout(60);
CkHttpResponseW resp;
CkJsonObjectW body;
CkJsonObjectW result;
result.put_Strict(true);
CkJsonObjectW cached;
cached.put_Strict(true);
success = cached.LoadFile(L"qa_data/tokens/cognito-user.json");
if (success != true) {
wprintf(L"Could not load qa_data/tokens/cognito-user.json.\n");
return;
}
if ((cached.JsonTypeOf(L"client_id") != 1) || (cached.stringOf(L"client_id") == L"")) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
if (cached.stringOf(L"client_id") != app.stringOf(L"client_id")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
if ((cached.JsonTypeOf(L"user_pool_id") != 1) || (cached.stringOf(L"user_pool_id") == L"")) {
wprintf(L"Missing or invalid user_pool_id.\n");
return;
}
if (cached.stringOf(L"user_pool_id") != app.stringOf(L"user_pool_id")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
if ((cached.JsonTypeOf(L"account_key") != 1) || (cached.stringOf(L"account_key") == L"")) {
wprintf(L"Missing or invalid account_key.\n");
return;
}
if (cached.stringOf(L"account_key") != app.stringOf(L"account_key")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
// Choose the expected token type independently of the incoming JWT.
const wchar_t *expectedUse = L"access";
const wchar_t *requiredScope = L"aws.cognito.signin.user.admin";
if ((expectedUse != L"access") && (expectedUse != L"id")) {
wprintf(L"Choose access or id.\n");
return;
}
const wchar_t *encodedToken = cached.stringOf(L"access_token");
if (expectedUse == L"id") {
encodedToken = cached.stringOf(L"id_token");
}
if (((expectedUse == L"access") && (cached.JsonTypeOf(L"access_token") != 1)) || ((expectedUse == L"id") && (cached.JsonTypeOf(L"id_token") != 1)) || (encodedToken == L"")) {
wprintf(L"Missing JWT.\n");
return;
}
CkJwtW jwt;
CkJsonObjectW header;
header.put_Strict(true);
success = header.Load(jwt.getHeader(encodedToken));
if (success != true) {
wprintf(L"Invalid JWT header.\n");
return;
}
if (header.stringOf(L"alg") != L"RS256") {
wprintf(L"Expected RS256; do not trust the token algorithm without an allowlist.\n");
return;
}
if ((header.JsonTypeOf(L"kid") != 1) || (header.stringOf(L"kid") == L"")) {
wprintf(L"Missing or invalid kid.\n");
return;
}
CkStringBuilderW issuer;
issuer.Append(endpoint.getAsString());
issuer.Append(app.stringOf(L"user_pool_id"));
CkStringBuilderW jwksUrl;
jwksUrl.Append(issuer.getAsString());
jwksUrl.Append(L"/.well-known/jwks.json");
// Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
success = http.HttpNoBody(L"GET",jwksUrl.getAsString(),resp);
if (resp.get_StatusCode() != 200) {
wprintf(L"HTTP status: %d\n",resp.get_StatusCode());
success = result.Load(resp.bodyStr());
if (success == true) {
wprintf(L"Error type: %s\n",result.stringOf(L"__type"));
wprintf(L"OAuth error: %s\n",result.stringOf(L"error"));
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (success != true) {
wprintf(L"The HTTP exchange did not complete.\n");
return;
}
success = result.Load(resp.bodyStr());
if (success != true) {
wprintf(L"Expected a JSON response.\n");
return;
}
if (result.JsonTypeOf(L"keys") != 4) {
wprintf(L"Expected a JWKS keys array.\n");
return;
}
int i = 0;
int count = result.SizeOfArray(L"keys");
int matches = 0;
CkJsonObjectW jwk;
while (i < count) {
result.put_I(i);
if (result.stringOf(L"keys[i].kid") == header.stringOf(L"kid")) {
matches = matches + 1;
success = result.ObjectOf2(L"keys[i]",jwk);
if (success != true) {
wprintf(L"Could not read the matching key.\n");
return;
}
}
i = i + 1;
}
if (matches != 1) {
wprintf(L"Expected exactly one matching signing key.\n");
return;
}
if ((jwk.stringOf(L"kty") != L"RSA") || (jwk.stringOf(L"use") != L"sig") || (jwk.stringOf(L"alg") != L"RS256")) {
wprintf(L"Unexpected signing-key type, use, or algorithm.\n");
return;
}
CkPublicKeyW publicKey;
success = publicKey.LoadFromString(jwk.emit());
if (success != true) {
wprintf(L"Could not load the RSA JWK.\n");
return;
}
success = jwt.VerifyJwtPk(encodedToken,publicKey);
if (success != true) {
wprintf(L"Invalid JWT signature.\n");
return;
}
// Only now inspect trusted claims. A valid signature alone is not sufficient.
CkJsonObjectW claims;
claims.put_Strict(true);
success = claims.Load(jwt.getPayload(encodedToken));
if (success != true) {
wprintf(L"Invalid JWT claims.\n");
return;
}
if (claims.stringOf(L"iss") != issuer.getAsString()) {
wprintf(L"JWT issuer mismatch.\n");
return;
}
if (claims.stringOf(L"token_use") != expectedUse) {
wprintf(L"Wrong token purpose.\n");
return;
}
if ((claims.JsonTypeOf(L"exp") != 2) || (claims.JsonTypeOf(L"iat") != 2)) {
wprintf(L"Missing numeric expiration or issue time.\n");
return;
}
if (jwt.IsTimeValid(encodedToken,60) != true) {
wprintf(L"JWT is expired or not yet valid.\n");
return;
}
if (expectedUse == L"id") {
if (claims.stringOf(L"aud") != clientId) {
wprintf(L"ID token audience mismatch.\n");
return;
}
}
else {
if (claims.stringOf(L"client_id") != clientId) {
wprintf(L"Access token client mismatch.\n");
return;
}
// Whole-word scope matching, not a substring match.
CkStringBuilderW scopes;
scopes.Append(L" ");
scopes.Append(claims.stringOf(L"scope"));
scopes.Append(L" ");
CkStringBuilderW wantedScope;
wantedScope.Append(L" ");
wantedScope.Append(requiredScope);
wantedScope.Append(L" ");
if ((requiredScope != L"") && (scopes.Contains(wantedScope.getAsString(),true) != true)) {
wprintf(L"Required scope is absent.\n");
return;
}
}
if ((claims.JsonTypeOf(L"sub") != 1) || (claims.stringOf(L"sub") == L"")) {
wprintf(L"Missing or invalid sub.\n");
return;
}
wprintf(L"JWT signature and required claims are valid.\n");
// Apply your application's authorization policy before granting access.
}