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

CkPerl
use chilkat();

$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 = chilkat::CkJsonObject->new();
$app->put_Strict(1);
$success = $app->LoadFile("qa_data/cognito/app.json");
if ($success != 1) {
    print "Could not load Cognito app settings." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("region") != 1) or ($app->stringOf("region") == "")) {
    print "Missing or invalid region." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("user_pool_id") != 1) or ($app->stringOf("user_pool_id") == "")) {
    print "Missing or invalid user_pool_id." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("client_id") != 1) or ($app->stringOf("client_id") == "")) {
    print "Missing or invalid client_id." . "\r\n";
    exit;
}

if (($app->JsonTypeOf("account_key") != 1) or ($app->stringOf("account_key") == "")) {
    print "Missing or invalid account_key." . "\r\n";
    exit;
}

$clientId = $app->stringOf("client_id");
$endpoint = chilkat::CkStringBuilder->new();
$endpoint->Append("https://cognito-idp.");
$endpoint->Append($app->stringOf("region"));
$endpoint->Append(".amazonaws.com/");
$http = chilkat::CkHttp->new();
$http->put_RequireSslCertVerify(1);
$http->put_FollowRedirects(0);
$http->put_ConnectTimeout(20);
$http->put_ReadTimeout(60);
$resp = chilkat::CkHttpResponse->new();
$body = chilkat::CkJsonObject->new();
$result = chilkat::CkJsonObject->new();
$result->put_Strict(1);
$cached = chilkat::CkJsonObject->new();
$cached->put_Strict(1);
$success = $cached->LoadFile("qa_data/tokens/cognito-user.json");
if ($success != 1) {
    print "Could not load qa_data/tokens/cognito-user.json." . "\r\n";
    exit;
}

if (($cached->JsonTypeOf("client_id") != 1) or ($cached->stringOf("client_id") == "")) {
    print "Missing or invalid client_id." . "\r\n";
    exit;
}

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

if (($cached->JsonTypeOf("user_pool_id") != 1) or ($cached->stringOf("user_pool_id") == "")) {
    print "Missing or invalid user_pool_id." . "\r\n";
    exit;
}

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

if (($cached->JsonTypeOf("account_key") != 1) or ($cached->stringOf("account_key") == "")) {
    print "Missing or invalid account_key." . "\r\n";
    exit;
}

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

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

$encodedToken = $cached->stringOf("access_token");
if ($expectedUse == "id") {
    $encodedToken = $cached->stringOf("id_token");
}

if ((($expectedUse == "access") and ($cached->JsonTypeOf("access_token") != 1)) or (($expectedUse == "id") and ($cached->JsonTypeOf("id_token") != 1)) or ($encodedToken == "")) {
    print "Missing JWT." . "\r\n";
    exit;
}

$jwt = chilkat::CkJwt->new();
$header = chilkat::CkJsonObject->new();
$header->put_Strict(1);
$success = $header->Load($jwt->getHeader($encodedToken));
if ($success != 1) {
    print "Invalid JWT header." . "\r\n";
    exit;
}

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

if (($header->JsonTypeOf("kid") != 1) or ($header->stringOf("kid") == "")) {
    print "Missing or invalid kid." . "\r\n";
    exit;
}

$issuer = chilkat::CkStringBuilder->new();
$issuer->Append($endpoint->getAsString());
$issuer->Append($app->stringOf("user_pool_id"));
$jwksUrl = chilkat::CkStringBuilder->new();
$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);
if ($resp->get_StatusCode() != 200) {
    print "HTTP status: " . $resp->get_StatusCode() . "\r\n";
    $success = $result->Load($resp->bodyStr());
    if ($success == 1) {
        print "Error type: " . $result->stringOf("__type") . "\r\n";
        print "OAuth error: " . $result->stringOf("error") . "\r\n";
    }

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

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

$success = $result->Load($resp->bodyStr());
if ($success != 1) {
    print "Expected a JSON response." . "\r\n";
    exit;
}

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

$i = 0;
$count = $result->SizeOfArray("keys");
$matches = 0;
$jwk = chilkat::CkJsonObject->new();
while ($i < $count) {
    $result->put_I($i);
    if ($result->stringOf("keys[i].kid") == $header->stringOf("kid")) {
        $matches = $matches + 1;
        $success = $result->ObjectOf2("keys[i]",$jwk);
        if ($success != 1) {
            print "Could not read the matching key." . "\r\n";
            exit;
        }

    }

    $i = $i + 1;
}

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

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

$publicKey = chilkat::CkPublicKey->new();
$success = $publicKey->LoadFromString($jwk->emit());
if ($success != 1) {
    print "Could not load the RSA JWK." . "\r\n";
    exit;
}

$success = $jwt->VerifyJwtPk($encodedToken,$publicKey);
if ($success != 1) {
    print "Invalid JWT signature." . "\r\n";
    exit;
}

#  Only now inspect trusted claims. A valid signature alone is not sufficient.
$claims = chilkat::CkJsonObject->new();
$claims->put_Strict(1);
$success = $claims->Load($jwt->getPayload($encodedToken));
if ($success != 1) {
    print "Invalid JWT claims." . "\r\n";
    exit;
}

if ($claims->stringOf("iss") != $issuer->getAsString()) {
    print "JWT issuer mismatch." . "\r\n";
    exit;
}

if ($claims->stringOf("token_use") != $expectedUse) {
    print "Wrong token purpose." . "\r\n";
    exit;
}

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

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

if ($expectedUse == "id") {
    if ($claims->stringOf("aud") != $clientId) {
        print "ID token audience mismatch." . "\r\n";
        exit;
    }

}
else {
    if ($claims->stringOf("client_id") != $clientId) {
        print "Access token client mismatch." . "\r\n";
        exit;
    }

    #  Whole-word scope matching, not a substring match.
    $scopes = chilkat::CkStringBuilder->new();
    $scopes->Append(" ");
    $scopes->Append($claims->stringOf("scope"));
    $scopes->Append(" ");
    $wantedScope = chilkat::CkStringBuilder->new();
    $wantedScope->Append(" ");
    $wantedScope->Append($requiredScope);
    $wantedScope->Append(" ");
    if (($requiredScope != "") and ($scopes->Contains($wantedScope->getAsString(),1) != 1)) {
        print "Required scope is absent." . "\r\n";
        exit;
    }

}

if (($claims->JsonTypeOf("sub") != 1) or ($claims->stringOf("sub") == "")) {
    print "Missing or invalid sub." . "\r\n";
    exit;
}

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