1. Go to this page and download the library: Download kylesean/hyperf-jwt library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kylesean / hyperf-jwt example snippets
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'
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
}
// Add the given token to the blacklist immediately
$manager->invalidate($token);
'blacklist_concurrency_grace_period' => 30, // 30 seconds grace period
use Kylesean\Jwt\Middleware\JwtAuthMiddleware;
use Hyperf\HttpServer\Router\Router;
Router::addGroup('/api', function () {
Router::get('/user/profile', [UserController::class, 'profile']);
}, ['middleware' => [JwtAuthMiddleware::class]]);
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
];
}
}