PHP code example of webdevcave / jwt

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

    

webdevcave / jwt example snippets




use Webdevcave\Jwt\Token;
use Webdevcave\Jwt\SignerFactory;
use \Webdevcave\Jwt\Secrets\HsSecret;

$secret = new HsSecret('your_secret_here');
$token = Token::create()
    ->withSigner(SignerFactory::build('HS256')) //HS256 signer is provided by default. This could be omitted
    ->with('exp', strtotime('+ 1 hour')) //Expires in one hour
    ->sign($secret)
    ->toString();



use Webdevcave\Jwt\Token;

$token = Token::fromString('xxxx.yyyyy.zzzzz');
$isValid = $token->validate($secret);

if ($isValid) {
    $payload = $token->getPayload();
    $headers = $token->getHeaders();
}



use Webdevcave\Jwt\Token;
use Webdevcave\Jwt\SignerFactory;
use \Webdevcave\Jwt\Secrets\RsSecret;

$secret = new RsSecret('private_key', 'public_key');

//Generate a token string
$tokenString = Token::create()
    ->withSigner(SignerFactory::build('RS256'))
    ->with('exp', strtotime('+ 1 hour')) //Expires in one hour
    ->sign($secret)
    ->toString();

//Validating...
$token = Token::fromString($tokenString);
if ($token->validate($secret)) {
    //token is valid...
    $creationDate = date(DATE_RFC3339, $token->getPayload('iat'));
    $expirationDate = date(DATE_RFC3339, $token->getPayload('exp'));
    
    echo "Your token was created at $creationDate.";
    echo "It will expire at $expirationDate.";
}

use \Webdevcave\Jwt\Validator\Validator;

class MyClaimValidator extends Validator {
    /**
     * @return string
     */
    public function validates() : string
    {
        return 'my-claim'; //this will validate value inside 'my-claim', when set
    }
    
    /**
     * @param mixed $value
     * @return bool
     */
    public function validate(mixed $value) : bool
    {
        // this claim must contain value 'a', 'b' or 'c'
        $valid = in_array($value, ['a', 'b', 'c']);
        
        return $valid;
    }
}



use Webdevcave\Jwt\Token;

$token = Token::fromString('xxxx.yyyyy.zzzzz')
            ->assignValidator(new MyClaimValidator());

$isValid = $token->validate($mySecret);

if ($isValid) {
    $myClaim = $token->getPayload('my-claim');
}


use Webdevcave\Jwt\Token;

//Load from authorization bearer
$token1 = Token::fromAuthorizationBearer();

//Load from get parameters
$token2 = Token::fromQueryString('token');
$token3 = Token::fromQueryString('token2');