A simple and efficient JWT (JSON Web Token) microservice built for ReactPHP register-center. This package provides JWT generation and verification services through microservice architecture.
composer require reactphp-x/jwt
- JWT token generation with customizable claims
- JWT token verification
- Microservice architecture with register-center integration
- Built with firebase/php-jwt for reliable JWT operations
- Comprehensive test coverage
<?php
require 'vendor/autoload.php';
use ReactphpX\RegisterCenter\ServiceRegistry;
use ReactphpX\Jwt\JwtService;
// Create JWT service instance
$jwtService = new JwtService('your-secret-key-here');
// Register JWT service
ServiceRegistry::register('jwt', $jwtService);
From another service, you can use the JWT service like this:
// Generate a token
$result = $client->call('jwt', 'generate', [[
'user_id' => 123,
'username' => 'john_doe'
]]);
// Success response:
// [
// 'code' => 0,
// 'msg' => 'success',
// 'data' => [
// 'token' => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...',
// 'expires_at' => 1234571490
// ]
// ]
// Verify a token
$result = $client->call('jwt', 'verify', ['your-token-here']);
// Success response:
// [
// 'code' => 0,
// 'msg' => 'success',
// 'data' => [
// 'user_id' => 123,
// 'username' => 'john_doe',
// 'iat' => 1234567890,
// 'exp' => 1234571490
// ]
// ]
// Error response example:
// [
// 'code' => 1,
// 'msg' => 'Token verification failed: Expired token',
// 'data' => null
// ]
All methods return a consistent response format:
-
Success response:
[ 'code' => 0, 'msg' => 'success', 'data' => [...] // Response data ]
-
Error response:
[ 'code' => 1, 'msg' => 'Error message', 'data' => null ]
The JwtService
constructor accepts the following parameters:
key
(string): The secret key used for signing tokensalgorithm
(string, optional): The algorithm to use for signing (default: 'HS256')expirationTime
(int, optional): Token expiration time in seconds (default: 3600)
composer install
./vendor/bin/phpunit
The test suite includes:
- Token generation tests
- Token verification tests
- Invalid token handling
- Expired token handling
- Custom algorithm tests
-
Required:
- firebase/php-jwt: ^6.11
-
Development:
- phpunit/phpunit: ^10.0
- reactphp-x/register-center: ^1.0
- monolog/monolog: ^3.9
MIT License