PHPackages                             uqi/cognito-token - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. uqi/cognito-token

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

uqi/cognito-token
=================

Lightweight JWT token management for cognito.

1.1.4(1y ago)3900MITPHPPHP &gt;=7.3

Since Apr 9Pushed 1y agoCompare

[ Source](https://github.com/uqi-dev/cognito-token)[ Packagist](https://packagist.org/packages/uqi/cognito-token)[ RSS](/packages/uqi-cognito-token/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (4)Versions (7)Used By (0)

Cognito Token
=============

[](#cognito-token)

A PHP library for verifying AWS Cognito JWT tokens (ID tokens and Access tokens).

Overview
--------

[](#overview)

The `CognitoTokenVerifier` class provides functionality to verify JSON Web Tokens (JWTs) issued by AWS Cognito. It handles:

- Signature verification using JSON Web Keys (JWK)
- Token expiration validation
- Issuer validation
- Audience validation for ID tokens
- Client ID validation for access tokens

Installation
------------

[](#installation)

```
composer require uqi/cognito-token
```

Requirements
------------

[](#requirements)

- PHP 7.4 or higher
- `web-token/jwt-signature` package
- `web-token/jwt-core` package

Implementation Options
----------------------

[](#implementation-options)

You have two options for implementing token verification in your application:

### Option 1: Use this library directly

[](#option-1-use-this-library-directly)

The simplest approach is to use this library as-is, which provides a complete solution for Cognito token verification.

```
use UQI\Cognito\Tokens\CognitoTokenVerifier;

$verifier = new CognitoTokenVerifier(
    'us-east-1',              // AWS region
    'us-east-1_example',    // Cognito User Pool ID
    'example'  // Cognito Client ID
);

$payload = $verifier->verifyIdToken($idToken);
```

### Option 2: Create your own implementation

[](#option-2-create-your-own-implementation)

If you need custom functionality or want to integrate with specific systems, you can create your own implementation based on the principles in this library:

1. Fetch the JWKS (JSON Web Key Set) from Cognito
2. Parse and verify the JWT signature using the appropriate JWK
3. Validate token claims (expiration, issuer, audience, etc.)

This approach gives you more control but requires deeper understanding of JWT verification.

Basic Usage
-----------

[](#basic-usage)

```
use UQI\Cognito\Tokens\CognitoTokenVerifier;
use UQI\Cognito\Tokens\Exception\CognitoTokenException;

// Initialize the verifier
$verifier = new CognitoTokenVerifier(
    'us-east-1',              // AWS region
    'us-east-1_aQRUYfYJQ',    // Cognito User Pool ID
    'example'  // Cognito Client ID
);

// Verify an ID token
try {
    $payload = $verifier->verifyIdToken($idToken);
    // $payload now contains the decoded token claims
    print_r($payload);
} catch (CognitoTokenException $e) {
    echo "Token verification failed: " . $e->getMessage();
}

// Verify an ID token
try {
    $payload = $verifier->verifyIdToken($idToken);
    // $payload now contains the decoded token claims
    print_r($payload);
} catch (CognitoTokenException $e) {
    echo "Token verification failed: " . $e->getMessage();
}

// Verify an id|access token
try {
    $payload = $verifier->verifyToken($token);
    // $payload now contains the decoded token claims
    print_r($payload);
} catch (CognitoTokenException $e) {
    echo "Token verification failed: " . $e->getMessage();
}
```

Caching
-------

[](#caching)

The library supports caching of JWKS (JSON Web Key Sets) to improve performance. By default, it uses a no-cache implementation, but you can provide your own cache implementation:

```
use UQI\Cognito\Tokens\CognitoTokenVerifier;
use YourNamespace\YourCacheImplementation;

// Create your cache implementation that implements CacheInterface
$cache = new YourCacheImplementation();

// Initialize the verifier with cache
$verifier = new CognitoTokenVerifier(
    'us-east-1',              // AWS region
    'us-east-1_aQRUYfYJQ',    // Cognito User Pool ID
    'example',  // Cognito Client ID
    $cache                    // Cache implementation
);
```

Implementing a Cache Driver
---------------------------

[](#implementing-a-cache-driver)

Create a class that implements the `CacheInterface`:

```
namespace YourNamespace;

use UQI\Cognito\Tokens\CacheInterface;

class YourCacheImplementation implements CacheInterface
{
    public function put(string $key, $value, int $minutes)
    {
        // Store the value in your cache system
    }

    public function get(string $key)
    {
        // Retrieve the value from your cache system
        // Return null if not found
    }

    public function has(string $key): bool
    {
        // Check if the key exists in your cache system
        return false;
    }
}
```

Laravel Integration
-------------------

[](#laravel-integration)

For Laravel users, a ready-to-use cache implementation is included with the library:

```
use Illuminate\Support\Facades\Cache;
use UQI\Cognito\Tokens\CacheInterface;

class LaravelCacheDriver implements CacheInterface
{
    /**
     * The name of the Laravel cache store to use.
     *
     * @var string
     */
    protected $store;

    /**
     * Create a new cache driver instance.
     *
     * @param string $store Laravel cache store name (e.g., 'file', 'redis', 'memcached').
     */
    public function __construct(string $store = 'file')
    {
        $this->store = $store;
    }

    /**
     * Store a value in the cache for the given number of minutes.
     *
     * @param string $key Cache key.
     * @param mixed $value The value to cache.
     * @param int $minutes Duration in minutes to keep the item.
     */
    public function put(string $key, $value, int $minutes)
    {
        Cache::store($this->store)->put($key, $value, $minutes);
    }

    /**

     * Retrieve an item from the cache by key.
     *
     * @param string $key Cache key.
     * @return mixed|null The cached value, or null if not found.
     */
    public function get(string $key)
    {
        return Cache::store($this->store)->get($key);
    }

    /**
     * Determine if the given cache key exists.
     *
     * @param string $key Cache key.
     * @return bool True if the key exists in the cache, false otherwise.
     */
    public function has(string $key): bool
    {
        return Cache::store($this->store)->has($key);
    }
}
```

Usage with Laravel:

```
use UQI\Cognito\Tokens\CognitoTokenVerifier;
use UQI\Cognito\Tokens\LaravelCache;

// Initialize the verifier with Laravel cache
$verifier = new CognitoTokenVerifier(
    config('cognito.region'),
    config('cognito.user_pool_id'),
    config('cognito.client_id'),
    new LaravelCache()
);
```

Error Handling
--------------

[](#error-handling)

The library throws `CognitoTokenException` with specific error codes:

Error CodeDescriptionJWKS\_FETCH\_FAILEDFailed to fetch JWKS from the remote URLJWKS\_INVALID\_FORMATInvalid JWKS format - 'keys' not foundNO\_KID\_IN\_TOKENNo 'kid' found in JWT headerNO\_JWK\_FOR\_KIDNo matching JWK found for the specified kidSIGNATURE\_VERIFICATION\_FAILEDJWT signature verification failedTOKEN\_PAYLOAD\_DECODING\_FAILEDFailed to decode JWT payloadINVALID\_TOKENInvalid tokenINVALID\_ISSUERInvalid issuer in tokenTOKEN\_EXPIREDToken is expiredINVALID\_AUDIENCEInvalid audience in ID tokenMISSING\_SUBJECTMissing subject (sub) claim in ID tokenINVALID\_CLIENT\_ID\_ACCESSInvalid client\_id in access tokenExample error handling:

```
use UQI\Cognito\Tokens\CognitoTokenVerifier;
use UQI\Cognito\Tokens\Exception\CognitoTokenException;

try {
    $payload = $verifier->verifyIdToken($token);
    // Token is valid
} catch (CognitoTokenException $e) {
    switch ($e->getCode()) {
        case CognitoTokenException::TOKEN_EXPIRED:
            echo "The token has expired";
            break;
        case CognitoTokenException::INVALID_ISSUER:
            echo "Invalid token issuer";
            break;
        default:
            echo "Token verification failed: " . $e->getMessage();
    }
}
```

Class Reference
---------------

[](#class-reference)

### CognitoTokenVerifier

[](#cognitotokenverifier)

#### Constructor

[](#constructor)

```
/**
 * Constructor.
 *
 * @param string $region     AWS region (e.g., "us-east-1").
 * @param string $userPoolId Cognito User Pool ID (e.g., "us-east-1_aQRUYfYJQ").
 * @param string $clientId   Cognito Client ID.
 * @param CacheInterface|null $cacheDriver (optional) Cache implementation.
 *
 * @throws CognitoTokenException if JWKS fetching or decoding fails.
 */
public function __construct(string $region, string $userPoolId, string $clientId, CacheInterface $cacheDriver = null)
```

#### Methods

[](#methods)

```
/**
 * Verifies the token's signature and basic claims.
 *
 * @param string $jwt The JWT string.
 * @return array Decoded token payload.
 * @return array|false Decoded token payload or false on failure.
 * @throws CognitoTokenException if verification fails.
 */
public function verifyToken(string $jwt): array
```

```
/**
 * Verifies a Cognito ID token.
 *
 * @param string $jwt The ID token.
 * @return array Decoded token payload.
 * @throws CognitoTokenException if any validation fails.
 */
public function verifyIdToken(string $jwt): array
```

```
/**
 * Verifies a Cognito access token.
 *
 * @param string $jwt The access token.
 * @return array Decoded token payload.
 * @throws CognitoTokenException if any validation fails.
 */
public function verifyAccessToken(string $jwt): array
```

### CacheInterface

[](#cacheinterface)

```
/**
 * Stores a value in the cache.
 *
 * @param string $key     The cache key.
 * @param mixed  $value   The value to store.
 * @param int    $minutes Cache duration in minutes.
 */
public function put(string $key, $value, int $minutes);

/**
 * Retrieves a value from the cache.
 *
 * @param string $key The cache key.
 * @return mixed The cached value or null if not found.
 */
public function get(string $key);

/**
 * Checks if a key exists in the cache.
 *
 * @param string $key The cache key.
 * @return bool True if the key exists, false otherwise.
 */
public function has(string $key): bool;
```

License
-------

[](#license)

MIT

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance48

Moderate activity, may be stable

Popularity20

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3 days

Total

6

Last Release

388d ago

PHP version history (2 changes)1.0.0PHP &gt;=7.4

1.1.2PHP &gt;=7.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/0a2cb7f08e3bd262b45d61d27fa8bc6cf50f69f2c298b52f01a8c3c2994ee267?d=identicon)[uqi](/maintainers/uqi)

---

Top Contributors

[![ishantoz](https://avatars.githubusercontent.com/u/40614334?v=4)](https://github.com/ishantoz "ishantoz (13 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/uqi-cognito-token/health.svg)

```
[![Health](https://phpackages.com/badges/uqi-cognito-token/health.svg)](https://phpackages.com/packages/uqi-cognito-token)
```

###  Alternatives

[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)[amocrm/amocrm-api-library

amoCRM API Client

182728.5k6](/packages/amocrm-amocrm-api-library)[simplesamlphp/simplesamlphp-module-oidc

A SimpleSAMLphp module adding support for the OpenID Connect protocol

5016.9k1](/packages/simplesamlphp-simplesamlphp-module-oidc)[openeuropa/oe_authentication

Authentication against the OpenEuropa Authentication service.

17314.8k2](/packages/openeuropa-oe-authentication)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
