PHP code example of okneloper / jwt-validators

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

    

okneloper / jwt-validators example snippets


use Lcobucci\JWT\Builder;

$token = (new Builder())->setIssuer('http://example.com') // Configures the issuer (iss claim)
    ->setAudience('http://example.org') // Configures the audience (aud claim)
    ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
    ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
    ->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
    ->setExpiration(time() + 3600) // Configures the expiration time of the token (nbf claim)
    ->set('uid', 1) // Configures a new claim, called "uid"
    ->getToken(); // Retrieves the generated token


$validator = new \Okneloper\JwtValidators\Validator();
// 

$validator->add(new ClaimPresenceValidator('iss')); //  

$validator->add(new ExpirationValidator());
 
$validator->addValidator(new LifetimeValidator(60)); // 60 seconds

$validator->addValidator(new SignaturePresenceValidator());

// find the user by uid stored in the token
$user = User::find($token->getClaim('uid'));
// example checker that will check the database if a token id
// previously provided by the $user has been processed before
$checker = new CustomChecker($user);
// add this validator same as any other
$validator->addValidator(new UniqueJtiValidator($checker));

interface ITokenValidator
{
    /**
     * Returns true if the token validates against this validator
     * @param \Lcobucci\JWT\Token $token
     * @return bool
     */
    public function validates(\Lcobucci\JWT\Token $token, $breakOnFirstError = true);

    /**
     * @return string
     */
    public function getErrors();
}

class CustomValidator extends TokenValidator
{
    public function __construct()
    {
        // the second argument is optional
        parent::__construct("The username is too long", new ClaimPresenceValidator('username'));
    }

    protected function isValid(\Lcobucci\JWT\Token $token)
    {
        return strlen($token->getClaim('username')) <= 10;
    }
}