PHPackages                             brainpicker/reallysimplejwt - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. brainpicker/reallysimplejwt

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

brainpicker/reallysimplejwt
===========================

A really simple library to generate user authentication JSON Web Tokens.

2.0.4(6y ago)087↓100%MITPHPPHP &gt;=7.1.0

Since Feb 19Pushed 6y agoCompare

[ Source](https://github.com/brainpicker/ReallySimpleJWT)[ Packagist](https://packagist.org/packages/brainpicker/reallysimplejwt)[ RSS](/packages/brainpicker-reallysimplejwt/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (27)Used By (0)

Really Simple JSON Web Tokens
=============================

[](#really-simple-json-web-tokens)

A simple PHP library for creating JSON Web Tokens that uses HMAC SHA256 to sign signatures. For basic usage the library exposes a static interface to allow developers to create a token that stores a user identifier and expiration time.

The library is also open to extension, developers can define their own encoding standard, set all the [RFC standard](https://tools.ietf.org/html/rfc7519) JWT claims and set their own private claims.

**Note:** Adapted quick and dirty for PHP 5.6 - not tests have been run to verify

Contents
--------

[](#contents)

- [What is a JSON Web Token?](#what-is-a-json-web-token)
- [Setup](#setup)
- [Basic Usage](#basic-usage)
    - [Create Token](#create-token)
    - [Validate Token](#validate-token)
    - [Get Header and Payload Claims Data](#get-header-and-payload-claims-data)
    - [Factory Methods](#factory-methods)
- [Advanced Usage](#advanced-usage)
    - [Create Custom Token](#create-custom-token)
    - [Access the Token](#access-the-token)
    - [Parse and Validate Token](#parse-and-validate-token)
    - [Access Token Claims Data](#access-token-claims-data)
    - [Customised Encoding](#customised-encoding)
- [Error Messages and Codes](#error-messages-and-codes)
- [Token Security](#token-security)
    - [Signature Secret](#signature-secret)
- [Version One Support](#version-one-support)

What is a JSON Web Token?
-------------------------

[](#what-is-a-json-web-token)

JSON Web Tokens is a standard for creating URL friendly access tokens that assert claims about a user or system.

A token is broken down into three parts; the header, the payload and the signature; with each part separated by a dot. Each part is encoded using the base64url standard, see the [RFC](https://tools.ietf.org/html/rfc4648#page-7).

An example JWT:

```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

```

The header and payload are both encoded JSON strings that contain a number of claims:

```
// Header
{
  "alg": "HS256",
  "typ": "JWT"
}

// Payload
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}
```

A claim is a key value pair, eg `"typ": "JWT"`, please read [RFC 7519](https://tools.ietf.org/html/rfc7519#section-4) to learn more about JSON Web Token claims.

Token security is achieved via the signature which is made up of the header, payload and a secret known only to the token author. This information is hashed and then base64url encoded.

If a malicious user attempts to edit the header or payload claims they will be unable to replicate the signature so long as you use a strong key. See [Token Security](#token-security) for more information on this.

Setup
-----

[](#setup)

Via Composer on the command line:

```
composer require rbdwllr/reallysimplejwt
```

Via composer.json:

```
"require": {
    "rbdwllr/reallysimplejwt": "^2.0"
}
```

Basic Usage
-----------

[](#basic-usage)

For basic usage the library exposes a set of static methods via the `ReallySimpleJWT\Token` class which allow a developer to create and validate basic JSON Web Tokens.

### Create Token

[](#create-token)

Call the `create()` static method and pass in a user identifier, a secret, an expiration date time number and the token issuer.

This will return a token string on success and throw a `ReallySimpleJWT\Exception\ValidateException` on failure.

```
use ReallySimpleJWT\Token;

$userId = 12;
$secret = 'sec!ReT423*&';
$expiration = time() + 3600;
$issuer = 'localhost';

$token = Token::create($userId, $secret, $expiration, $issuer);
```

To create a more customised token developers can use the `customPayload()` method. This allows the creation of a token based on an array of key value pairs which represent the payload claims.

```
use ReallySimpleJWT\Token;

$payload = [
    'iat' => time(),
    'uid' => 1,
    'exp' => time() + 10,
    'iss' => 'localhost'
];

$secret = 'Hello&MikeFooBar123';

$token = Token::customPayload($payload, $secret);
```

On success the `customPayload()` method will return a JWT token string and on failure it will throw an exception.

### Validate Token

[](#validate-token)

To validate a JSON web token call the `validate()` static method, pass in the token string and the secret. The validate method checks the token structure is correct, the signature is valid, the expiration time has not expired and the not before time has elapsed.

It will return true on success and false on failure.

```
use ReallySimpleJWT\Token;

$token = 'aaa.bbb.ccc';
$secret = 'sec!ReT423*&'

$result = Token::validate($token, $secret);
```

### Get Header and Payload Claims Data

[](#get-header-and-payload-claims-data)

To retrieve the token claims data from the header or payload call the `getHeader()` and or `getPayload()` static methods.

Both methods will return an associative array on success and throw an exception on failure.

```
use ReallySimpleJWT\Token;

$token = 'aaa.bbb.ccc';
$secret = 'sec!ReT423*&'

// Return the header claims
Token::getHeader($token, $secret);

// Return the payload claims
Token::getPayload($token, $secret);
```

### Factory Methods

[](#factory-methods)

The `ReallySimpleJWT\Token` class also provides two factory methods to gain access to the core `ReallySimpleJWT\Build` and `ReallySimpleJWT\Parse` classes.

```
Token::builder(); // Returns an instance of ReallySimpleJWT\Build

Token::parser($token, $secret); // Returns an instance of ReallySimpleJWT\Parse
```

Advanced Usage
--------------

[](#advanced-usage)

To create customised JSON Web Tokens developers need to access the `ReallySimpleJWT\Build` and `ReallySimpleJWT\Parse` classes directly.

### Create Custom Token

[](#create-custom-token)

The `ReallySimpleJWT\Build` class allows you to create a completely unique JSON Web Token. It has helper methods for all the [RFC](https://tools.ietf.org/html/rfc7519#section-4) defined header and payload claims. For example, the `setIssuer()` method will add the `iss` claim to the token payload.

The class also allows developers to set custom header and payload claims via the `setHeaderClaim()` and `setPayloadClaim()` methods.

The methods can be chained together and when the `build()` method is called the token will be generated and returned within a `ReallySimpleJWT\Jwt` object.

```
use ReallySimpleJWT\Build;
use ReallySimpleJWT\Validate;
use ReallySimpleJWT\Encode;

$build = new Build('JWT', new Validate(), new Encode());

$token = $build->setContentType('JWT')
    ->setHeaderClaim('info', 'foo')
    ->setSecret('!secReT$123*')
    ->setIssuer('localhost')
    ->setSubject('admins')
    ->setAudience('https://google.com')
    ->setExpiration(time() + 30)
    ->setNotBefore(time() - 30)
    ->setIssuedAt(time())
    ->setJwtId('123ABC')
    ->setPayloadClaim('uid', 12)
    ->build();
```

### Access the Token

[](#access-the-token)

A `ReallySimpleJWT\Jwt` object is returned when a developer calls the `build()` method on the `ReallySimpleJWT\Build` class. The Jwt class offers two methods `getToken()` and `getSecret()`. The former returns the generated JSON Web Token and the latter returns the secret used for the token signature.

To parse a JSON Web Token via the `ReallySimpleJWT\Parse` class a developer must first create a new `ReallySimpleJWT\Jwt` object by injecting the token and secret.

```
use ReallySimpleJWT\Jwt;

$token = 'aaa.bbb.ccc';
$secret = '!secReT$123*';

$jwt = new Jwt($token, $secret);

// Return the token
$jwt->getToken();

// Return the secret
$jwt->getSecret();
```

### Parse and Validate Token

[](#parse-and-validate-token)

The `ReallySimpleJWT\Parse` class allows a developer to parse and validate a JSON Web Token. Three validation methods are available which can all be chained:

- `validate()` confirms the structure of the token and the validity of the signature.
- `validateExpiration()` confirms the token expiration claim (`exp`) has not expired.
- `validateNotBefore()` confirms the token not before claim (`nbf`) has elapsed.

Each validation method will throw a `ReallySimpleJWT\Exception\ValidateException` if there is anything wrong with the supplied token.

The `parse()` method which should be called after validation is complete will decode the JSON Web Token. It will then return the result as a `ReallySimpleJWT\Parsed` object. This will provide access to the claims data the token holds in the header and the payload.

```
use ReallySimpleJWT\Parse;
use ReallySimpleJWT\Jwt;
use ReallySimpleJWT\Validate;
use ReallySimpleJWT\Encode;

$token = 'aaa.bbb.ccc';
$secret = '!secReT$123*';

$jwt = new Jwt($token, $secret);

$parse = new Parse($jwt, new Validate(), new Encode());

$parsed = $parse->validate()
    ->validateExpiration()
    ->validateNotBefore()
    ->parse();

// Return the token header claims as an associative array.
$parsed->getHeader();

// Return the token payload claims as an associative array.
$parsed->getPayload();
```

### Access Token Claims Data

[](#access-token-claims-data)

The `ReallySimpleJWT\Parsed` class is returned when a developer calls the `parse()` method on the `ReallySimpleJWT\Parse` class.

It provides a number of helper methods to gain access to the token claim data. A developer can call the `getHeader()` and `getPayload()` methods to gain access to the respective claim data as associative arrays.

Alternatively a developer can call one of the [RFC](https://tools.ietf.org/html/rfc7519#section-4) compliant claim methods:

**Header**

- `getAlgorithm()`
- `getType()`
- `getContentType()`

**Payload**

- `getIssuer()`
- `getSubject()`
- `getAudience()`
- `getExpiration()`
- `getNotBefore()`
- `getIssuedAt()`
- `getJwtId()`

### Customised Encoding

[](#customised-encoding)

By default this library hashes and encodes the JWT signature via `hash_hmac()` using the sha256 algorithm. If a developer would like to use a customised form of encoding they just need to generate a custom encode class which complies with the `ReallySimpleJWT\Interfaces\EncodeInterface`.

```
interface EncodeInterface
{
    public function getAlgorithm(): string;

    public function encode(string $toEncode): string;

    public function decode(string $toDecode): string;

    public function signature(string $header, string $payload, string $secret): string;
}
```

Error Messages and Codes
------------------------

[](#error-messages-and-codes)

The ReallySimpleJWT library will in a number of situations throw exceptions to highlight problems when creating and parsing JWT tokens. The error codes, messages and their explanations are below.

CodeMessageExplanation1Token is invalid.Token must have three parts separated by dots.2\*Token could not be parsed.Something weird happened ;) undefined problem with the token.3Signature is invalid.Signature does not match header / payload content. Could not replicate signature with provided header and payload.4Expiration claim has expired.The exp claim must be a valid date time number in the future.5Not Before claim has not elapsed.The nbf claim must be a valid date time number in the past.6Expiration claim is not set.Attempt was made to validate an Expiration claim which does not exist.7Not Before claim is not set.Attempt was made to validate a Not Before claim which does not exist.8Invalid payload claim.Payload claims must be key value pairs of the format string:mixed.9Invalid secret.Must be 12 characters in length, contain upper and lower case letters, a number, and a special character `\*&amp;!@%^#$``10Invalid Audience claim.The aud claim can either be a string or an array of strings nothing else.\* No longer in use, library will not generate this error code.

Token Security
--------------

[](#token-security)

The JWT [RFC 7519](https://tools.ietf.org/html/rfc7519#section-7) allows for the creation of tokens without signatures and without secured / hashed signatures. The ReallySimpleJWT library however imposes security by default as there is no logical reason not to. All created tokens must have a signature and a strong secret, but the library will validate tokens without a secret or a strong secret. The library will not validate tokens without a signature.

It is possible to edit and enhance the implementation of the signature and its security level by creating a custom encode class that implements the `ReallySimpleJWT\Interfaces\EncodeInterface`. See section [Customised Encoding](#customised-encoding)

### Signature Secret

[](#signature-secret)

This JWT library imposes strict secret security as follows: the secret must be at least 12 characters in length; contain numbers; upper and lowercase letters; and one of the following special characters `*&!@%^#$`.

```
// Bad Secret
secret123

// Good Secret
sec!ReT423*&
```

The reason for this is that there are lots of [JWT Crackers](https://github.com/lmammino/jwt-cracker) available meaning weak secrets are easy to crack thus rendering the security JWT offers useless.

Version One Support
-------------------

[](#version-one-support)

Support for version one of this library will continue until July 2019. No new features will be added to the version, just bug fixes and security patches.

License
-------

[](#license)

MIT

Author
------

[](#author)

Rob Waller

Twitter: [@robdwaller](https://twitter.com/RobDWaller)

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 97.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~32 days

Total

26

Last Release

2544d ago

Major Versions

0.2 → 1.0.02018-01-27

1.0.6 → 2.0.0-alpha2018-12-10

1.1.0 → 2.0.0-alpha12018-12-12

1.x-dev → 2.0.0-rc2019-01-02

PHP version history (3 changes)v0.1-alpha1PHP &gt;=5.6.0

1.0.0PHP &gt;=7.0.0

2.0.0-alphaPHP &gt;=7.1.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/c8a60f17c907e326dce6829e00f41bc9b47f6ae1c9325b2900cc33744d7e27e7?d=identicon)[brainpicker](/maintainers/brainpicker)

---

Top Contributors

[![RobDWaller](https://avatars.githubusercontent.com/u/634080?v=4)](https://github.com/RobDWaller "RobDWaller (215 commits)")[![brainpicker](https://avatars.githubusercontent.com/u/5030167?v=4)](https://github.com/brainpicker "brainpicker (2 commits)")[![B3none](https://avatars.githubusercontent.com/u/24966460?v=4)](https://github.com/B3none "B3none (1 commits)")[![joelcuevas](https://avatars.githubusercontent.com/u/275014?v=4)](https://github.com/joelcuevas "joelcuevas (1 commits)")[![pixeline](https://avatars.githubusercontent.com/u/393415?v=4)](https://github.com/pixeline "pixeline (1 commits)")

---

Tags

phpjwtjsontokensAuthenticationjson web tokens

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/brainpicker-reallysimplejwt/health.svg)

```
[![Health](https://phpackages.com/badges/brainpicker-reallysimplejwt/health.svg)](https://phpackages.com/packages/brainpicker-reallysimplejwt)
```

###  Alternatives

[rbdwllr/reallysimplejwt

A really simple library to generate user authentication JSON Web Tokens.

2902.4M22](/packages/rbdwllr-reallysimplejwt)[rbdwllr/psr-jwt

A PSR 7 compliant JSON Web Token Middleware Library.

1658.0k7](/packages/rbdwllr-psr-jwt)[vizir/laravel-keycloak-web-guard

Simple Keycloak Guard to Laravel Web Routes

166574.1k](/packages/vizir-laravel-keycloak-web-guard)[maicol07/flarum-ext-sso

SSO for Flarum

468.3k](/packages/maicol07-flarum-ext-sso)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
