Yet another jwt for PHP.

v2.1.1 2024-06-08 13:30 UTC

This package is auto-updated.

Last update: 2024-10-31 08:58:00 UTC


README

Build Status

Simple JWT implementation for PHP.

Installation

Install package via composer

composer req marvin255/jwt

Parse token from header

use Marvin255\Jwt\JwtFactory;

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

Validate token

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());
}

Retrieve data from token

// 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

Create new token

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()
;

Encode token to string

use Marvin255\Jwt\JwtFactory;

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