-
Notifications
You must be signed in to change notification settings - Fork 232
Fix token expired throw error / 修复token过期,直接抛出异常错误,增加捕获异常。 #718
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,7 +12,12 @@ | |
|
|
||
| namespace App\Http\Common\Middleware; | ||
|
|
||
| use App\Http\Common\Result; | ||
| use App\Http\Common\ResultCode; | ||
| use Hyperf\Codec\Json; | ||
| use Hyperf\HttpMessage\Stream\SwooleStream; | ||
| use Lcobucci\JWT\UnencryptedToken; | ||
| use Lcobucci\JWT\Validation\RequiredConstraintsViolated; | ||
| use Mine\Jwt\JwtInterface; | ||
| use Mine\JwtAuth\Middleware\AbstractTokenMiddleware; | ||
| use Psr\Http\Message\ResponseInterface; | ||
|
|
@@ -24,16 +29,25 @@ class RefreshTokenMiddleware extends AbstractTokenMiddleware | |
| { | ||
| public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | ||
| { | ||
| $this->checkToken->checkJwt($this->parserToken($request)); | ||
| try { | ||
| $token = $this->parserToken($request); | ||
| } catch (RequiredConstraintsViolated $e) { | ||
| $isExpired = str_contains($e->getMessage(), 'The token is expired'); | ||
| $result = new Result( | ||
| code: ResultCode::UNAUTHORIZED, | ||
| message: $isExpired ? trans('jwt.expired') : trans('jwt.unauthorized'), | ||
| ); | ||
| return $this->buildErrorResponse($request, $result); | ||
| } | ||
|
|
||
| $this->checkToken->checkJwt($token); | ||
| return $handler->handle( | ||
| value( | ||
| static function (ServerRequestPlusInterface $request, UnencryptedToken $token) { | ||
| return $request->setAttribute('token', $token); | ||
| }, | ||
| $request, | ||
| $this->getJwt()->parserRefreshToken( | ||
| $this->getToken($request) | ||
| ) | ||
| $token | ||
| ) | ||
| ); | ||
| } | ||
|
|
@@ -47,4 +61,13 @@ protected function parserToken(ServerRequestInterface $request): UnencryptedToke | |
| { | ||
| return $this->getJwt()->parserRefreshToken($this->getToken($request)); | ||
| } | ||
| } | ||
|
|
||
| private function buildErrorResponse(ServerRequestInterface $request, Result $result): ResponseInterface | ||
| { | ||
| /** @var \Swow\Psr7\Message\ResponsePlusInterface $response */ | ||
| $response = \Hyperf\Context\Context::get(ResponseInterface::class); | ||
| return $response | ||
| ->setHeader('Content-Type', 'application/json; charset=utf-8') | ||
| ->setBody(new SwooleStream(Json::encode($result->toArray()))); | ||
|
Comment on lines
+65
to
+71
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
🧹 建议修复- return $this->buildErrorResponse($request, $result);
+ return $this->buildErrorResponse($result);
...
- private function buildErrorResponse(ServerRequestInterface $request, Result $result): ResponseInterface
+ private function buildErrorResponse(Result $result): ResponseInterface
{
/** `@var` \Swow\Psr7\Message\ResponsePlusInterface $response */
$response = \Hyperf\Context\Context::get(ResponseInterface::class);
return $response
->setHeader('Content-Type', 'application/json; charset=utf-8')
->setBody(new SwooleStream(Json::encode($result->toArray())));
}🧰 Tools🪛 PHPMD (2.15.0)[warning] 65-65: Avoid unused parameters such as '$request'. (undefined) (UnusedFormalParameter) 🤖 Prompt for AI Agents |
||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 118
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 149
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 3069
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 116
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
rg "RequiredConstraintsViolated" --type php -B 2 -A 5Repository: mineadmin/MineAdmin
Length of output: 3227
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 78
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 80
🌐 Web query:
Lcobucci JWT library violations() API constraint checking expiration💡 Result:
In lcobucci/jwt,
violations()is how you inspect which validation constraints failed when you useValidator::assert()and catchRequiredConstraintsViolated. The validator will run all constraints, collect all failures, then throw;violations()returns the collected constraint-violation exceptions. (lcobucci-jwt.readthedocs.io)To check expiration (
exp) you must include a time constraint:StrictValidAt(requiresiat,nbf, andexpto be present) orLooseValidAt(only checks those claims if present). (lcobucci-jwt.readthedocs.io)StrictValidAtthrows a violation ifexpis missing and throws “The token is expired” if it’s expired. (raw.githubusercontent.com)Example (assert + violations, with optional leeway):
(
StrictValidAt/LooseValidAtaccept an optionalDateIntervalleeway; negative leeway is rejected.) (raw.githubusercontent.com)Citations:
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 78
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🌐 Web query:
Lcobucci JWT violations constraint instance check type expiration💡 Result:
In lcobucci/jwt,
Validator::assert()throwsRequiredConstraintsViolated, and you can inspect the individualConstraintViolationobjects via$e->violations()to see which constraint failed and why. [1][2]How to detect “expired token” vs other failures
Time checks are performed by
LooseValidAt/StrictValidAt. When the token is expired they throw aConstraintViolationwith message"The token is expired". [3][4]In v6+,
ConstraintViolationcarries the failing constraint as a class-string in$violation->constraint(set byConstraintViolation::error(...)). [2]Notes
StrictValidAtcan also fail because requirediat/nbf/expclaims are missing (it throws violations like"Expiration Time" claim missing). [4]LooseValidAtonly checks those claims if present. [3]Sources: [1] [2] [3] [4]
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 1464
🏁 Script executed:
grep -i "lcobucci" ./composer.jsonRepository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
rg "lcobucci/jwt" --type jsonRepository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 126
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 9338
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
rg "StrictValidAt\|LooseValidAt\|ConstraintViolation" --type phpRepository: mineadmin/MineAdmin
Length of output: 45
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 100
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 35164
🏁 Script executed:
Repository: mineadmin/MineAdmin
Length of output: 50379
避免通过异常消息文本判断令牌过期
依赖
str_contains($e->getMessage(), 'The token is expired')存在脆弱性,会受库版本更新和语言环境变化的影响。建议改为遍历$e->violations()检查约束类型:这样既保持向后兼容性,又提高了代码的稳定性。注意此模式同样适用于
AccessTokenMiddleware.php。🤖 Prompt for AI Agents