• Stars
    star
    110
  • Rank 315,811 (Top 7 %)
  • Language
    PHP
  • Created over 10 years ago
  • Updated almost 9 years ago

Reviews

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

Repository Details

A JWT (JSON Web Token) Encoder & Decoder

JWT (JSON Web Token) Creation and Decoding Library

Build Status

This library allows for the creation and decoding of JWT (JSON Web Tokens).

Installation

This tool can be installed via Composer:

{
	"require": {
		"psecio/jwt": "1.*"
	}
}

Example Usage

In the example below, the JWT object is created and a Header instance is assigned (required). The JWt object is then assigned several claims: issuer, audience, issued at and not before to define data and how it could be processed. The encode method is then called with the key and a resulting JWT-formatted string is returned.

NOTE: The JWT token will be generated in the order the claims are provided. No sorting is done in the background.

The decode method can then be called on the data along with the key to return an object matching the state of the jwt object.

<?php

require_once 'vendor/autoload.php';

$key = "example_key";

$header = new \Psecio\Jwt\Header($key);
$jwt = new \Psecio\Jwt\Jwt($header);

$jwt
    ->issuer('http://example.org')
    ->audience('http://example.com')
	->issuedAt(1356999524)
	->notBefore(1357000000)
	->expireTime(time()+3600)
	->jwtId('id123456')
	->type('https://example.com/register');

$result = $jwt->encode();
echo 'ENCODED: '.print_r($result)."\n\n";
echo 'DECODED: '.var_export($jwt->decode($result), true);

?>

Encryption via OpenSSL

The JWT Library also supports encryption of the resulting JWT-formatted string. Here's an example of it in use:

<?php

require_once 'vendor/autoload.php';

$key = 'example_key';
$encryptKey = 'my-encryption-key';

$header = new \Psecio\Jwt\Header($key);
$jwt = new \Psecio\Jwt\Jwt($header);

$jwt
    ->issuer('http://example.org')
    ->audience('http://example.com')
	->issuedAt(1356999524)
	->notBefore(1357000000)
	->expireTime(time()+3600)
	->jwtId('id123456')
	->type('https://example.com/register');

$result = $jwt->encrypt('AES-256-CBC', '1234567812345678', $encryptKey);

echo 'ENCRYPTED: '.var_export($result, true)."\n";
echo "DECRYPTED: ".var_export($jwt->decrypt($result, 'AES-256-CBC', '1234567812345678', $encryptKey), true)."\n";

?>

Custom Claim values

You can also add your own custom claim values to the JWT payload using the custom method. The first paramater is the value and the second is the claim "type" (key):

<?php
require_once 'vendor/autoload.php';

$key = "example_key";

$header = new \Psecio\Jwt\Header($key);

$jwt = new \Psecio\Jwt\Jwt($header);
$jwt->custom('foobar', 'custom-claim');

// Or, you can add more than one at the same time with an array
$jwt->custom(array(
    'custom-claim' => 'foorbar',
    'key1' => 'value1'
));

$result = $jwt->encode();
echo 'ENCODED: '.print_r($result)."\n\n";
echo 'DECODED: '.var_export($jwt->decode($result), true);
?>

You can use any of the OpenSSL cypher methods provided by the openssl_get_cipher_methods on your system.

Supported Claim Types

  • Audience (aud)
  • Expire Time (exp)
  • Issued At (iat)
  • Issuer (iss)
  • JwtId (jit)
  • Not Before (nbf)
  • Subject (sub)
  • Private

Hashing types

By default this JWT tool uses HMAC hashing (HS256) to generate the signature for the request. There are other options for this that will use the OpenSSL functionality to let you use public and private keys for these methods:

  • HS256
  • HS384
  • HS512
  • ES256
  • ES384
  • ES512
  • RS256
  • RS384
  • RS512

You cannot use a simple text string for the key like you can with HMAC hashing, so you must provide a valid key instance for the library to use. Here's an example using a .pem private key file and the RS256 hashing:

<?php
$key = openssl_pkey_get_private('file://'.__DIR__.'/private.pem', 'test1234');

$header = new \Psecio\Jwt\Header($key);
$header->setAlgorithm('RS256');

// or you can define the hash algorithm on the init too:
$header = new \Psecio\Jwt\Header($key, 'RS256');
?>

An exception (\Psecio\Jwt\Exception\InvalidKeyException) will be thrown if the key is invalid and cannot be used in signing the request. If there is an error during the actual signing of the message, you will be thrown a \Psecio\Jwt\Exception\SignatureErrorException.

Documentation for JSON Web Tokens

More Repositories

1

iniscan

A php.ini scanner for best security practices
PHP
1,477
star
2

gatekeeper

Gatekeeper: An Authentication & Authorization Library
PHP
366
star
3

parse

Parse: A Static Security Scanner
PHP
357
star
4

versionscan

A PHP version scanner for reporting possible vulnerabilities
PHP
255
star
5

secure_dotenv

A secure .env handler with encrypted key/value storage
PHP
117
star
6

propauth

A library for property-based policy evaluation
PHP
59
star
7

invoke

Invoke: Route Authentication/Authorization Management
PHP
36
star
8

canary

Canary: Input Detection and Response
PHP
30
star
9

pwdcheck

A password strength checking utility
PHP
21
star
10

secure-api

Repository for the "Building a Secure API" series on Websec.io
PHP
16
star
11

csrf

CSRF Token Generation Library
PHP
13
star
12

uri

A secure URI generation and validation library
PHP
12
star
13

verify

Framework Agnostic Authentication & Authorization
PHP
11
star
14

protected-env-example

An example (Docker environment) showing the protection of sensitive information from PHP's file read
PHP
10
star
15

rift

A vulnerable application for teaching the basics of web application security
CSS
9
star
16

security-bundle

A bundle of recommended PHP security libraries
8
star
17

validation

A simple little validation library
PHP
7
star
18

dbot

Discord bot platform for PHP
PHP
7
star
19

session-encrypt

An encrypted session handler
6
star
20

fortify

Fortify provides a single, simple interface for handling authentication and authorization
PHP
6
star
21

notch

Notch: A Vulnerable Application
PHP
4
star
22

oauth2-discord

A Discord provider for the League OAuth2 Client
PHP
4
star
23

gatekeeper-ui

A web interface for the Gatekeeper Access Control System
JavaScript
3
star
24

gatekeeper-cli

A command line tool for the Gatekeeper auth framework
PHP
2
star
25

authorize

A comprehensive authorization library (ACL, RBAC, PBAC)
PHP
1
star
26

phpsecinfo

Code for the phpsecinfo.com site
PHP
1
star
27

userappio

An API library for using the UserApp.io Service
PHP
1
star
28

securingphp

Source for the Securing PHP website
PHP
1
star
29

vaultlib

A simple Vault client for PHP
PHP
1
star
30

statext

A PHP static site generator
PHP
1
star