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 Objective-C Downloads
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoJwt.h>
#import <CkoPublicKey.h>
BOOL success = NO;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
// App settings are trusted configuration. Keep a separate account_key/cache per local user.
CkoJsonObject *app = [[CkoJsonObject alloc] init];
app.Strict = YES;
success = [app LoadFile: @"qa_data/cognito/app.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load Cognito app settings.");
return;
}
if (([[app JsonTypeOf: @"region"] intValue] != 1) || ([app StringOf: @"region"] == @"")) {
NSLog(@"%@",@"Missing or invalid region.");
return;
}
if (([[app JsonTypeOf: @"user_pool_id"] intValue] != 1) || ([app StringOf: @"user_pool_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid user_pool_id.");
return;
}
if (([[app JsonTypeOf: @"client_id"] intValue] != 1) || ([app StringOf: @"client_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid client_id.");
return;
}
if (([[app JsonTypeOf: @"account_key"] intValue] != 1) || ([app StringOf: @"account_key"] == @"")) {
NSLog(@"%@",@"Missing or invalid account_key.");
return;
}
NSString *clientId = [app StringOf: @"client_id"];
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"https://cognito-idp."];
[endpoint Append: [app StringOf: @"region"]];
[endpoint Append: @".amazonaws.com/"];
CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:60];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *body = [[CkoJsonObject alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
CkoJsonObject *cached = [[CkoJsonObject alloc] init];
cached.Strict = YES;
success = [cached LoadFile: @"qa_data/tokens/cognito-user.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load qa_data/tokens/cognito-user.json.");
return;
}
if (([[cached JsonTypeOf: @"client_id"] intValue] != 1) || ([cached StringOf: @"client_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid client_id.");
return;
}
if ([cached StringOf: @"client_id"] != [app StringOf: @"client_id"]) {
NSLog(@"%@",@"Saved data belongs to another client, pool, or local account.");
return;
}
if (([[cached JsonTypeOf: @"user_pool_id"] intValue] != 1) || ([cached StringOf: @"user_pool_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid user_pool_id.");
return;
}
if ([cached StringOf: @"user_pool_id"] != [app StringOf: @"user_pool_id"]) {
NSLog(@"%@",@"Saved data belongs to another client, pool, or local account.");
return;
}
if (([[cached JsonTypeOf: @"account_key"] intValue] != 1) || ([cached StringOf: @"account_key"] == @"")) {
NSLog(@"%@",@"Missing or invalid account_key.");
return;
}
if ([cached StringOf: @"account_key"] != [app StringOf: @"account_key"]) {
NSLog(@"%@",@"Saved data belongs to another client, pool, or local account.");
return;
}
// Choose the expected token type independently of the incoming JWT.
NSString *expectedUse = @"access";
NSString *requiredScope = @"aws.cognito.signin.user.admin";
if ((expectedUse != @"access") && (expectedUse != @"id")) {
NSLog(@"%@",@"Choose access or id.");
return;
}
NSString *encodedToken = [cached StringOf: @"access_token"];
if (expectedUse == @"id") {
encodedToken = [cached StringOf: @"id_token"];
}
if (((expectedUse == @"access") && ([[cached JsonTypeOf: @"access_token"] intValue] != 1)) || ((expectedUse == @"id") && ([[cached JsonTypeOf: @"id_token"] intValue] != 1)) || (encodedToken == @"")) {
NSLog(@"%@",@"Missing JWT.");
return;
}
CkoJwt *jwt = [[CkoJwt alloc] init];
CkoJsonObject *header = [[CkoJsonObject alloc] init];
header.Strict = YES;
success = [header Load: [jwt GetHeader: encodedToken]];
if (success != YES) {
NSLog(@"%@",@"Invalid JWT header.");
return;
}
if ([header StringOf: @"alg"] != @"RS256") {
NSLog(@"%@",@"Expected RS256; do not trust the token algorithm without an allowlist.");
return;
}
if (([[header JsonTypeOf: @"kid"] intValue] != 1) || ([header StringOf: @"kid"] == @"")) {
NSLog(@"%@",@"Missing or invalid kid.");
return;
}
CkoStringBuilder *issuer = [[CkoStringBuilder alloc] init];
[issuer Append: [endpoint GetAsString]];
[issuer Append: [app StringOf: @"user_pool_id"]];
CkoStringBuilder *jwksUrl = [[CkoStringBuilder alloc] init];
[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" url: [jwksUrl GetAsString] response: resp];
if ([resp.StatusCode intValue] != 200) {
NSLog(@"%@%d",@"HTTP status: ",[resp.StatusCode intValue]);
success = [result Load: resp.BodyStr];
if (success == YES) {
NSLog(@"%@%@",@"Error type: ",[result StringOf: @"__type"]);
NSLog(@"%@%@",@"OAuth error: ",[result StringOf: @"error"]);
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (success != YES) {
NSLog(@"%@",@"The HTTP exchange did not complete.");
return;
}
success = [result Load: resp.BodyStr];
if (success != YES) {
NSLog(@"%@",@"Expected a JSON response.");
return;
}
if ([[result JsonTypeOf: @"keys"] intValue] != 4) {
NSLog(@"%@",@"Expected a JWKS keys array.");
return;
}
int i = 0;
int count = [[result SizeOfArray: @"keys"] intValue];
int matches = 0;
CkoJsonObject *jwk = [[CkoJsonObject alloc] init];
while (i < count) {
result.I = [NSNumber numberWithInt: i];
if ([result StringOf: @"keys[i].kid"] == [header StringOf: @"kid"]) {
matches = matches + 1;
success = [result ObjectOf2: @"keys[i]" jsonObj: jwk];
if (success != YES) {
NSLog(@"%@",@"Could not read the matching key.");
return;
}
}
i = i + 1;
}
if (matches != 1) {
NSLog(@"%@",@"Expected exactly one matching signing key.");
return;
}
if (([jwk StringOf: @"kty"] != @"RSA") || ([jwk StringOf: @"use"] != @"sig") || ([jwk StringOf: @"alg"] != @"RS256")) {
NSLog(@"%@",@"Unexpected signing-key type, use, or algorithm.");
return;
}
CkoPublicKey *publicKey = [[CkoPublicKey alloc] init];
success = [publicKey LoadFromString: [jwk Emit]];
if (success != YES) {
NSLog(@"%@",@"Could not load the RSA JWK.");
return;
}
success = [jwt VerifyJwtPk: encodedToken key: publicKey];
if (success != YES) {
NSLog(@"%@",@"Invalid JWT signature.");
return;
}
// Only now inspect trusted claims. A valid signature alone is not sufficient.
CkoJsonObject *claims = [[CkoJsonObject alloc] init];
claims.Strict = YES;
success = [claims Load: [jwt GetPayload: encodedToken]];
if (success != YES) {
NSLog(@"%@",@"Invalid JWT claims.");
return;
}
if ([claims StringOf: @"iss"] != [issuer GetAsString]) {
NSLog(@"%@",@"JWT issuer mismatch.");
return;
}
if ([claims StringOf: @"token_use"] != expectedUse) {
NSLog(@"%@",@"Wrong token purpose.");
return;
}
if (([[claims JsonTypeOf: @"exp"] intValue] != 2) || ([[claims JsonTypeOf: @"iat"] intValue] != 2)) {
NSLog(@"%@",@"Missing numeric expiration or issue time.");
return;
}
if ([jwt IsTimeValid: encodedToken leeway: [NSNumber numberWithInt: 60]] != YES) {
NSLog(@"%@",@"JWT is expired or not yet valid.");
return;
}
if (expectedUse == @"id") {
if ([claims StringOf: @"aud"] != clientId) {
NSLog(@"%@",@"ID token audience mismatch.");
return;
}
}
else {
if ([claims StringOf: @"client_id"] != clientId) {
NSLog(@"%@",@"Access token client mismatch.");
return;
}
// Whole-word scope matching, not a substring match.
CkoStringBuilder *scopes = [[CkoStringBuilder alloc] init];
[scopes Append: @" "];
[scopes Append: [claims StringOf: @"scope"]];
[scopes Append: @" "];
CkoStringBuilder *wantedScope = [[CkoStringBuilder alloc] init];
[wantedScope Append: @" "];
[wantedScope Append: requiredScope];
[wantedScope Append: @" "];
if ((requiredScope != @"") && ([scopes Contains: [wantedScope GetAsString] caseSensitive: YES] != YES)) {
NSLog(@"%@",@"Required scope is absent.");
return;
}
}
if (([[claims JsonTypeOf: @"sub"] intValue] != 1) || ([claims StringOf: @"sub"] == @"")) {
NSLog(@"%@",@"Missing or invalid sub.");
return;
}
NSLog(@"%@",@"JWT signature and required claims are valid.");
// Apply your application's authorization policy before granting access.