Lib for generating Json Web Tokens using PHP

v1.1.1 2024-07-16 00:18 UTC

This package is auto-updated.

Last update: 2024-12-16 01:18:08 UTC


README

codecov Latest Stable Version Latest Unstable Version Total Downloads License StyleCI

How to install

composer require webdevcave/jwt

Provided signers

Provided claim validators

  • "typ" claim is defined as JWT by default.
  • "iat" and "nbf" claims are starts with the current timestamp by default.
  • "jti" validator isn't provided but it can be implemented by your application as presented in "Validating your private claims" section

Basic Usage

Generating a token

<?php

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

Validating and reading values from a token

<?php

use Webdevcave\Jwt\Token;

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

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

RSA Tokens:

First of all, you will need a public/private key pair. If you don't have one, you can generate it easily at the following page: https://cryptotools.net/rsagen

With your public/private key pair in hand, the process will be similar to the hmac tokens in the above example:

<?php

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.";
}

Validating your private claims

First you have to create your validator

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

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

<?php

use Webdevcave\Jwt\Token;

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

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

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

Shortcuts

You can get an Token instance directly from the Authorization header or through a query parameter with the following methods:

use Webdevcave\Jwt\Token;

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

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

Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or a pull request on GitHub.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Credits

Original project can be found here