zotenme/hyperf-jwt-auth

JWT Authentication package for Hyperf framework

Maintainers

Package info

github.com/Zotenme/hyperf-jwt-auth

pkg:composer/zotenme/hyperf-jwt-auth

Transparency log

Statistics

Installs: 977

Dependents: 0

Suggesters: 0

Stars: 2

Open Issues: 0

v2.0.0 2026-07-28 16:19 UTC

This package is auto-updated.

Last update: 2026-07-28 16:34:39 UTC


README

PHP Version Hyperf Version License CI

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

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

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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.