PHP code example of adhocore / jwt

1. Go to this page and download the library: Download adhocore/jwt 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/ */

    

adhocore / jwt example snippets


use Ahc\Jwt\JWT;

// Instantiate with key, algo, maxAge and leeway.
$jwt = new JWT('secret', 'HS256', 3600, 10);

$jwt = new JWT('secret');
// algo = HS256, maxAge = 3600, leeway = 0

$key = openssl_pkey_new([
    'digest_alg' => 'sha256',
    'private_key_bits' => 1024,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
]);

$key = '/path/to/rsa.key';

// Then, instantiate JWT with this key and RS* as algo:
$jwt = new JWT($key, 'RS384');

$token = $jwt->encode([
    'uid'    => 1,
    'aud'    => 'http://site.com',
    'scopes' => ['user'],
    'iss'    => 'http://api.mysite.com',
]);

$payload = $jwt->decode($token);

$token   = (new JWT('topSecret', 'HS512', 1800))->encode(['uid' => 1, 'scopes' => ['user']]);
$payload = (new JWT('topSecret', 'HS512', 1800))->decode($token);

$token = $jwt->encode($payload, ['hdr' => 'hdr_value']);

$jwt->setTestTimestamp(time() + 10000);

// Throws Exception.
$jwt->parse($token);

$jwt->setTestTimestamp();

$jwt = new JWT(['key1' => 'secret1', 'key2' => 'secret2']);

// Use key2
$token = $jwt->encode(['a' => 1, 'exp' => time() + 1000], ['kid' => 'key2']);

$payload = $jwt->decode($token);

$token = $jwt->encode(['a' => 1, 'exp' => time() + 1000], ['kid' => 'key3']);
// -> Exception with message Unknown key ID key3