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

PHP
<?php

use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;
use Chilkat2\Jwt;
use Chilkat2\PublicKey;
use Chilkat2\StringBuilder;

$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 = new JsonObject();
$app->Strict = true;
try {
    $app->LoadFile('qa_data/cognito/app.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not load Cognito app settings.\n";
    exit;
}

if (($app->JsonTypeOf('region') != 1) || ($app->StringOf('region') === '')) {
    echo "Missing or invalid region.\n";
    exit;
}

if (($app->JsonTypeOf('user_pool_id') != 1) || ($app->StringOf('user_pool_id') === '')) {
    echo "Missing or invalid user_pool_id.\n";
    exit;
}

if (($app->JsonTypeOf('client_id') != 1) || ($app->StringOf('client_id') === '')) {
    echo "Missing or invalid client_id.\n";
    exit;
}

if (($app->JsonTypeOf('account_key') != 1) || ($app->StringOf('account_key') === '')) {
    echo "Missing or invalid account_key.\n";
    exit;
}

$clientId = $app->StringOf('client_id');
$endpoint = new StringBuilder();
$endpoint->Append('https://cognito-idp.');
$endpoint->Append($app->StringOf('region'));
$endpoint->Append('.amazonaws.com/');
$http = new Http();
$http->RequireSslCertVerify = true;
$http->FollowRedirects = false;
$http->ConnectTimeout = 20;
$http->ReadTimeout = 60;
$resp = new HttpResponse();
$body = new JsonObject();
$result = new JsonObject();
$result->Strict = true;
$cached = new JsonObject();
$cached->Strict = true;
try {
    $cached->LoadFile('qa_data/tokens/cognito-user.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not load qa_data/tokens/cognito-user.json.\n";
    exit;
}

if (($cached->JsonTypeOf('client_id') != 1) || ($cached->StringOf('client_id') === '')) {
    echo "Missing or invalid client_id.\n";
    exit;
}

if ($cached->StringOf('client_id') !== $app->StringOf('client_id')) {
    echo "Saved data belongs to another client, pool, or local account.\n";
    exit;
}

if (($cached->JsonTypeOf('user_pool_id') != 1) || ($cached->StringOf('user_pool_id') === '')) {
    echo "Missing or invalid user_pool_id.\n";
    exit;
}

if ($cached->StringOf('user_pool_id') !== $app->StringOf('user_pool_id')) {
    echo "Saved data belongs to another client, pool, or local account.\n";
    exit;
}

if (($cached->JsonTypeOf('account_key') != 1) || ($cached->StringOf('account_key') === '')) {
    echo "Missing or invalid account_key.\n";
    exit;
}

if ($cached->StringOf('account_key') !== $app->StringOf('account_key')) {
    echo "Saved data belongs to another client, pool, or local account.\n";
    exit;
}

// Choose the expected token type independently of the incoming JWT.
$expectedUse = 'access';
$requiredScope = 'aws.cognito.signin.user.admin';
if (($expectedUse !== 'access') && ($expectedUse !== 'id')) {
    echo "Choose access or id.\n";
    exit;
}

$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 === ''))) {
    echo "Missing JWT.\n";
    exit;
}

$jwt = new Jwt();
$header = new JsonObject();
$header->Strict = true;
try {
    $header->Load($jwt->GetHeader($encodedToken));
} catch (\Chilkat2\Exception $e) {
    echo "Invalid JWT header.\n";
    exit;
}

if ($header->StringOf('alg') !== 'RS256') {
    echo "Expected RS256; do not trust the token algorithm without an allowlist.\n";
    exit;
}

if (($header->JsonTypeOf('kid') != 1) || ($header->StringOf('kid') === '')) {
    echo "Missing or invalid kid.\n";
    exit;
}

$issuer = new StringBuilder();
$issuer->Append($endpoint->GetAsString());
$issuer->Append($app->StringOf('user_pool_id'));
$jwksUrl = new StringBuilder();
$jwksUrl->Append($issuer->GetAsString());
$jwksUrl->Append('/.well-known/jwks.json');
// Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
$http->HttpNoBody('GET', $jwksUrl->GetAsString(), $resp);
if ($resp->StatusCode != 200) {
    echo 'HTTP status: ', $resp->StatusCode, "\n";
    try {
        $result->Load($resp->BodyStr);
        $success = true;
    } catch (\Chilkat2\Exception $e) {
        $success = false;
    }
    if ($success) {
        echo 'Error type: ', $result->StringOf('__type'), "\n";
        echo 'OAuth error: ', $result->StringOf('error'), "\n";
    }

    // Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    exit;
}

if (!$success) {
    echo "The HTTP exchange did not complete.\n";
    exit;
}

try {
    $result->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
    echo "Expected a JSON response.\n";
    exit;
}

if ($result->JsonTypeOf('keys') != 4) {
    echo "Expected a JWKS keys array.\n";
    exit;
}

$i = 0;
$count = $result->SizeOfArray('keys');
$matches = 0;
$jwk = new JsonObject();
while ($i < $count) {
    $result->I = $i;
    if ($result->StringOf('keys[i].kid') === $header->StringOf('kid')) {
        $matches = $matches + 1;
        try {
            $result->ObjectOf2('keys[i]', $jwk);
        } catch (\Chilkat2\Exception $e) {
            echo "Could not read the matching key.\n";
            exit;
        }
    }

    $i = $i + 1;
}

if ($matches != 1) {
    echo "Expected exactly one matching signing key.\n";
    exit;
}

if (($jwk->StringOf('kty') !== 'RSA') || (($jwk->StringOf('use') !== 'sig') || ($jwk->StringOf('alg') !== 'RS256'))) {
    echo "Unexpected signing-key type, use, or algorithm.\n";
    exit;
}

$publicKey = new PublicKey();
try {
    $publicKey->LoadFromString($jwk->Emit());
} catch (\Chilkat2\Exception $e) {
    echo "Could not load the RSA JWK.\n";
    exit;
}

try {
    $jwt->VerifyJwtPk($encodedToken, $publicKey);
} catch (\Chilkat2\Exception $e) {
    echo "Invalid JWT signature.\n";
    exit;
}

// Only now inspect trusted claims. A valid signature alone is not sufficient.
$claims = new JsonObject();
$claims->Strict = true;
try {
    $claims->Load($jwt->GetPayload($encodedToken));
} catch (\Chilkat2\Exception $e) {
    echo "Invalid JWT claims.\n";
    exit;
}

if ($claims->StringOf('iss') !== $issuer->GetAsString()) {
    echo "JWT issuer mismatch.\n";
    exit;
}

if ($claims->StringOf('token_use') !== $expectedUse) {
    echo "Wrong token purpose.\n";
    exit;
}

if (($claims->JsonTypeOf('exp') != 2) || ($claims->JsonTypeOf('iat') != 2)) {
    echo "Missing numeric expiration or issue time.\n";
    exit;
}

if (!$jwt->IsTimeValid($encodedToken, 60)) {
    echo "JWT is expired or not yet valid.\n";
    exit;
}

if ($expectedUse === 'id') {
    if ($claims->StringOf('aud') !== $clientId) {
        echo "ID token audience mismatch.\n";
        exit;
    }
} else {
    if ($claims->StringOf('client_id') !== $clientId) {
        echo "Access token client mismatch.\n";
        exit;
    }

    // Whole-word scope matching, not a substring match.
    $scopes = new StringBuilder();
    $scopes->Append(' ');
    $scopes->Append($claims->StringOf('scope'));
    $scopes->Append(' ');
    $wantedScope = new StringBuilder();
    $wantedScope->Append(' ');
    $wantedScope->Append($requiredScope);
    $wantedScope->Append(' ');
    if (($requiredScope !== '') && (!$scopes->Contains($wantedScope->GetAsString(), true))) {
        echo "Required scope is absent.\n";
        exit;
    }
}

if (($claims->JsonTypeOf('sub') != 1) || ($claims->StringOf('sub') === '')) {
    echo "Missing or invalid sub.\n";
    exit;
}

echo "JWT signature and required claims are valid.\n";
// Apply your application's authorization policy before granting access.