PHP code example of token / jwt

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

    

token / jwt example snippets


use Token\JWT\Builder;
use Token\JWT\Encoding\ChainedFormatter;
use Token\JWT\Encoding\JoseEncoder;
use Token\JWT\Signature\Hmac\HS256;
use Token\JWT\Key;

$algorithm  = new HS256();
$signingKey = Key::plainText(random_bytes(32));

$now     = new DateTimeImmutable();
$builder = new Builder(new JoseEncoder(), ChainedFormatter::default());
$token   = $builder
    // Configures the issuer (iss claim)
    ->issuedBy('http://example.com')
    // Configures the audience (aud claim)
    ->permittedFor('http://example.org')
    // Configures the id (jti claim)
    ->identifiedBy('4f1g23a12aa')
    // Configures the time that the token was issue (iat claim)
    ->issuedAt($now)
    // Configures the time that the token can be used (nbf claim)
    ->canOnlyBeUsedAfter($now->modify('+1 minute'))
    // Configures the expiration time of the token (exp claim)
    ->expiresAt($now->modify('+1 hour'))
    // Configures a new claim, called "uid"
    ->withClaim('uid', 1)
    // Configures a new header, called "foo"
    ->withHeader('foo', 'bar')
    // Builds a new token
    ->getToken($algorithm, $signingKey);

var_dump($token->toString());

use Token\JWT\Parser;
use Token\JWT\Encoding\JoseEncoder;

$parser = new Parser(new JoseEncoder());

$token = $parser->parse(
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.'
    . 'eyJzdWIiOiIxMjM0NTY3ODkwIn0.'
    . '2gSBz9EOsQRN9I-3iSxJoFt7NtgV6Rm0IL6a8CAwl3Q'
);

var_dump($token->headers()); // Retrieves the token headers
var_dump($token->claims()); // Retrieves the token claims

use Token\JWT\Encoding\JoseEncoder;
use Token\JWT\Exceptions\RequiredConstraintsViolated;
use Token\JWT\Parser;
use Token\JWT\Validation\Constraint\RelatedTo;
use Token\JWT\Validation\Validator;

$parser = new Parser(new JoseEncoder());

$token = $parser->parse(
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.'
    . 'eyJzdWIiOiIxMjM0NTY3ODkwIn0.'
    . '2gSBz9EOsQRN9I-3iSxJoFt7NtgV6Rm0IL6a8CAwl3Q'
);

$validator = new Validator();

try {
    // $validator->assert($token, new RelatedTo('1234567891'));// throw an exception
    $validator->assert($token, new RelatedTo('1234567890'));
} catch (RequiredConstraintsViolated $e) {
    // list of constraints violation exceptions:
    var_dump($e->violations());
}

var_dump($token->toString());