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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var 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.
final app = CkJsonObject();
app.strict = true;
try {
app.loadFile('qa_data/cognito/app.json');
} on ChilkatException {
print('Could not load Cognito app settings.');
return;
}
if ((app.jsonTypeOf('region') != 1) || (app.stringOf('region') == '')) {
print('Missing or invalid region.');
return;
}
if ((app.jsonTypeOf('user_pool_id') != 1) || (app.stringOf('user_pool_id') == '')) {
print('Missing or invalid user_pool_id.');
return;
}
if ((app.jsonTypeOf('client_id') != 1) || (app.stringOf('client_id') == '')) {
print('Missing or invalid client_id.');
return;
}
if ((app.jsonTypeOf('account_key') != 1) || (app.stringOf('account_key') == '')) {
print('Missing or invalid account_key.');
return;
}
final clientId = app.stringOf('client_id');
final endpoint = CkStringBuilder();
endpoint.append('https://cognito-idp.');
endpoint.append(app.stringOf('region'));
endpoint.append('.amazonaws.com/');
final http = CkHttp();
http.requireSslCertVerify = true;
http.followRedirects = false;
http.connectTimeout = 20;
http.readTimeout = 60;
final resp = CkHttpResponse();
final body = CkJsonObject();
final result = CkJsonObject();
result.strict = true;
final cached = CkJsonObject();
cached.strict = true;
try {
cached.loadFile('qa_data/tokens/cognito-user.json');
} on ChilkatException {
print('Could not load qa_data/tokens/cognito-user.json.');
return;
}
if ((cached.jsonTypeOf('client_id') != 1) || (cached.stringOf('client_id') == '')) {
print('Missing or invalid client_id.');
return;
}
if (cached.stringOf('client_id') != app.stringOf('client_id')) {
print('Saved data belongs to another client, pool, or local account.');
return;
}
if ((cached.jsonTypeOf('user_pool_id') != 1) || (cached.stringOf('user_pool_id') == '')) {
print('Missing or invalid user_pool_id.');
return;
}
if (cached.stringOf('user_pool_id') != app.stringOf('user_pool_id')) {
print('Saved data belongs to another client, pool, or local account.');
return;
}
if ((cached.jsonTypeOf('account_key') != 1) || (cached.stringOf('account_key') == '')) {
print('Missing or invalid account_key.');
return;
}
if (cached.stringOf('account_key') != app.stringOf('account_key')) {
print('Saved data belongs to another client, pool, or local account.');
return;
}
// Choose the expected token type independently of the incoming JWT.
final expectedUse = 'access';
final requiredScope = 'aws.cognito.signin.user.admin';
if ((expectedUse != 'access') && (expectedUse != 'id')) {
print('Choose access or id.');
return;
}
var 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 == ''))) {
print('Missing JWT.');
return;
}
final jwt = CkJwt();
final header = CkJsonObject();
header.strict = true;
try {
header.load(jwt.getHeader(encodedToken));
} on ChilkatException {
print('Invalid JWT header.');
return;
}
if (header.stringOf('alg') != 'RS256') {
print('Expected RS256; do not trust the token algorithm without an allowlist.');
return;
}
if ((header.jsonTypeOf('kid') != 1) || (header.stringOf('kid') == '')) {
print('Missing or invalid kid.');
return;
}
final issuer = CkStringBuilder();
issuer.append(endpoint.getAsString());
issuer.append(app.stringOf('user_pool_id'));
final jwksUrl = 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 = true;
try {
http.httpNoBody('GET', jwksUrl.getAsString(), resp);
} on ChilkatException {
success = false;
}
if (resp.statusCode != 200) {
print('HTTP status: ${resp.statusCode}');
try {
result.load(resp.bodyStr);
print('Error type: ${result.stringOf('__type')}');
print('OAuth error: ${result.stringOf('error')}');
} on ChilkatException {
// result.load() failed; continue anyway.
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (!success) {
print('The HTTP exchange did not complete.');
return;
}
try {
result.load(resp.bodyStr);
} on ChilkatException {
print('Expected a JSON response.');
return;
}
if (result.jsonTypeOf('keys') != 4) {
print('Expected a JWKS keys array.');
return;
}
var i = 0;
final count = result.sizeOfArray('keys');
var matches = 0;
final jwk = CkJsonObject();
while (i < count) {
result.i = i;
if (result.stringOf('keys[i].kid') == header.stringOf('kid')) {
matches++;
try {
result.objectOf2('keys[i]', jwk);
} on ChilkatException {
print('Could not read the matching key.');
return;
}
}
i++;
}
if (matches != 1) {
print('Expected exactly one matching signing key.');
return;
}
if ((jwk.stringOf('kty') != 'RSA') || ((jwk.stringOf('use') != 'sig') || (jwk.stringOf('alg') != 'RS256'))) {
print('Unexpected signing-key type, use, or algorithm.');
return;
}
final publicKey = CkPublicKey();
try {
publicKey.loadFromString(jwk.emit());
} on ChilkatException {
print('Could not load the RSA JWK.');
return;
}
try {
jwt.verifyJwtPk(encodedToken, publicKey);
} on ChilkatException {
print('Invalid JWT signature.');
return;
}
// Only now inspect trusted claims. A valid signature alone is not sufficient.
final claims = CkJsonObject();
claims.strict = true;
try {
claims.load(jwt.getPayload(encodedToken));
} on ChilkatException {
print('Invalid JWT claims.');
return;
}
if (claims.stringOf('iss') != issuer.getAsString()) {
print('JWT issuer mismatch.');
return;
}
if (claims.stringOf('token_use') != expectedUse) {
print('Wrong token purpose.');
return;
}
if ((claims.jsonTypeOf('exp') != 2) || (claims.jsonTypeOf('iat') != 2)) {
print('Missing numeric expiration or issue time.');
return;
}
if (!jwt.isTimeValid(encodedToken, 60)) {
print('JWT is expired or not yet valid.');
return;
}
if (expectedUse == 'id') {
if (claims.stringOf('aud') != clientId) {
print('ID token audience mismatch.');
return;
}
} else {
if (claims.stringOf('client_id') != clientId) {
print('Access token client mismatch.');
return;
}
// Whole-word scope matching, not a substring match.
final scopes = CkStringBuilder();
scopes.append(' ');
scopes.append(claims.stringOf('scope'));
scopes.append(' ');
final wantedScope = CkStringBuilder();
wantedScope.append(' ');
wantedScope.append(requiredScope);
wantedScope.append(' ');
if ((requiredScope != '') && (!scopes.contains(wantedScope.getAsString(), true))) {
print('Required scope is absent.');
return;
}
}
if ((claims.jsonTypeOf('sub') != 1) || (claims.stringOf('sub') == '')) {
print('Missing or invalid sub.');
return;
}
print('JWT signature and required claims are valid.');
// Apply your application's authorization policy before granting access.
}