PHP code example of marvin255 / jwt

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

    

marvin255 / jwt example snippets


use Marvin255\Jwt\JwtFactory;

$token = JwtFactory::decoder()->decodeHeader($_SERVER['HTTP_AUTHORIZE']);

use Marvin255\Jwt\JwtFactory;
use Marvin255\Jwt\JwtSecretFactory;
use Marvin255\Jwt\JwtSignerFactory;
use Marvin255\Jwt\Signer\Algorithm;
use Marvin255\Jwt\Validator\ExpirationConstraint;
use Marvin255\Jwt\Validator\NotBeforeConstraint;
use Marvin255\Jwt\Validator\AudienceConstraint;
use Marvin255\Jwt\Validator\SignatureConstraint;

$publicKey = JwtSecretFactory::create('file:///path/to/public.key');
$signer = JwtSignerFactory::createRsa(Algorithm::RSA_SHA_512, $publicKey);

$constraints = [
    new ExpirationConstraint(3),          // checks that token is not expired with 3s leeway
    new NotBeforeConstraint(3),           // checks nbf header with 3s leeway
    new AudienceConstraint('my_service'), // checks that token was issued for this service
    new SignatureConstraint($signer),     // checks signature
];

$res = JwtFactory::validator()->validate($token, $constraints);
if ($res->isValid()) {
    echo "token is valid";
} else {
    var_dump($res->getErrors());
}

// jose params
$alg = $token->jose()->alg()->get();                           // registered JOSE params have own getters
$customParam = $token->jose()->param('custom_jose')->get();    // any custom JOSE param from the payload

// claims
$iss = $token->claims()->iss()->get();                         // registered claims have own getters
$customClaim = $token->claims()->param('custom_claim')->get(); // any custom claim from the payload

use Marvin255\Jwt\JwtFactory;
use Marvin255\Jwt\JwtSecretFactory;
use Marvin255\Jwt\JwtSignerFactory;
use Marvin255\Jwt\Signer\Algorithm;

$privateKey = JwtSecretFactory::create('file:///path/to/private.key');
$signer = JwtSignerFactory::createRsa(Algorithm::RSA_SHA_512, null, $privateKey);

$token = JwtFactory::builder()
    ->setJoseParam('test', 'test') // any custom JOSE param
    ->setIss('test')               // registered claims have own setters
    ->setClaim('test', 'test')     // any custom claim
    ->signWith($signer)            // signer
    ->build()
;

use Marvin255\Jwt\JwtFactory;

$tokenString = JwtFactory::encoder()->encode($token);