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

Delphi ActiveX
var
success: Integer;
app: TChilkatJsonObject;
clientId: WideString;
endpoint: TChilkatStringBuilder;
http: TChilkatHttp;
resp: TChilkatHttpResponse;
body: TChilkatJsonObject;
result: TChilkatJsonObject;
cached: TChilkatJsonObject;
expectedUse: WideString;
requiredScope: WideString;
encodedToken: WideString;
jwt: TChilkatJwt;
header: TChilkatJsonObject;
issuer: TChilkatStringBuilder;
jwksUrl: TChilkatStringBuilder;
i: Integer;
count: Integer;
matches: Integer;
jwk: TChilkatJsonObject;
publicKey: TPublicKey;
claims: TChilkatJsonObject;
scopes: TChilkatStringBuilder;
wantedScope: TChilkatStringBuilder;

begin
success := 0;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success := 0;
//  App settings are trusted configuration. Keep a separate account_key/cache per local user.
app := TChilkatJsonObject.Create(Self);
app.Strict := 1;
success := app.LoadFile('qa_data/cognito/app.json');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not load Cognito app settings.');
    Exit;
  end;
if ((app.JsonTypeOf('region') <> 1) or (app.StringOf('region') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid region.');
    Exit;
  end;
if ((app.JsonTypeOf('user_pool_id') <> 1) or (app.StringOf('user_pool_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid user_pool_id.');
    Exit;
  end;
if ((app.JsonTypeOf('client_id') <> 1) or (app.StringOf('client_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
if ((app.JsonTypeOf('account_key') <> 1) or (app.StringOf('account_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid account_key.');
    Exit;
  end;
clientId := app.StringOf('client_id');
endpoint := TChilkatStringBuilder.Create(Self);
endpoint.Append('https://cognito-idp.');
endpoint.Append(app.StringOf('region'));
endpoint.Append('.amazonaws.com/');
http := TChilkatHttp.Create(Self);
http.RequireSslCertVerify := 1;
http.FollowRedirects := 0;
http.ConnectTimeout := 20;
http.ReadTimeout := 60;
resp := TChilkatHttpResponse.Create(Self);
body := TChilkatJsonObject.Create(Self);
result := TChilkatJsonObject.Create(Self);
result.Strict := 1;
cached := TChilkatJsonObject.Create(Self);
cached.Strict := 1;
success := cached.LoadFile('qa_data/tokens/cognito-user.json');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not load qa_data/tokens/cognito-user.json.');
    Exit;
  end;
if ((cached.JsonTypeOf('client_id') <> 1) or (cached.StringOf('client_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid client_id.');
    Exit;
  end;
if (cached.StringOf('client_id') <> app.StringOf('client_id')) then
  begin
    Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
    Exit;
  end;
if ((cached.JsonTypeOf('user_pool_id') <> 1) or (cached.StringOf('user_pool_id') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid user_pool_id.');
    Exit;
  end;
if (cached.StringOf('user_pool_id') <> app.StringOf('user_pool_id')) then
  begin
    Memo1.Lines.Add('Saved data belongs to another client, pool, or local account.');
    Exit;
  end;
if ((cached.JsonTypeOf('account_key') <> 1) or (cached.StringOf('account_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid account_key.');
    Exit;
  end;
if (cached.StringOf('account_key') <> app.StringOf('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 := cached.StringOf('access_token');
if (expectedUse = 'id') then
  begin
    encodedToken := cached.StringOf('id_token');
  end;
if (((expectedUse = 'access') and (cached.JsonTypeOf('access_token') <> 1)) or ((expectedUse = 'id') and (cached.JsonTypeOf('id_token') <> 1)) or (encodedToken = '')) then
  begin
    Memo1.Lines.Add('Missing JWT.');
    Exit;
  end;
jwt := TChilkatJwt.Create(Self);
header := TChilkatJsonObject.Create(Self);
header.Strict := 1;
success := header.Load(jwt.GetHeader(encodedToken));
if (success <> 1) then
  begin
    Memo1.Lines.Add('Invalid JWT header.');
    Exit;
  end;
if (header.StringOf('alg') <> 'RS256') then
  begin
    Memo1.Lines.Add('Expected RS256; do not trust the token algorithm without an allowlist.');
    Exit;
  end;
if ((header.JsonTypeOf('kid') <> 1) or (header.StringOf('kid') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid kid.');
    Exit;
  end;
issuer := TChilkatStringBuilder.Create(Self);
issuer.Append(endpoint.GetAsString());
issuer.Append(app.StringOf('user_pool_id'));
jwksUrl := TChilkatStringBuilder.Create(Self);
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',jwksUrl.GetAsString(),resp.ControlInterface);
if (resp.StatusCode <> 200) then
  begin
    Memo1.Lines.Add('HTTP status: ' + IntToStr(resp.StatusCode));
    success := result.Load(resp.BodyStr);
    if (success = 1) then
      begin
        Memo1.Lines.Add('Error type: ' + result.StringOf('__type'));
        Memo1.Lines.Add('OAuth error: ' + result.StringOf('error'));
      end;
    //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Exit;
  end;
if (success <> 1) then
  begin
    Memo1.Lines.Add('The HTTP exchange did not complete.');
    Exit;
  end;
success := result.Load(resp.BodyStr);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Expected a JSON response.');
    Exit;
  end;
if (result.JsonTypeOf('keys') <> 4) then
  begin
    Memo1.Lines.Add('Expected a JWKS keys array.');
    Exit;
  end;
i := 0;
count := result.SizeOfArray('keys');
matches := 0;
jwk := TChilkatJsonObject.Create(Self);
while i < count do
  begin
    result.I := i;
    if (result.StringOf('keys[i].kid') = header.StringOf('kid')) then
      begin
        matches := matches + 1;
        success := result.ObjectOf2('keys[i]',jwk.ControlInterface);
        if (success <> 1) 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 ((jwk.StringOf('kty') <> 'RSA') or (jwk.StringOf('use') <> 'sig') or (jwk.StringOf('alg') <> 'RS256')) then
  begin
    Memo1.Lines.Add('Unexpected signing-key type, use, or algorithm.');
    Exit;
  end;
publicKey := TPublicKey.Create(Self);
success := publicKey.LoadFromString(jwk.Emit());
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not load the RSA JWK.');
    Exit;
  end;
success := jwt.VerifyJwtPk(encodedToken,publicKey.ControlInterface);
if (success <> 1) then
  begin
    Memo1.Lines.Add('Invalid JWT signature.');
    Exit;
  end;
//  Only now inspect trusted claims. A valid signature alone is not sufficient.
claims := TChilkatJsonObject.Create(Self);
claims.Strict := 1;
success := claims.Load(jwt.GetPayload(encodedToken));
if (success <> 1) then
  begin
    Memo1.Lines.Add('Invalid JWT claims.');
    Exit;
  end;
if (claims.StringOf('iss') <> issuer.GetAsString()) then
  begin
    Memo1.Lines.Add('JWT issuer mismatch.');
    Exit;
  end;
if (claims.StringOf('token_use') <> expectedUse) then
  begin
    Memo1.Lines.Add('Wrong token purpose.');
    Exit;
  end;
if ((claims.JsonTypeOf('exp') <> 2) or (claims.JsonTypeOf('iat') <> 2)) then
  begin
    Memo1.Lines.Add('Missing numeric expiration or issue time.');
    Exit;
  end;
if (jwt.IsTimeValid(encodedToken,60) <> 1) then
  begin
    Memo1.Lines.Add('JWT is expired or not yet valid.');
    Exit;
  end;
if (expectedUse = 'id') then
  begin
    if (claims.StringOf('aud') <> clientId) then
      begin
        Memo1.Lines.Add('ID token audience mismatch.');
        Exit;
      end;
  end
else
  begin
    if (claims.StringOf('client_id') <> clientId) then
      begin
        Memo1.Lines.Add('Access token client mismatch.');
        Exit;
      end;
    //  Whole-word scope matching, not a substring match.
    scopes := TChilkatStringBuilder.Create(Self);
    scopes.Append(' ');
    scopes.Append(claims.StringOf('scope'));
    scopes.Append(' ');
    wantedScope := TChilkatStringBuilder.Create(Self);
    wantedScope.Append(' ');
    wantedScope.Append(requiredScope);
    wantedScope.Append(' ');
    if ((requiredScope <> '') and (scopes.Contains(wantedScope.GetAsString(),1) <> 1)) then
      begin
        Memo1.Lines.Add('Required scope is absent.');
        Exit;
      end;
  end;
if ((claims.JsonTypeOf('sub') <> 1) or (claims.StringOf('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.