corviz/jwt

Lib for generating Json Web Tokens using PHP

v1.0 2022-03-22 11:38 UTC

This package is auto-updated.

Last update: 2024-11-22 23:20:17 UTC


README

JWT Logo

How to install

composer require corviz/jwt

Provided signers

Provided claim validators

Basic Usage

Generating token

<?php

use Corviz\Jwt\Token;
use Corviz\Jwt\SignerFactory;

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

Validating and reading values from a token

<?php

use Corviz\Jwt\Token;

$token = Token::fromString('xxxx.yyyyy.zzzzz');

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

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

Validating your private claims

First you have to create your validator

use \Corviz\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;
    }
}

Then all you have to do is assign your validator before running validate() method

<?php

use Corviz\Jwt\Token;

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

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

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