PHP code example of emarref / jwt

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

    

emarref / jwt example snippets


use Emarref\Jwt\Claim;

$token = new Emarref\Jwt\Token();

// Standard claims are supported
$token->addClaim(new Claim\Audience(['audience_1', 'audience_2']));
$token->addClaim(new Claim\Expiration(new \DateTime('30 minutes')));
$token->addClaim(new Claim\IssuedAt(new \DateTime('now')));
$token->addClaim(new Claim\Issuer('your_issuer'));
$token->addClaim(new Claim\JwtId('your_id'));
$token->addClaim(new Claim\NotBefore(new \DateTime('now')));
$token->addClaim(new Claim\Subject('your_subject'));

// Custom claims are supported
$token->addClaim(new Claim\PublicClaim('claim_name', 'claim_value'));
$token->addClaim(new Claim\PrivateClaim('claim_name', 'claim_value'));

$jwt = new Emarref\Jwt\Jwt();

$algorithm = new Emarref\Jwt\Algorithm\None();
$encryption = Emarref\Jwt\Encryption\Factory::create($algorithm);
$serializedToken = $jwt->serialize($token, $encryption);

$algorithm = new Emarref\Jwt\Algorithm\Hs256('verysecret');
$encryption = Emarref\Jwt\Encryption\Factory::create($algorithm);
$serializedToken = $jwt->serialize($token, $encryption);

$token = $jwt->deserialize($serializedToken);

$context = new Emarref\Jwt\Verification\Context($encryption);
$context->setAudience('audience_1');
$context->setIssuer('your_issuer');

try {
    $jwt->verify($token, $context);
} catch (Emarref\Jwt\Exception\VerificationException $e) {
    echo $e->getMessage();
}