• Stars
    star
    271
  • Rank 151,717 (Top 3 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ultra lightweight, dependency free and standalone JSON web token (JWT) library for PHP5.6 to PHP8.2. This library makes JWT a cheese. It is a minimal JWT integration for PHP.

adhocore/jwt

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

Latest Version Build Scrutinizer CI Codecov branch StyleCI Software License Tweet Support

  • Lightweight JSON Web Token (JWT) library for PHP7.
  • Zero dependency (no vendor bloat).
  • If you still use PHP5.6, use version 0.1.2

Installation

# PHP7.0+
composer require adhocore/jwt

# PHP5.6
composer require adhocore/jwt:0.1.2

# For PHP5.4-5.5, use version 0.1.2 with a polyfill for https://php.net/hash_equals

Features

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

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']);

Test mocking

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

Examples with kid

$jwt = new JWT(['key1' => 'secret1', 'key2' => 'secret2']);

// Use key2
$token = $jwt->encode(['a' => 1, 'exp' => time() + 1000], ['kid' => 'key2']);

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

$token = $jwt->encode(['a' => 1, 'exp' => time() + 1000], ['kid' => 'key3']);
// -> Exception with message Unknown key ID key3

Stabillity

The library is now marked at version 1.*.* as being stable in functionality and API.

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.

More Repositories

1

php-cli

PHP Console Application made easy- build great console apps with ease. Comes with Zero Dependency and Autocompletion support. Think of it as a PHP cli application framework.
PHP
333
star
2

gronx

Lightweight, fast and dependency-free Cron expression parser (due checker, next/prev due date finder), task runner, job scheduler and/or daemon for Golang (tested on v1.13+) and standalone usage. If you are bold, use it to replace crontab entirely.
Go
317
star
3

urlsh

Golang URL shortener and bookmarker service with UI, API, Cache, Hits Counter and forwarder using postgres and redis in backend, bulma in frontend. Think of it as self hosting ready url shortener.
Go
144
star
4

docker-phpfpm

Lightweight (~100mb) Docker PHP FPM for both arm and amd arch on alpine 3.17 with PHP8.0.30/8.1.25/8.2.12 (also 7.4.33) with ~82-84 useful extensions (you can disable not necessary ones easily)
Dockerfile
96
star
5

phint

Interactively scaffolds and init new (or fixup old) PHP project/library with sane defaults using templates in no time
PHP
93
star
6

please

please is semver release made easy, detects current version from API or tags and next version from commits, creates detailed changelogs that are configurable.
Shell
86
star
7

fast

Check your internet speed/bandwidth right from your terminal. Built on Golang using chromedp
Go
81
star
8

php-cron-expr

Ultra lightweight, Dependency free and Super Fast Cron Expression parser for PHP
PHP
51
star
9

htmlup

Light and fast markdown parser, that parses markdown in a way human does
PHP
50
star
10

php-json-fixer

Fix truncated JSON data
PHP
45
star
11

php-underscore

PHP underscore inspired &/or cloned from _.js, with extra goodies like higher order messaging
PHP
44
star
12

phalcon-ext

Foundations, adapters, extensions, middlewares and utilities for Phalcon v4
PHP
42
star
13

tusc.sh

tus 1.0.0 client protocol implementation for bash. Resumable large file upload to Tus sever from terminal using bash script
Shell
32
star
14

chin

A Go lang library to show a spinner as user waits for any long running jobs to finish.
Go
31
star
15

goic

Golang OpenID Connect Client
Go
28
star
16

php-json-comment

Lightweight JSON comment and trailing comma stripper library for PHP with support for literal newlines and nested JSON strings.
PHP
27
star
17

php-env

A small and fast .env loader for PHP
PHP
23
star
18

with

With provides object like fluent interface for scalars and non-objects
PHP
17
star
19

jquery-plugins

jQuery plugins: BS calendar & datepicker, auto form filler, css grid float top, lazy & ajax pagination
JavaScript
16
star
20

crx-jtrans

jTransliter - the roman to unicode transliter as Google chrome extension
JavaScript
15
star
21

dsa

data structure and algorithm - examples and implementations
PHP
15
star
22

stiky

modular backbonejs application for sticky notes
JavaScript
14
star
23

jsonc

Golang (v1.13+) JSON5 preprocessor supporting comments, trailing comma, unquoted key/single-quoted string, hex number, trailing decimal point, literal newlines and more.
Go
14
star
24

twig-yall

Resource lazy loader extension for twig using malchata/yall.js
PHP
12
star
25

crx-loshin

loshin, the Load Shedding Indicator
JavaScript
12
star
26

php-cli-syntax

PHP Code Syntax Highlighter and/or exporter for CLI. Zero Dependency.
PHP
11
star
27

vue-inventory

Vue JS inventory app for hotel
HTML
11
star
28

php-env-bench

Benchmarking env loaders/parsers for PHP.
PHP
11
star
29

fsb

f...ing simple benchmark(ing)
PHP
10
star
30

get-in

Handy Traversal of chained objects with error trap and default value (suited for View)
PHP
9
star
31

sublime-phpcsfixer

A simple and minimal plugin for sublime editor to fix php files with php-cs-fixer via context menu
Python
9
star
32

php-cron-bench

Benchmarking cron parsers for PHP.
PHP
9
star
33

asserts

More PHPUnit assertions as a Trait
PHP
9
star
34

log-viewer

Simple log viewer app built with Lumen framework and VueJS
PHP
9
star
35

php-polyfills

Miscellaneous polyfills for older PHP versions
PHP
8
star
36

win-cli-launcher

a command line launcher for windows os
Batchfile
8
star
37

py-routes

Python recursive shortest path algo to find the optimal route between two points in terms of number of stops and duration
Python
8
star
38

php-tools

php tools for string, numbers, dates etc
PHP
7
star
39

gh-sc

Cancel all but the last SC automatically
JavaScript
7
star
40

plastic

PHP elasticsearch wrapper designed to be minimal, intuitive and dependency free
PHP
7
star
41

ci-captcha

Easy, hassle free, plug and play Code Igniter captcha library [OLD CODE]
PHP
7
star
42

live-console

PHP live console in browser
PHP
6
star
43

crx-adblock

chrome extension to hide/block custom ads
JavaScript
6
star
44

crx-joom

auto zoom the webpage for more readability and less eye stress
JavaScript
6
star
45

adhocore.github.io

adhocore.github.io
HTML
5
star
46

adhocore

5
star
47

php-adhocore

A PHP framework I created in early 2013 - inspired by CodeIgniter. Published here for historical reason. It was still a work in progress and was not complete- I am afraid it may as well never be. Check the initial commit.
PHP
5
star
48

leetcode

Just some leet code solutions in Python
Python
3
star
49

zshist

ZSH history manager: merge/deduplicate/normalize history entries for zsh, arrow suggestion UX is improved (plus save space, remove redundancy)
Go
2
star
50

opentelemetry

Temp mirror of old version of open-telemetry/opentelemetry
PHP
2
star
51

import-configuration-jms

Clone of techdivision/import-configuration-jms
PHP
2
star
52

docker-php-fpm-old-alpine

Mirror of official PHP docker images built on alpine 3.13/3/14 instead of 3.15/3.16
Dockerfile
2
star