Sample code for 30+ languages & platforms
Delphi DLL 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 Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
app: HCkJsonObject;
clientId: PWideChar;
endpoint: HCkStringBuilder;
http: HCkHttp;
resp: HCkHttpResponse;
body: HCkJsonObject;
result: HCkJsonObject;
cached: HCkJsonObject;
expectedUse: PWideChar;
requiredScope: PWideChar;
encodedToken: PWideChar;
jwt: HCkJwt;
header: HCkJsonObject;
issuer: HCkStringBuilder;
jwksUrl: HCkStringBuilder;
i: Integer;
count: Integer;
matches: Integer;
jwk: HCkJsonObject;
publicKey: HCkPublicKey;
claims: HCkJsonObject;
scopes: HCkStringBuilder;
wantedScope: HCkStringBuilder;

begin
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.
app := CkJsonObject_Create();
CkJsonObject_putStrict(app,True);
success := CkJsonObject_LoadFile(app,'qa_data/cognito/app.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load Cognito app settings.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(app,'region') <> 1) or (CkJsonObject__stringOf(app,'region') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid region.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(app,'user_pool_id') <> 1) or (CkJsonObject__stringOf(app,'user_pool_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid user_pool_id.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(app,'client_id') <> 1) or (CkJsonObject__stringOf(app,'client_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(app,'account_key') <> 1) or (CkJsonObject__stringOf(app,'account_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid account_key.');
    Exit;
  end;
clientId := CkJsonObject__stringOf(app,'client_id');
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'https://cognito-idp.');
CkStringBuilder_Append(endpoint,CkJsonObject__stringOf(app,'region'));
CkStringBuilder_Append(endpoint,'.amazonaws.com/');
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,20);
CkHttp_putReadTimeout(http,60);
resp := CkHttpResponse_Create();
body := CkJsonObject_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
cached := CkJsonObject_Create();
CkJsonObject_putStrict(cached,True);
success := CkJsonObject_LoadFile(cached,'qa_data/tokens/cognito-user.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load qa_data/tokens/cognito-user.json.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(cached,'client_id') <> 1) or (CkJsonObject__stringOf(cached,'client_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
if (CkJsonObject__stringOf(cached,'client_id') <> CkJsonObject__stringOf(app,'client_id')) then
  begin
    Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(cached,'user_pool_id') <> 1) or (CkJsonObject__stringOf(cached,'user_pool_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid user_pool_id.');
    Exit;
  end;
if (CkJsonObject__stringOf(cached,'user_pool_id') <> CkJsonObject__stringOf(app,'user_pool_id')) then
  begin
    Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(cached,'account_key') <> 1) or (CkJsonObject__stringOf(cached,'account_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid account_key.');
    Exit;
  end;
if (CkJsonObject__stringOf(cached,'account_key') <> CkJsonObject__stringOf(app,'account_key')) then
  begin
    Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
    Exit;
  end;
//  Choose the expected token type independently of the incoming JWT.
expectedUse := 'access';
requiredScope := 'aws.cognito.signin.user.admin';
if ((expectedUse <> 'access') and (expectedUse <> 'id')) then
  begin
    Memo1.Lines.Add('Choose access or id.');
    Exit;
  end;
encodedToken := CkJsonObject__stringOf(cached,'access_token');
if (expectedUse = 'id') then
  begin
    encodedToken := CkJsonObject__stringOf(cached,'id_token');
  end;
if (((expectedUse = 'access') and (CkJsonObject_JsonTypeOf(cached,'access_token') <> 1)) or ((expectedUse = 'id') and (CkJsonObject_JsonTypeOf(cached,'id_token') <> 1)) or (encodedToken = '')) then
  begin
    Memo1.Lines.Add('Missing JWT.');
    Exit;
  end;
jwt := CkJwt_Create();
header := CkJsonObject_Create();
CkJsonObject_putStrict(header,True);
success := CkJsonObject_Load(header,CkJwt__getHeader(jwt,encodedToken));
if (success <> True) then
  begin
    Memo1.Lines.Add('Invalid JWT header.');
    Exit;
  end;
if (CkJsonObject__stringOf(header,'alg') <> 'RS256') then
  begin
    Memo1.Lines.Add('Expected RS256; do not trust the token algorithm without an allowlist.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(header,'kid') <> 1) or (CkJsonObject__stringOf(header,'kid') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid kid.');
    Exit;
  end;
issuer := CkStringBuilder_Create();
CkStringBuilder_Append(issuer,CkStringBuilder__getAsString(endpoint));
CkStringBuilder_Append(issuer,CkJsonObject__stringOf(app,'user_pool_id'));
jwksUrl := CkStringBuilder_Create();
CkStringBuilder_Append(jwksUrl,CkStringBuilder__getAsString(issuer));
CkStringBuilder_Append(jwksUrl,'/.well-known/jwks.json');
//  Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
success := CkHttp_HttpNoBody(http,'GET',CkStringBuilder__getAsString(jwksUrl),resp);
if (CkHttpResponse_getStatusCode(resp) <> 200) then
  begin
    Memo1.Lines.Add('HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
    success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
    if (success = True) then
      begin
        Memo1.Lines.Add('Error type: ' + CkJsonObject__stringOf(result,'__type'));
        Memo1.Lines.Add('OAuth error: ' + CkJsonObject__stringOf(result,'error'));
      end;
    //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Exit;
  end;
if (success <> True) then
  begin
    Memo1.Lines.Add('The HTTP exchange did not complete.');
    Exit;
  end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected a JSON response.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(result,'keys') <> 4) then
  begin
    Memo1.Lines.Add('Expected a JWKS keys array.');
    Exit;
  end;
i := 0;
count := CkJsonObject_SizeOfArray(result,'keys');
matches := 0;
jwk := CkJsonObject_Create();
while i < count do
  begin
    CkJsonObject_putI(result,i);
    if (CkJsonObject__stringOf(result,'keys[i].kid') = CkJsonObject__stringOf(header,'kid')) then
      begin
        matches := matches + 1;
        success := CkJsonObject_ObjectOf2(result,'keys[i]',jwk);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not read the matching key.');
            Exit;
          end;
      end;
    i := i + 1;
  end;

if (matches <> 1) then
  begin
    Memo1.Lines.Add('Expected exactly one matching signing key.');
    Exit;
  end;
if ((CkJsonObject__stringOf(jwk,'kty') <> 'RSA') or (CkJsonObject__stringOf(jwk,'use') <> 'sig') or (CkJsonObject__stringOf(jwk,'alg') <> 'RS256')) then
  begin
    Memo1.Lines.Add('Unexpected signing-key type, use, or algorithm.');
    Exit;
  end;
publicKey := CkPublicKey_Create();
success := CkPublicKey_LoadFromString(publicKey,CkJsonObject__emit(jwk));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load the RSA JWK.');
    Exit;
  end;
success := CkJwt_VerifyJwtPk(jwt,encodedToken,publicKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Invalid JWT signature.');
    Exit;
  end;
//  Only now inspect trusted claims. A valid signature alone is not sufficient.
claims := CkJsonObject_Create();
CkJsonObject_putStrict(claims,True);
success := CkJsonObject_Load(claims,CkJwt__getPayload(jwt,encodedToken));
if (success <> True) then
  begin
    Memo1.Lines.Add('Invalid JWT claims.');
    Exit;
  end;
if (CkJsonObject__stringOf(claims,'iss') <> CkStringBuilder__getAsString(issuer)) then
  begin
    Memo1.Lines.Add('JWT issuer mismatch.');
    Exit;
  end;
if (CkJsonObject__stringOf(claims,'token_use') <> expectedUse) then
  begin
    Memo1.Lines.Add('Wrong token purpose.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(claims,'exp') <> 2) or (CkJsonObject_JsonTypeOf(claims,'iat') <> 2)) then
  begin
    Memo1.Lines.Add('Missing numeric expiration or issue time.');
    Exit;
  end;
if (CkJwt_IsTimeValid(jwt,encodedToken,60) <> True) then
  begin
    Memo1.Lines.Add('JWT is expired or not yet valid.');
    Exit;
  end;
if (expectedUse = 'id') then
  begin
    if (CkJsonObject__stringOf(claims,'aud') <> clientId) then
      begin
        Memo1.Lines.Add('ID token audience mismatch.');
        Exit;
      end;
  end
else
  begin
    if (CkJsonObject__stringOf(claims,'client_id') <> clientId) then
      begin
        Memo1.Lines.Add('Access token client mismatch.');
        Exit;
      end;
    //  Whole-word scope matching, not a substring match.
    scopes := CkStringBuilder_Create();
    CkStringBuilder_Append(scopes,' ');
    CkStringBuilder_Append(scopes,CkJsonObject__stringOf(claims,'scope'));
    CkStringBuilder_Append(scopes,' ');
    wantedScope := CkStringBuilder_Create();
    CkStringBuilder_Append(wantedScope,' ');
    CkStringBuilder_Append(wantedScope,requiredScope);
    CkStringBuilder_Append(wantedScope,' ');
    if ((requiredScope <> '') and (CkStringBuilder_Contains(scopes,CkStringBuilder__getAsString(wantedScope),True) <> True)) then
      begin
        Memo1.Lines.Add('Required scope is absent.');
        Exit;
      end;
  end;
if ((CkJsonObject_JsonTypeOf(claims,'sub') <> 1) or (CkJsonObject__stringOf(claims,'sub') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid sub.');
    Exit;
  end;
Memo1.Lines.Add('JWT signature and required claims are valid.');
//  Apply your application's authorization policy before granting access.

CkJsonObject_Dispose(app);
CkStringBuilder_Dispose(endpoint);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(cached);
CkJwt_Dispose(jwt);
CkJsonObject_Dispose(header);
CkStringBuilder_Dispose(issuer);
CkStringBuilder_Dispose(jwksUrl);
CkJsonObject_Dispose(jwk);
CkPublicKey_Dispose(publicKey);
CkJsonObject_Dispose(claims);
    CkStringBuilder_Dispose(scopes);
    CkStringBuilder_Dispose(wantedScope);