PHPackages                             zenstruck/jwt - 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. zenstruck/jwt

Abandoned → [firebase/php-jwt](/?search=firebase%2Fphp-jwt)ArchivedLibrary[Authentication &amp; Authorization](/categories/authentication)

zenstruck/jwt
=============

JSON Object Signing and Encryption library for PHP.

v1.0.0(10y ago)174.2k↓38.4%1MITPHPPHP &gt;=5.4.8

Since Dec 9Pushed 10y ago2 watchersCompare

[ Source](https://github.com/kbond/php-jwt)[ Packagist](https://packagist.org/packages/zenstruck/jwt)[ RSS](/packages/zenstruck-jwt/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (3)Used By (0)

zenstruck/jwt
=============

[](#zenstruckjwt)

[![Build Status](https://camo.githubusercontent.com/1a3d86d54e3843d95edf2da2ff79b7c0df34e88e5c1c93894d77bccd56d10916/687474703a2f2f696d672e736869656c64732e696f2f7472617669732f6b626f6e642f7068702d6a77742e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/kbond/php-jwt)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/08fa42dd09522ba49014342fdcd94fe1140a9bf4c4d7ef05870e3aceb6aaaecd/687474703a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6b626f6e642f7068702d6a77742e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/kbond/php-jwt/)[![Code Coverage](https://camo.githubusercontent.com/e4d638e47431d2fba567a975e01cc233b757e3fb694336a8e74cc6612226376d/687474703a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f6b626f6e642f7068702d6a77742e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/kbond/php-jwt/)[![SensioLabs Insight](https://camo.githubusercontent.com/cbabd912e088a11a42ac448e5a1c01d63ab2ec7ccd0e3c51bfd4b548e61ca477/68747470733a2f2f696d672e736869656c64732e696f2f73656e73696f6c6162732f692f35343137666639382d626537372d346638322d623466662d3562323635306335363538332e7376673f7374796c653d666c61742d737175617265)](https://insight.sensiolabs.com/projects/5417ff98-be77-4f82-b4ff-5b2650c56583)[![StyleCI](https://camo.githubusercontent.com/7472bf4b733eb700ff1ddabe032bca49ed7d8a7acafa901b4a61ab9b924a6246/68747470733a2f2f7374796c6563692e696f2f7265706f732f34333433303833312f736869656c64)](https://styleci.io/repos/43430831)[![Latest Stable Version](https://camo.githubusercontent.com/c653c002097c8f9b3bd28234c1bc661acc469833f621ed273d31471a5a339e01/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7a656e73747275636b2f6a77742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/zenstruck/jwt)[![License](https://camo.githubusercontent.com/6ef6de7dbb2abe6c62a24179408cd0cfdfcf6b2e86e9cbb83ae417a220a19a10/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7a656e73747275636b2f6a77742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/zenstruck/jwt)

Provides a lightweight implementation of the JWS ([JSON Web Signature](http://tools.ietf.org/html/draft-jones-json-web-signature-04)) specification. This library is a fork of [namshi/jose](https://github.com/namshi/jose).

Requirements
------------

[](#requirements)

1. **PHP 5.4.8+** (tested on 5.4, 5.5, 5.6, 7 and HHVM)
2. *(Optional)* OpenSSL extension (when using RSA/ECDSA signers)
3. *(Optional)* [symfony/polyfill-php56](https://packagist.org/packages/symfony/polyfill-php56) library (when HMAC signers in PHP versions less than 5.6)

Installation
------------

[](#installation)

```
composer require zenstruck/jwt

```

**When using an HMAC signer in PHP versions less than 5.6**

```
composer require symfony/polyfill-php56

```

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

[](#basic-usage)

1. Create, encode and send a token to the user:

    ```
    use Zenstruck\JWT\Token;
    use Zenstruck\JWT\Signer\HMAC\HS256;

    // create the token
    $token = new Token([
        'username' => 'kevin', // custom claim
        'iss' => 'zenstruck', // set issuer
        'exp' => time() + 86400, // set expiry claim to 1 day from now
    ]);

    // can access claims
    $token->get('username'); // kevin
    $token->get('non-existant'); // null

    // sign the token
    $token->sign(new HS256(), 'my secret key');

    $encodedTokenForUser = (string) $token;

    // ...pass to user
    ```
2. Fetch encoded token from user, decode, verify, validate and access custom claims

    ```
    use Zenstruck\JWT\Token;
    use Zenstruck\JWT\Signer\HMAC\HS256;
    use Zenstuck\JWT\Validator\ExpiresAtValidator;
    use Zenstuck\JWT\Validator\IssuerValidator;
    use Zenstruck\JWT\Exception\MalformedToken;
    use Zenstruck\JWT\Exception\UnverifiedToken;
    use Zenstruck\JWT\Exception\Validation\ExpiredToken;
    use Zenstruck\JWT\Exception\ValidationFailed;

    $encodedTokenFromUser = // ...fetched from user

    try {
        $decodedToken = Token::fromString($encodedTokenFromUser);
    } catch (MalformedToken $e) {
        // token is not correctly formed
    }

    // at this point $decodedToken is a JWT but is not yet verified or validated

    try {
        $decodedToken->verify(new HS256(), 'my secret key');
    } catch (UnverifiedToken $e) {
        // token could not be verified
    }

    try {
        $decodedToken->validate(new ExpiresAtValidator());
        $decodedToken->validate(new IssuerValidator('zenstruck'));
    } catch (ExpiredToken $e) {
        // the token has expired
    } catch (ValidationFailed $e) {
        // token is invalid - in this case, the issuer does not match
    }

    // can access claims
    $token->get('username'); // kevin
    $token->get('non-existant'); // null
    ```

Token Builder
-------------

[](#token-builder)

```
use Zenstruck\JWT\TokenBuilder;

$token = (new TokenBuilder())
    ->issuer('kevin')
    ->subject('zenstruck\jwt')
    ->audience('php community')
    ->expiresAt(new \DateTime('+1 day'))
    ->notBefore(new \DateTime('+1 hour'))
    ->issuedAt() // can pass \DateTime object - uses current time by default
    ->id('foo')
    ->set('foo', 'bar') // set custom claims
    ->create(); // instance of Zenstruck\JWT\Token
```

Signers
-------

[](#signers)

### HMAC

[](#hmac)

These signers require an identical key string to be used for signing and validating.

AlgorithmSigner ClassHS256`Zenstruck\JWT\Signer\HMAC\HS256`HS384`Zenstruck\JWT\Signer\HMAC\HS384`HS512`Zenstruck\JWT\Signer\HMAC\HS512`#### Usage

[](#usage)

```
$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above

$token->sign($signer, 'my secret key');
$token->verify($signer, 'my secret key'); // verified
$token->verify($signer, 'invalid secret key'); // unverified - exception thrown
```

### RSA/ECDSA (OpenSSL)

[](#rsaecdsa-openssl)

These signers require a private key for signing and a public key for verifying.

- **PrivateKey**: a `string` (key contents or filename), `resource` or instance of `Zenstruck\JWT\Signer\OpenSSL\PrivateKey`
- **PublicKey**: a `string` (key contents or filename), `resource` or instance of `Zenstruck\JWT\Signer\OpenSSL\PublicKey`
- **Keychain**: instance of `Zenstruck\JWT\Signer\OpenSSL\Keychain` contains both a public and private key. Can be passed as the key to both `Signer::sign()` and `Signer::verify()`.

AlgorithmSigner ClassRS256`Zenstruck\JWT\Signer\OpenSSL\RSA\RS256`RS384`Zenstruck\JWT\Signer\OpenSSL\RSA\RS384`RS512`Zenstruck\JWT\Signer\OpenSSL\RSA\RS512`ES256`Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256`ES384`Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES384`ES512`Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES512`#### Usage

[](#usage-1)

```
$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above
$privateKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PrivateKey, instance of Zenstruck\JWT\Signer\OpenSSL\Keychain
$publicKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PublicKey, instance of Zenstruck\JWT\Signer\OpenSSL\Keychain

$token->sign($signer, $privateKey);
$token->verify($signer, $publicKey); // verified
$token->verify($signer, '/path/to/unmatched/public/key'); // unverified - exception thrown
```

##### Keychain

[](#keychain)

A keychain contains both a public and private key. When passed a keychain as the key, the signer uses the proper key for the operation.

```
use Zenstruck\JWT\Signer\OpenSSL\Keychain;

$token = // ... instance of Zenstruck\JWT\Token
$signer = // an instance of one of the classes in the table above
$privateKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PrivateKey
$publicKey = // can be string, resource, filename, instance of Zenstruck\JWT\Signer\OpenSSL\PublicKey

$keychain = new Keychain($publicKey, $privateKey, 'my passphrase');

$token->sign($signer, $keychain);
$token->verify($signer, $keychain); // verified
```

Validation
----------

[](#validation)

ValidatorDescription`Zenstruck\JWT\Validator\IssuerValidator`Ensures `iss` claim exists and matches expected value`Zenstruck\JWT\Validator\SubjectValidator`Ensures `sub` claim exists and matches expected value`Zenstruck\JWT\Validator\AudienceValidator`Ensures `aud` claim exists and matches expected value`Zenstruck\JWT\Validator\ExpiresAtValidator`Ensures `exp` claim exists is not greater than expected time`Zenstruck\JWT\Validator\NotBeforeValidator`Ensures `nbf` claim exists is not less than expected time`Zenstruck\JWT\Validator\IssuedAtValidator`Ensures `iat` claim exists and matches expected value`Zenstruck\JWT\Validator\IdAtValidator`Ensures `jti` claim exists and matches expected value`Zenstruck\JWT\Validator\ChainValidator`Combines any of the above validators together### Usage

[](#usage-2)

```
use Zenstruck\JWT\Validator\IssuerValidator;
use Zenstruck\JWT\Validator\AudienceValidator;
use Zenstruck\JWT\Validator\ChainValidator;

$token = // ... instance of Zenstruck\JWT\Token
$validator = new ChainValidator([new IssuerValidator(), new AudienceValidator()]);

try {
    $token->validate($validator);
} catch (ValidationFailed $e) {
    $reason = $e->getMessage();
}
```

ValidatorBuilder
----------------

[](#validatorbuilder)

```
$validator = (new ValidatorBuilder())
    ->issuer('kevin')
    ->subject('zenstruck\jwt')
    ->audience('php community')
    ->expiresAt()
    ->notBefore()
    ->issuedAt(time())
    ->id('foo')
    ->create(); // instance of Zenstruck\JWT\Validator\ChainValidator
```

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity32

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

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

Unknown

Total

1

Last Release

3813d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/707369cc916e0ea1aacbf077dcba464f611cef879f024d8944311a54a15224b3?d=identicon)[kbond](/maintainers/kbond)

---

Top Contributors

[![odino](https://avatars.githubusercontent.com/u/328420?v=4)](https://github.com/odino "odino (48 commits)")[![cirpo](https://avatars.githubusercontent.com/u/51252?v=4)](https://github.com/cirpo "cirpo (16 commits)")[![kbond](https://avatars.githubusercontent.com/u/127811?v=4)](https://github.com/kbond "kbond (13 commits)")[![brianjmiller](https://avatars.githubusercontent.com/u/95960?v=4)](https://github.com/brianjmiller "brianjmiller (5 commits)")[![nikita2206](https://avatars.githubusercontent.com/u/1030688?v=4)](https://github.com/nikita2206 "nikita2206 (5 commits)")[![eroux](https://avatars.githubusercontent.com/u/60868?v=4)](https://github.com/eroux "eroux (4 commits)")[![nsfinkelstein](https://avatars.githubusercontent.com/u/2919482?v=4)](https://github.com/nsfinkelstein "nsfinkelstein (4 commits)")[![AyhamAlzoubi](https://avatars.githubusercontent.com/u/1628272?v=4)](https://github.com/AyhamAlzoubi "AyhamAlzoubi (2 commits)")[![dol](https://avatars.githubusercontent.com/u/41777?v=4)](https://github.com/dol "dol (2 commits)")[![mikesir87](https://avatars.githubusercontent.com/u/746837?v=4)](https://github.com/mikesir87 "mikesir87 (2 commits)")[![tymondesigns](https://avatars.githubusercontent.com/u/1801923?v=4)](https://github.com/tymondesigns "tymondesigns (2 commits)")[![kidtronnix](https://avatars.githubusercontent.com/u/4520386?v=4)](https://github.com/kidtronnix "kidtronnix (1 commits)")[![greg0ire](https://avatars.githubusercontent.com/u/657779?v=4)](https://github.com/greg0ire "greg0ire (1 commits)")[![thijsvdanker](https://avatars.githubusercontent.com/u/429548?v=4)](https://github.com/thijsvdanker "thijsvdanker (1 commits)")[![mfn](https://avatars.githubusercontent.com/u/87493?v=4)](https://github.com/mfn "mfn (1 commits)")

---

Tags

jwtjsonJWStokenJSON Web TokenJSON Web Signature

### Embed Badge

![Health badge](/badges/zenstruck-jwt/health.svg)

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

###  Alternatives

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[sop/jwx

A PHP library for JSON web tokens (JWT) with signature (JWS) and encryption (JWE) support.

26257.5k1](/packages/sop-jwx)[adhocore/jwt

Ultra lightweight JSON web token (JWT) library for PHP5.5+.

3031.6M15](/packages/adhocore-jwt)[gamegos/jws

Json Web Signature (JWS) PHP implementation

26359.6k6](/packages/gamegos-jws)[psecio/jwt

A JWT (JSON Web Token) Encoding &amp; Decoding library

109352.2k2](/packages/psecio-jwt)[bizley/jwt

JWT integration for Yii 2

67425.3k2](/packages/bizley-jwt)

PHPackages © 2026

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