methorz/jwt-auth-middleware 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

methorz/jwt-auth-middleware

Composer 安装命令:

composer require methorz/jwt-auth-middleware

包简介

PSR-15 JWT authentication middleware with zero-config approach. Supports HS256/RS256, Bearer/custom headers, optional user loading, and scope validation.

README 文档

README

CI codecov PHPStan PHP Version License

PSR-15 JWT authentication middleware with zero-config approach. Just add your JWT secret and you're ready to go!

Features

  • Zero Configuration - Works out of the box with environment variables
  • PSR-15 Compliant - Standard middleware interface
  • Framework Agnostic - Works with any PSR-15 compatible framework
  • Flexible Token Extraction - Bearer token (default) or custom header
  • Multiple Algorithms - Supports HS256 (symmetric) and RS256 (asymmetric)
  • Standard Claims Validation - Validates exp, nbf, iss, aud automatically
  • Optional User Loading - Inject your own user loader
  • Optional Scope Validation - Route-level permission checks
  • Route-Specific Protection - Opt-in authentication per route

Installation

composer require methorz/jwt-auth-middleware

Quick Start

1. Set Environment Variable

# For symmetric key (HS256)
JWT_SECRET=your-secret-key-here

# Or for asymmetric (RS256)
JWT_PUBLIC_KEY_PATH=/path/to/public.pem
JWT_ALGORITHM=RS256

2. Add to Your Pipeline

Mezzio:

// config/pipeline.php
$app->pipe(\MethorZ\JwtAuthMiddleware\Middleware\JwtAuthenticationMiddleware::class);

Slim:

$app->add(\MethorZ\JwtAuthMiddleware\Middleware\JwtAuthenticationMiddleware::class);

3. Protect Routes

Mezzio:

$app->get('/api/protected', ProtectedHandler::class, 'protected-route')
    ->setOptions(['auth' => ['required' => true]]);

In Your Handler:

public function handle(ServerRequestInterface $request): ResponseInterface
{
    // Get JWT claims from request
    $claims = $request->getAttribute('jwt_claims');
    $userId = $claims->get('sub'); // User ID from token

    // Optional: Get loaded user (if user loader configured)
    $user = $request->getAttribute('user');

    return new JsonResponse(['user_id' => $userId]);
}

That's it! 🎉

Configuration

Environment Variables (Zero-Config)

Variable Default Description
JWT_SECRET - Secret key for HS256 (required if using symmetric)
JWT_PUBLIC_KEY_PATH - Path to public key for RS256 (required if using asymmetric)
JWT_ALGORITHM HS256 Algorithm: HS256 or RS256
JWT_ISSUER - Expected iss claim (optional)
JWT_AUDIENCE - Expected aud claim (optional)
JWT_HEADER_NAME Authorization Header to extract token from
JWT_HEADER_PREFIX Bearer Token prefix (e.g., "Bearer ")

Advanced Configuration (Optional)

If you need more control, create a configuration file:

// config/autoload/jwt-auth.php
return [
    'jwt_auth' => [
        'algorithm' => 'HS256',
        'secret' => $_ENV['JWT_SECRET'],

        // Validation constraints
        'issuer' => 'your-app',
        'audience' => 'your-api',

        // Token extraction
        'header_name' => 'Authorization',
        'header_prefix' => 'Bearer',

        // Optional: Custom header
        // 'header_name' => 'X-Auth-Token',
        // 'header_prefix' => '',

        // Optional: User loader service
        // 'user_loader' => UserLoaderInterface::class,
    ],
];

Usage Examples

Protect Specific Routes

// Only require JWT for specific routes
$app->get('/public', PublicHandler::class); // No auth

$app->get('/protected', ProtectedHandler::class)
    ->setOptions(['auth' => ['required' => true]]); // Requires JWT

Scope/Permission Validation

// Require specific scopes
$app->post('/admin/users', AdminHandler::class)
    ->setOptions([
        'auth' => [
            'required' => true,
            'scopes' => ['admin', 'users:write'],
        ],
    ]);

In your token, include a scope claim:

{
  "sub": "user123",
  "scope": "admin users:write users:read"
}

Custom User Loading

Implement UserLoaderInterface to load user from database:

use MethorZ\JwtAuthMiddleware\Contract\UserLoaderInterface;
use Lcobucci\JWT\Token\Plain;

class DatabaseUserLoader implements UserLoaderInterface
{
    public function __construct(private UserRepository $repository) {}

    public function loadUser(Plain $token): ?object
    {
        $userId = $token->claims()->get('sub');
        return $this->repository->findById($userId);
    }
}

Register in container:

// ConfigProvider.php
use MethorZ\JwtAuthMiddleware\Contract\UserLoaderInterface;

return [
    'dependencies' => [
        'factories' => [
            UserLoaderInterface::class => DatabaseUserLoaderFactory::class,
        ],
    ],
];

Now $request->getAttribute('user') contains your user object!

Generate Tokens (Separate from Middleware)

use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;

$config = Configuration::forSymmetricSigner(
    new Sha256(),
    InMemory::plainText($_ENV['JWT_SECRET'])
);

$now = new DateTimeImmutable();
$token = $config->builder()
    ->issuedBy('your-app')
    ->permittedFor('your-api')
    ->identifiedBy('unique-token-id')
    ->issuedAt($now)
    ->expiresAt($now->modify('+1 hour'))
    ->withClaim('sub', 'user123')
    ->withClaim('scope', 'users:read users:write')
    ->getToken($config->signer(), $config->signingKey());

echo $token->toString(); // Send to client

Request Attributes

After successful authentication, these attributes are added to the request:

Attribute Type Description
jwt_token Lcobucci\JWT\Token\Plain Full parsed token
jwt_claims Lcobucci\JWT\Token\DataSet Token claims
user `object null`

Exceptions

All exceptions extend MethorZ\JwtAuthMiddleware\Exception\JwtAuthenticationException:

Exception When Thrown
MissingTokenException No token in request
InvalidTokenException Token is malformed
ExpiredTokenException Token has expired
InvalidSignatureException Signature verification failed
InsufficientScopeException Required scope missing

Recommendation: Use with methorz/http-problem-details to automatically format exceptions as RFC 7807 Problem Details responses.

Testing

composer test          # Run tests
composer cs-check      # Check code style
composer cs-fix        # Fix code style
composer analyze       # Static analysis
composer check         # All checks

Requirements

  • PHP 8.2 or higher
  • PSR-15 compatible framework
  • lcobucci/jwt ^5.4

License

MIT License. See LICENSE for details.

Contributing

Contributions welcome! Please ensure:

  • All tests pass
  • Code follows PSR-12
  • PHPStan level 9 passes
  • Zero-config principle maintained

methorz/jwt-auth-middleware 适用场景与选型建议

methorz/jwt-auth-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 48 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 12 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 methorz/jwt-auth-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 methorz/jwt-auth-middleware 我们能提供哪些服务?
定制开发 / 二次开发

基于 methorz/jwt-auth-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 48
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 31
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-10