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

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

kylesean/hyperf-jwt
===================

A JWT (JSON Web Token) package for Hyperf framework.

v1.3.1(1mo ago)011MITPHPPHP ^8.2CI failing

Since May 25Pushed 3w agoCompare

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

READMEChangelogDependencies (34)Versions (6)Used By (0)

Hyperf JWT Package
==================

[](#hyperf-jwt-package)

English | [中文文档](README.zh-CN.md)

A high-performance, lightweight JWT (JSON Web Token) package designed for [Hyperf](https://github.com/hyperf/hyperf) coroutine framework, powered by [lcobucci/jwt](https://github.com/lcobucci/jwt) v5.

---

Features
--------

[](#features)

- **Coroutine Friendly**: Native integration with Hyperf DI container and Swoole/Swow coroutine concurrency environments.
- **Multiple Algorithms**: Full support for HMAC (HS256, HS384, HS512), RSA (RS256, etc.), and ECDSA (ES256, etc.) signing algorithms.
- **Blacklist &amp; Concurrency Grace Period**: Redis/Cache-backed token blacklisting with an innovative **Concurrency Grace Period** mechanism for coroutine applications.
- **Flexible Request Parsing**: Extract tokens from Authorization Header (Bearer), URL Query Parameters, POST Body, or Cookies in customizable order.
- **Seamless Authentication Middleware**: Out-of-the-box `JwtAuthMiddleware` with coroutine context isolation and convenient static helpers.

---

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

[](#installation)

Install via Composer:

```
composer require kylesean/hyperf-jwt
```

Publish the configuration file:

```
php bin/hyperf.php vendor:publish kylesean/hyperf-jwt
```

Generate a secure secret key:

```
php bin/hyperf.php jwt:gen-key --algo=hs256 --update-env
```

---

Quick Start
-----------

[](#quick-start)

### 1. Token Issuance &amp; Parsing

[](#1-token-issuance--parsing)

```
use Kylesean\Jwt\Contract\ManagerInterface;
use Hyperf\Context\ApplicationContext;

$manager = ApplicationContext::getContainer()->get(ManagerInterface::class);

// 1. Issue a Token with custom claims and subject
$token = $manager->issueToken([
    'user_id' => 123,
    'role' => 'admin'
], 'user_123');

$tokenString = $token->toString();

// 2. Parse and validate a Token string
$parsedToken = $manager->parse($tokenString);
$userId = $parsedToken->getClaim('user_id'); // 123
$subject = $parsedToken->getSubject();       // 'user_123'
```

---

### 2. Token Refreshing

[](#2-token-refreshing)

The `ManagerInterface::refreshToken()` method allows clients to swap an expiring token for a fresh token within the configured refresh window (`refresh_ttl`), automatically blacklisting the old token.

```
use Kylesean\Jwt\Exception\TokenExpiredException;
use Kylesean\Jwt\Exception\TokenInvalidException;

try {
    // Refresh the old token and get a new Token instance
    // Param 1: Old token string
    // Param 2: forceForever (Whether to permanently blacklist the old token)
    // Param 3: resetClaims (Whether to reset custom claims on the new token, default false)
    $newToken = $manager->refreshToken($oldTokenString);

    echo $newToken->toString();
} catch (TokenExpiredException $e) {
    // Old token has exceeded the refresh TTL window
} catch (TokenInvalidException $e) {
    // Old token is invalid, tampered with, or already blacklisted
}
```

---

### 3. Token Invalidation &amp; Blacklist Grace Period

[](#3-token-invalidation--blacklist-grace-period)

#### Manual Invalidation (Logout)

[](#manual-invalidation-logout)

```
// Add the given token to the blacklist immediately
$manager->invalidate($token);
```

The blacklist entry for an invalidated token is kept until the token's natural expiry **plus** the full `refresh_ttl` window, so a logged-out token can never be "revived" by refreshing it later. Pass `true` as the second argument to keep the entry for one year ("forever") instead: `$manager->invalidate($token, true)`.

#### Coroutine Concurrency Grace Period

[](#coroutine-concurrency-grace-period)

In high-concurrency coroutine environments (e.g. 5 parallel HTTP requests sent by a Single Page App simultaneously), if one request refreshes the token and invalidates the old one immediately, the remaining 4 concurrent requests carrying the old token might trigger 401 Unauthorized errors.

Configure the concurrency grace period in `config/autoload/jwt.php`:

```
'blacklist_concurrency_grace_period' => 30, // 30 seconds grace period
```

During this 30-second window, the replaced old token remains accepted as valid, preventing race-condition failures.

> **Concurrency semantics:** the grace period guarantees that concurrent requests *validating* the old token do not fail. Blacklisting itself is a non-atomic check-then-set against the cache, so two refresh calls arriving at the exact same instant may both succeed and each receive a new token (the old token still ends up blacklisted). If your business logic requires strictly single-use refresh, add a distributed lock around `refreshToken()`.

---

### 4. Authentication Middleware

[](#4-authentication-middleware)

Register `JwtAuthMiddleware` in your routes or controller annotations:

```
use Kylesean\Jwt\Middleware\JwtAuthMiddleware;
use Hyperf\HttpServer\Router\Router;

Router::addGroup('/api', function () {
    Router::get('/user/profile', [UserController::class, 'profile']);
}, ['middleware' => [JwtAuthMiddleware::class]]);
```

Access authenticated identity inside controllers:

```
use Kylesean\Jwt\Middleware\JwtAuthMiddleware;

class UserController
{
    public function profile()
    {
        // Retrieve current authenticated Token / Subject from Coroutine Context
        $subject = JwtAuthMiddleware::getSubject();
        $role = JwtAuthMiddleware::getClaim('role');

        return [
            'user' => $subject,
            'role' => $role
        ];
    }
}
```

---

License
-------

[](#license)

[MIT license](LICENSE)

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance94

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.4% 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 ~104 days

Total

5

Last Release

31d ago

PHP version history (2 changes)v1.0.0PHP &gt;=8.1

v1.3.0PHP ^8.2

### Community

Maintainers

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

---

Top Contributors

[![kylesean](https://avatars.githubusercontent.com/u/19353263?v=4)](https://github.com/kylesean "kylesean (17 commits)")[![jkxsai666](https://avatars.githubusercontent.com/u/247395285?v=4)](https://github.com/jkxsai666 "jkxsai666 (1 commits)")

---

Tags

phpjwtJSON Web Tokenhyperf

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

86337.5k](/packages/flow-php-flow)[flow-php/etl

PHP ETL - Extract Transform Load - Abstraction

378637.6k126](/packages/flow-php-etl)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.8M674](/packages/shopware-core)[hyperf/database

A flexible database library.

193.0M353](/packages/hyperf-database)[simplesamlphp/simplesamlphp-module-oidc

A SimpleSAMLphp module adding support for the OpenID Connect protocol

5018.6k1](/packages/simplesamlphp-simplesamlphp-module-oidc)

PHPackages © 2026

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