marvin255 / jwt
Yet another jwt for PHP.
v2.1.1
2024-06-08 13:30 UTC
Requires
- php: >=8.1
- marvin255/optional: ^0.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- infection/infection: ^0.27
- phpunit/phpunit: ^10.0
- vimeo/psalm: ^5.0
This package is auto-updated.
Last update: 2024-12-01 00:09:02 UTC
README
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);