PHP code example of uqi / cognito-token

1. Go to this page and download the library: Download uqi/cognito-token library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

uqi / cognito-token example snippets


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);

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();
}

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
);

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;
    }
}


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);
    }
}

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()
);

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();
    }
}

/**
 * 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)

/**
 * 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

/**
 * 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;