PHP code example of kylesean / hyperf-jwt
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
$customClaims = [
'user_id' => 123,
'username' => 'test_user',
// 其他自定义数据...
];
$subject = 123;
$tokenObject = $this->jwtManager->issueToken($customClaims, $subject);
$tokenString = $tokenObject->toString();
use FriendsOfHyperf\Jwt\Contract\ManagerInterface;
use FriendsOfHyperf\Jwt\Exception\TokenExpiredException;
use FriendsOfHyperf\Jwt\Exception\TokenInvalidException;
use FriendsOfHyperf\Jwt\Exception\TokenNotYetValidException;
use FriendsOfHyperf\Jwt\Exception\JwtException;
use Psr\Http\Message\ServerRequestInterface;
// ...
try {
$tokenObject = $this->jwtManager->parseTokenFromRequest($request);
// $tokenObject = $this->jwtManager->parse($tokenString);
if ($tokenObject) {
$userId = $tokenObject->getClaim('user_id');
$jti = $tokenObject->getId(); // 获取 jti
} else {
// Token 未找到或无效
}
} catch (TokenExpiredException $e) {
// Token 已过期
} catch (TokenInvalidException $e) {
// Token 无效 (例如,签名错误、声明缺失、已在黑名单)
} catch (TokenNotYetValidException $e) {
// Token 尚未生效
} catch (JwtException $e) {
// 其他 JWT 相关错误
}
// $oldTokenString 是客户端传递过来的旧 Token 字符串
try {
$newTokenObject = $this->jwtManager->refreshToken($oldTokenString);
$newTokenString = $newTokenObject->toString();
// 将新的 Token 返回给客户端,客户端需要替换旧的 Token
} catch (TokenExpiredException $e) {
// 旧 Token 已彻底过期,无法刷新
} catch (TokenInvalidException $e) {
// 旧 Token 无效 (例如已在黑名单)
} catch (JwtException $e) {
// 刷新过程中发生其他错误
}
// refreshToken 方法会自动将旧 Token 加入黑名单
try {
$tokenObject = $this->jwtManager->parse($tokenString);
if ($tokenObject) {
$this->jwtManager->invalidate($tokenObject);
// Token 已成功加入黑名单
}
} catch (JwtException $e) {
}
// config/dependencies.php
return [
\FriendsOfHyperf\Jwt\Contract\PayloadFactoryInterface::class => \App\Service\MyCustomPayloadFactory::class,
];
bash
php bin/hyperf.php vendor:publish friendsofhyperf/jwt
php bin/hyperf.php jwt:gen-key --algo=HS256