zotenme / hyperf-jwt-auth
JWT Authentication package for Hyperf framework
Requires
- php: >=8.3
- hyperf/cache: ^3.2
- lcobucci/jwt: ^5.5
- ramsey/uuid: ^4.9
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.85.1
- mockery/mockery: ^1.6.12
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^12.5.8
- symfony/process: ^5.4.51 || ^6.4.33 || ^7.3.11
Suggests
- hyperf/redis: Required for atomic refresh-token rotation with the built-in storage.
README
JWT authentication for Hyperf 3.2+ with refresh-token rotation, revocation, single-session mode and symmetric or asymmetric signing.
Features
- 🔐 Multiple Algorithm Support - HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512
- 🔄 Atomic Token Rotation - A Redis-backed refresh token can be consumed only once
- 🚫 Token Blacklisting - Revoke tokens before expiration with grace period support
- 👤 Single Session (SSO) - A new login invalidates the subject's previous tokens
- ⚡ Hyperf 3.2 Cache Integration - Uses the configured default or named cache store
- 🛡️ Type Safe - Full PHP 8.3+ type declarations with PHPStan level 8
Quick Start
Installation
composer require zotenme/hyperf-jwt-auth
composer require hyperf/redis:^3.2 # required by refresh rotation
php bin/hyperf.php vendor:publish zotenme/hyperf-jwt-auth
Basic Usage
<?php use Zotenme\JwtAuth\Contract\JwtManagerInterface; class AuthController { public function __construct( private JwtManagerInterface $jwtManager ) {} public function login(LoginRequest $request): JsonResponse { $userId = $this->validateCredentials($request); $tokenPair = $this->jwtManager->generateTokenPair( subjectId: $userId, payload: ['role' => 'user', 'permissions' => ['read', 'write']] ); return new JsonResponse([ 'access_token' => $tokenPair->accessToken, 'refresh_token' => $tokenPair->refreshToken, 'expires_in' => $tokenPair->accessExpiresIn, ]); } public function refresh(RefreshRequest $request): JsonResponse { $refreshToken = $request->input('refresh_token'); $tokenPair = $this->jwtManager->refreshAccessToken($refreshToken); return new JsonResponse([ 'access_token' => $tokenPair->accessToken, 'refresh_token' => $tokenPair->refreshToken, 'expires_in' => $tokenPair->accessExpiresIn, ]); } }
Configuration
Edit config/autoload/jwt.php:
<?php return [ 'algorithm' => 'HS256', 'keys' => [ 'secret_key' => env('JWT_SECRET'), ], 'access_token' => [ 'ttl' => 900, // default: 15 minutes 'max_ttl' => 86400, // maximum dynamic value: 1 day ], 'refresh_token' => [ 'ttl' => 604800, // default: 7 days 'max_ttl' => 2592000, // maximum dynamic value: 30 days 'rotation_enabled' => true, ], 'cache' => [ 'store' => null, // Hyperf's default cache store 'prefix' => 'jwt_auth:', ], 'blacklist' => ['enabled' => true], 'sso_mode' => false, 'issuer' => 'my-api', 'audience' => ['my-web-app'], ];
Refresh rotation is enabled by default and requires a Redis-backed Hyperf cache
store because token consumption must be atomic. Set rotation_enabled to
false only if the selected store cannot provide Redis SET NX EX.
Dynamic Expiration
Use TokenOptions to override token lifetimes for one issued session without
mutating shared Hyperf configuration:
use Zotenme\JwtAuth\DTO\TokenOptions; $tokenPair = $jwtManager->generateTokenPair( subjectId: (string) $user->id, payload: ['role' => $user->role], options: new TokenOptions( accessTtl: 3600, // 1 hour refreshTtl: 2592000, // 30 days sessionTtl: 2592000, // absolute session limit ), );
Overrides cannot exceed the configured max_ttl. The policy and absolute
session deadline are signed into the refresh token and preserved during
rotation.
Documentation
- 📖 Installation & Configuration - Complete setup guide
- 🚀 Usage Examples - Practical examples and patterns
- 🔧 API Reference - Complete API documentation
- 🛡️ Security Guide - Best practices and security considerations
- 🍪 Secure Cookie Authentication - HttpOnly cookies, refresh and CSRF protection
- 🏗️ Advanced Features - Token rotation, SSO, RSA/ECDSA algorithms
- 🔌 Middleware Integration - HTTP middleware setup
- ⚠️ Error Handling - Exception handling guide
- ⬆️ Upgrade Guide - Migrating from 1.x to 2.0
- 📝 Changelog - Release history and notable changes
Requirements
- PHP 8.3 or higher
- Hyperf 3.2 or higher
- ext-json
Upgrading
Version 2.0 is a major update. Applications upgrading from 1.x must review configuration, Redis requirements, token cutover and custom storage changes. Follow the complete upgrade guide before deployment.
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Please ensure your code follows PSR-12 coding standards and includes tests.
Testing
# Run all tests composer test # Static analysis composer analyse # Code style fixer composer cs-fix
License
This package is open-sourced software licensed under the MIT license.
Support
If you discover any security vulnerabilities or have questions, please email zotenme@gmail.com.