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

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

lake/larke-jwt
==============

A library to work with JSON Web Token and JSON Web Signature.

v1.3.1(1y ago)05.3k3BSD-3-ClausePHPPHP ~8.1|~8.2|~8.3

Since Dec 1Pushed 1y agoCompare

[ Source](https://github.com/deatil/larke-jwt)[ Packagist](https://packagist.org/packages/lake/larke-jwt)[ Docs](https://github.com/deatil/larke-jwt)[ RSS](/packages/lake-larke-jwt/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (10)DependenciesVersions (19)Used By (3)

JWT
===

[](#jwt)

A simple library to work with JSON Web Token and JSON Web Signature (requires PHP 5.6+). The implementation is based on the [RFC 7519](https://tools.ietf.org/html/rfc7519).

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

[](#installation)

you can install it using [Composer](http://getcomposer.org).

```
composer require lake/larke-jwt
```

### Dependencies

[](#dependencies)

- PHP &gt;= 8.1.0
- OpenSSL Extension
- sodium Extension

Basic usage
-----------

[](#basic-usage)

### Creating

[](#creating)

Just use the builder to create a new JWT/JWS tokens:

```
use DateTimeImmutable;
use Larke\JWT\Builder;
use Larke\JWT\Signer\None;
use Larke\JWT\Signer\Key\InMemory;

$now    = new DateTimeImmutable();
$signer = new None();
$key    = InMemory::plainText('testing')

$token = (new Builder())
    ->issuedBy('http://example.com') // Configures the issuer (iss claim)
    ->permittedFor('http://example.org') // Configures the audience (aud claim)
    ->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
    ->issuedAt($now) // Configures the time that the token was issue (iat claim)
    ->canOnlyBeUsedAfter($now->modify('+1 minute')) // Configures the time that the token can be used (nbf claim)
    ->expiresAt($now->modify('+1 hour')) // Configures the expiration time of the token (exp claim)
    ->withClaim('uid', 1) // Configures a new claim, called "uid"
    ->getToken($signer, $key); // Retrieves the generated token

$token->headers()->all(); // Retrieves the token headers
$token->claims()->all(); // Retrieves the token claims

echo $token->headers()->get('jti'); // will print "4f1g23a12aa"
echo $token->claims()->get('iss'); // will print "http://example.com"
echo $token->claims()->get('uid'); // will print "1"
echo $token->toString(); // The string representation of the object is a JWT string (pretty easy, right?)
```

### Parsing from strings

[](#parsing-from-strings)

Use the parser to create a new token from a JWT string (using the previous token as example):

```
use Larke\JWT\Parser;

$token = (new Parser())->parse((string) $token); // Parses from a string
$token->headers()->all(); // Retrieves the token headers
$token->claims()->all(); // Retrieves the token claims

echo $token->headers()->get('jti'); // will print "4f1g23a12aa"
echo $token->claims()->get('iss'); // will print "http://example.com"
echo $token->claims()->get('uid'); // will print "1"
```

### Validating

[](#validating)

We can easily validate if the token is valid (using the previous token and time as example):

```
use DateTimeImmutable;
use Larke\JWT\Validator;
use Larke\JWT\ValidationData;

$now = new DateTimeImmutable();

$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->issuedBy('http://example.com');
$data->permittedFor('http://example.org');
$data->identifiedBy('4f1g23a12aa');

$validation = new Validator();

var_dump($validation->validate($token, $data)); // false, because token cannot be used before now() + 60

$data->currentTime($now->modify('+61 seconds')); // changing the validation time to future

var_dump($validation->validate($token, $data)); // true, because current time is between "nbf" and "exp" claims

$data->currentTime($now->modify('+4000 seconds')); // changing the validation time to future

var_dump($validation->validate($token, $data)); // false, because token is expired since current time is greater than exp

// We can also use the $leeway parameter to deal with clock skew (see notes below)
// If token's claimed now is invalid but the difference between that and the validation time is less than $leeway,
// then token is still considered valid
$dataWithLeeway = new ValidationData($now, 20);
$dataWithLeeway->issuedBy('http://example.com');
$dataWithLeeway->permittedFor('http://example.org');
$dataWithLeeway->identifiedBy('4f1g23a12aa');

var_dump($validation->validate($token, $dataWithLeeway)); // false, because token can't be used before now() + 60, not within leeway

$dataWithLeeway->currentTime($now->modify('+51 seconds')); // changing the validation time to future

var_dump($validation->validate($token, $dataWithLeeway)); // true, because current time plus leeway is between "nbf" and "exp" claims

$dataWithLeeway->currentTime($now->modify('+3610 seconds')); // changing the validation time to future but within leeway

var_dump($validation->validate($token, $dataWithLeeway)); // true, because current time - 20 seconds leeway is less than exp

$dataWithLeeway->currentTime($now->modify('+4000 seconds')); // changing the validation time to future outside of leeway

var_dump($validation->validate($token, $dataWithLeeway)); // false, because token is expired since current time is greater than exp
```

#### Important

[](#important)

- You have to configure `ValidationData` informing all claims you want to validate the token.
- If `ValidationData` contains claims that are not being used in token or token has claims that are not configured in `ValidationData` they will be ignored by `Token::validate()`.
- `exp`, `nbf` and `iat` claims are configured by default in `ValidationData::__construct()`with the current time (`DateTimeImmutable`).
- The optional `$leeway` parameter of `ValidationData` will cause us to use that number of seconds of leeway when validating the time-based claims, pretending we are further in the future for the "Issued At" (`iat`) and "Not Before" (`nbf`) claims and pretending we are further in the past for the "Expiration Time" (`exp`) claim. This allows for situations where the clock of the issuing server has a different time than the clock of the verifying server, as mentioned in [section 4.1 of RFC 7519](https://tools.ietf.org/html/rfc7519#section-4.1).

Token signature
---------------

[](#token-signature)

We can use signatures to be able to verify if the token was not modified after its generation. This library implements `Hmac`, `RSA`, `ECDSA`, `EdDSA` and `Blake2b` signatures (using 256, 384 and 512). The `none` is not signatures.

### Important

[](#important-1)

Do not allow the string sent to the Parser to dictate which signature algorithm to use, or else your application will be vulnerable to a [critical JWT security vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries).

The examples below are safe because the choice in `Signer` is hard-coded and cannot be influenced by malicious users.

### Hmac and Blake2b

[](#hmac-and-blake2b)

Hmac signatures are really simple to be used:

```
use DateTimeImmutable;
use Larke\JWT\Builder;
use Larke\JWT\Validator;
use Larke\JWT\Signer\Hmac\Sha256;
use Larke\JWT\Signer\Key\InMemory;

$now    = new DateTimeImmutable();
$signer = new Sha256();
$key    = InMemory::plainText('testing');

$token = (new Builder())
    ->issuedBy('http://example.com') // Configures the issuer (iss claim)
    ->permittedFor('http://example.org') // Configures the audience (aud claim)
    ->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
    ->issuedAt($now) // Configures the time that the token was issue (iat claim)
    ->canOnlyBeUsedAfter($now->modify('+1 minute')) // Configures the time that the token can be used (nbf claim)
    ->expiresAt($now->modify('+1 hour')) // Configures the expiration time of the token (exp claim)
    ->withClaim('uid', 1) // Configures a new claim, called "uid"
    ->getToken($signer, $key); // Retrieves the generated token

$key1 = InMemory::plainText('testing 1');
$key2 = InMemory::plainText('testing');

$validation = new Validator();

var_dump($validation->verify($token, $signer, $key1)); // false, because the key is different
var_dump($validation->verify($token, $signer, $key2)); // true, because the key is the same
```

### RSA, ECDSA and EdDSA

[](#rsa-ecdsa-and-eddsa)

RSA, ECDSA and EdDSA signatures are based on public and private keys so you have to generate using the private key and verify using the public key:

```
use DateTimeImmutable;
use Larke\JWT\Builder;
use Larke\JWT\Validator;
use Larke\JWT\Signer\Key\LocalFileReference;
use Larke\JWT\Signer\Rsa\Sha256; // you can use Larke\JWT\Signer\Ecdsa\Sha256 if you're using ECDSA keys

$now        = new DateTimeImmutable();
$signer     = new Sha256();
$privateKey = LocalFileReference::file('file://{path to your private key}');

$token = (new Builder())
    ->issuedBy('http://example.com') // Configures the issuer (iss claim)
    ->permittedFor('http://example.org') // Configures the audience (aud claim)
    ->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
    ->issuedAt($now) // Configures the time that the token was issue (iat claim)
    ->canOnlyBeUsedAfter($now->modify('+1 minute')) // Configures the time that the token can be used (nbf claim)
    ->expiresAt($now->modify('+1 hour')) // Configures the expiration time of the token (exp claim)
    ->withClaim('uid', 1) // Configures a new claim, called "uid"
    ->getToken($signer, $privateKey); // Retrieves the generated token

$publicKey = LocalFileReference::file('file://{path to your public key}');

$validation = new Validator();

var_dump($validation->verify($token, $signer, $publicKey)); // true when the public key was generated by the private one =)
```

**It's important to say that if you're using RSA keys you shouldn't invoke ECDSA signers (and vice-versa), otherwise `sign()` and `verify()` will raise an exception!**

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance43

Moderate activity, may be stable

Popularity22

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~91 days

Recently: every ~180 days

Total

18

Last Release

447d ago

PHP version history (5 changes)1.0.0PHP ^5.6 || ^7.0

1.1.0PHP ^5.6|^7.0|^8.0

1.1.9PHP ~8.1.0 || ~8.2.0

1.3.0PHP ~8.1 || ~8.2 || ~8.3

v1.3.1PHP ~8.1|~8.2|~8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/6d9102ba7087cc40ae6c6bedcc0c84cd8cb12870a983d0bc147785833d009e3c?d=identicon)[deatil](/maintainers/deatil)

---

Top Contributors

[![deatil](https://avatars.githubusercontent.com/u/24578855?v=4)](https://github.com/deatil "deatil (45 commits)")

---

Tags

ecdsaeddsahmacjson-web-signaturejwsjwtjwt-tokenphprsajwtJWSlakelarkelarke-jwt

### Embed Badge

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

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

###  Alternatives

[lcobucci/jwt

A simple library to work with JSON Web Token and JSON Web Signature

7.5k316.6M895](/packages/lcobucci-jwt)[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[web-token/jwt-framework

JSON Object Signing and Encryption library for PHP and Symfony Bundle.

94518.9M77](/packages/web-token-jwt-framework)[web-token/jwt-library

JWT library

2011.2M83](/packages/web-token-jwt-library)[bizley/jwt

JWT integration for Yii 2

67425.3k2](/packages/bizley-jwt)[web-token/jwt-bundle

JWT Bundle of the JWT Framework.

132.5M7](/packages/web-token-jwt-bundle)

PHPackages © 2026

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