Ultra lightweight JSON web token (JWT) library for PHP5.5 or newer
Switch branches/tags
Clone or download
Latest commit eb2f940 Aug 23, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src Apply fixes from StyleCI Aug 5, 2018
tests Apply fixes from StyleCI Aug 5, 2018
.editorconfig Everything Apr 13, 2017
.gitignore chore: git ignore coverage.xml Oct 24, 2017
.travis.yml build(travis): well no 5.4 actually Jul 14, 2018
LICENSE Initial commit Apr 13, 2017
README.md docs: [skip ci] Aug 23, 2018
composer.json chore: update php support msg Jul 14, 2018
phpunit.xml.dist Everything Apr 13, 2017

README.md

adhocore/jwt

If you are new to JWT or want to refresh your familiarity with it, please check jwt.io

Latest Version Travis Build Scrutinizer CI Codecov branch StyleCI Software License

  • Lightweight JSON Web Token (JWT) library for PHP5.5 or newer.

Installation

composer require adhocore/jwt

Usage

use Ahc\Jwt\JWT;

// Instantiate with key, algo, maxAge and leeway.
$jwt = new JWT('secret', 'HS256', 3600, 10);

Only the key is required. Defaults will be used for the rest:

$jwt = new JWT('secret');
// algo = HS256, maxAge = 3600, leeway = 0

For RS* algo, the key should be either a resource like below:

$key = openssl_pkey_new([
    'digest_alg' => 'sha256',
    'private_key_bits' => 1024,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
]);

OR, a string with full path to the RSA private key like below:

$key = '/path/to/rsa.key';

// Then, instantiate JWT with this key and RS* as algo:
$jwt = new JWT($key, 'RS384');

Pro You dont need to specify pub key path, that is deduced from priv key.

Generate JWT token from payload array:

$token = $jwt->encode([
    'uid'    => 1,
    'aud'    => 'http://site.com',
    'scopes' => ['user'],
    'iss'    => 'http://api.mysite.com',
]);

Retrieve the payload array:

$payload = $jwt->decode($token);

Oneliner:

$token   = (new JWT('topSecret', 'HS512', 1800))->encode(['uid' => 1, 'scopes' => ['user']]));
$payload = (new JWT('topSecret', 'HS512', 1800))->decode($token);

Pro

Can pass extra headers into encode() with second parameter:

$token = $jwt->encode($payload, ['hdr' => 'hdr_value']);

Spoof time() for testing token expiry:

$jwt->setTestTimestamp(time() + 10000);

// Throws Exception.
$jwt->parse($token);

Call again without parameter to stop spoofing time():

$jwt->setTestTimestamp();

Features

  • Six algorithms supported:
'HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512'
  • Leeway support 0-120 seconds.
  • Timestamp spoofing for tests.
  • Passphrase support for RS* algos.

Integration

Phalcon

Check adhocore/phalcon-ext.

Laravel/Lumen

Coming soon laravel-jwt.

Consideration

Be aware of some security related considerations as outlined here which can be valid for any JWT implementations.