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

Perl
use strict;
use warnings;
use Chilkat2;

# Assumes Chilkat is unlocked. See Global Unlock Sample.
my $success = 0;
# App settings are trusted configuration. Keep a separate account_key/cache per local user.
my $app = Chilkat2::JsonObject->new;
$app->Strict(1);
$success = $app->LoadFile('qa_data/cognito/app.json');
if (!$success) {
    print "Could not load Cognito app settings.\n";
    exit;
}

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

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

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

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

my $clientId = $app->StringOf('client_id');
my $endpoint = Chilkat2::StringBuilder->new;
$endpoint->Append('https://cognito-idp.');
$endpoint->Append($app->StringOf('region'));
$endpoint->Append('.amazonaws.com/');
my $http = Chilkat2::Http->new;
$http->RequireSslCertVerify(1);
$http->FollowRedirects(0);
$http->ConnectTimeout(20);
$http->ReadTimeout(60);
my $resp = Chilkat2::HttpResponse->new;
my $body = Chilkat2::JsonObject->new;
my $result = Chilkat2::JsonObject->new;
$result->Strict(1);
my $cached = Chilkat2::JsonObject->new;
$cached->Strict(1);
$success = $cached->LoadFile('qa_data/tokens/cognito-user.json');
if (!$success) {
    print "Could not load qa_data/tokens/cognito-user.json.\n";
    exit;
}

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

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

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

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

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

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

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

my $encodedToken = $cached->StringOf('access_token');
if ($expectedUse eq 'id') {
    $encodedToken = $cached->StringOf('id_token');
}

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

my $jwt = Chilkat2::Jwt->new;
my $header = Chilkat2::JsonObject->new;
$header->Strict(1);
$success = $header->Load($jwt->GetHeader($encodedToken));
if (!$success) {
    print "Invalid JWT header.\n";
    exit;
}

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

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

my $issuer = Chilkat2::StringBuilder->new;
$issuer->Append($endpoint->GetAsString());
$issuer->Append($app->StringOf('user_pool_id'));
my $jwksUrl = Chilkat2::StringBuilder->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->StatusCode != 200) {
    print 'HTTP status: ', $resp->StatusCode, "\n";
    $success = $result->Load($resp->BodyStr);
    if ($success) {
        print 'Error type: ', $result->StringOf('__type'), "\n";
        print 'OAuth error: ', $result->StringOf('error'), "\n";
    }

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

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

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

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

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

    $i = $i + 1;
}

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

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

my $publicKey = Chilkat2::PublicKey->new;
$success = $publicKey->LoadFromString($jwk->Emit());
if (!$success) {
    print "Could not load the RSA JWK.\n";
    exit;
}

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

# Only now inspect trusted claims. A valid signature alone is not sufficient.
my $claims = Chilkat2::JsonObject->new;
$claims->Strict(1);
$success = $claims->Load($jwt->GetPayload($encodedToken));
if (!$success) {
    print "Invalid JWT claims.\n";
    exit;
}

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

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

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

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

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

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

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

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