kaabar-jwt/yii2-jwt 问题修复 & 功能扩展

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

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

kaabar-jwt/yii2-jwt

Composer 安装命令:

composer require kaabar-jwt/yii2-jwt

包简介

The Yii2 JWT extension is a tool for implementing JWT (JSON Web Token) authentication in Yii2 applications. It allows developers to create APIs that require authentication and authorization, ensuring that only authorized users can access certain resources. The extension provides a simple and flexibl

README 文档

README

The Yii2 JWT extension is a tool for implementing JWT (JSON Web Token) authentication in Yii2 applications. It allows developers to create APIs that require authentication and authorization, ensuring that only authorized users can access certain resources. The extension provides a simple and flexible way to implement JWT authentication in Yii2, using the JWT library and following the JWT specification. It includes support for creating and verifying JWT tokens, as well as handling token expiration and refresh. The Yii2 JWT extension can be easily integrated into any Yii2 application, making it a powerful tool for API authentication and authorization.

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist kaabar-jwt/yii2-jwt:dev-master 

or add

"kaabar-jwt/yii2-jwt": "dev-master" 

to the require section of your composer.json file.

Implementation Steps

  • Yii2 installed
  • An https enabled site is required for the HttpOnly cookie to work cross-site
  • A database table for storing RefreshTokens:
<?php CREATE TABLE `user_refresh_tokens` ( `user_refresh_tokenID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `urf_userID` INT(10) UNSIGNED NOT NULL, `urf_token` VARCHAR(1000) NOT NULL, `urf_ip` VARCHAR(50) NOT NULL, `urf_user_agent` VARCHAR(1000) NOT NULL, `urf_created` DATETIME NOT NULL COMMENT 'UTC', PRIMARY KEY (`user_refresh_tokenID`) ) COMMENT='For JWT authentication process'; ?>
  • Add JWT parameters in /config/params.php
<?php return [ ... 'jwt' => [ 'issuer' => 'https://api.example.com', //name of your project (for information only) 'audience' => 'https://example.com', //description of the audience, eg. the website using the authentication (for info only) 'id' => 'AMqey0yAVrqmhR82RMlWB3zqMpvRP0zaaOheEeq2tmmcEtRYNj', //a unique identifier for the JWT, typically a random string 'expire' => '+1 hour', //the short-lived JWT token is here set to expire after 1 Hours. 'request_time' => '+5 seconds', //the time between the two requests. (optional) ], ... ]; ?>
  • Add component in configuration in /config/web.php for initializing JWT authentication:
<?php $config = [ 'components' => [ ... 'jwt' => [ 'class' => \kaabar\jwt\Jwt::class, 'key' => 'SECRET-KEY', //typically a long random string ], ... ], ]; ?>
  • Add the authenticator behavior to your controllers

  • For AuthController.php we must exclude actions that do not require being authenticated, like login, options (when browser sends the cross-site OPTIONS request).

<?php public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => \kaabar\jwt\JwtHttpBearerAuth::class, 'except' => [ 'login', 'options', ], ]; return $behaviors; } ?>
  • Add the methods generateJwt() and generateRefreshToken() to AuthController.php. We'll be using them in the login/refresh-token actions. Adjust class name for your user model if different.
<?php private function generateJwt(\app\models\User $user) { $jwt = Yii::$app->jwt; $signer = $jwt->getSigner('HS256'); $key = $jwt->getKey(); //use DateTimeImmutable; $now = new DateTimeImmutable(); $jwtParams = Yii::$app->params['jwt']; $token = $jwt->getBuilder() // Configures the issuer (iss claim) ->issuedBy($jwtParams['issuer']) // Configures the audience (aud claim) ->permittedFor($jwtParams['audience']) // Configures the id (jti claim) ->identifiedBy($jwtParams['id'], true) // Configures the time that the token was issue (iat claim) ->issuedAt($now) // Configures the time that the token can be used (nbf claim) ->canOnlyBeUsedAfter($now->modify($jwtParams['request_time'])) // Configures the expiration time of the token (exp claim) ->expiresAt($now->modify($jwtParams['expire'])) // Configures a new claim, called "uid" ->withClaim('uid', $user->id) // Builds a new token ->getToken($signer, $key); return $token->toString(); } /**  * @throws yii\base\Exception */ private function generateRefreshToken(\app\models\User $user, \app\models\User $impersonator = null): \app\models\UserRefreshToken { $refreshToken = Yii::$app->security->generateRandomString(200); // TODO: Don't always regenerate - you could reuse existing one if user already has one with same IP and user agent $userRefreshToken = new \app\models\UserRefreshToken([ 'urf_userID' => $user->id, 'urf_token' => $refreshToken, 'urf_ip' => Yii::$app->request->userIP, 'urf_user_agent' => Yii::$app->request->userAgent, 'urf_created' => gmdate('Y-m-d H:i:s'), ]); if (!$userRefreshToken->save()) { throw new \yii\web\ServerErrorHttpException('Failed to save the refresh token: '. $userRefreshToken->getErrorSummary(true)); } // Send the refresh-token to the user in a HttpOnly cookie that Javascript can never read and that's limited by path Yii::$app->response->cookies->add(new \yii\web\Cookie([ 'name' => 'refresh-token', 'value' => $refreshToken, 'httpOnly' => true, 'sameSite' => 'none', 'secure' => true, 'path' => '/v1/auth/refresh-token', //endpoint URI for renewing the JWT token using this refresh-token, or deleting refresh-token ])); return $userRefreshToken; } ?>
  • Add the login action to AuthController.php:
<?php public function actionLogin() { $model = new \app\models\LoginForm(); if ($model->load(Yii::$app->request->getBodyParams()) && $model->login()) { $user = Yii::$app->user->identity; $token = $this->generateJwt($user); return [ 'user' => $user, 'token' => (string) $token, ]; } else { $model->validate(); return $model; } } ?>
  • Add the refresh-token action to AuthController.php. Call POST /auth/refresh-token when JWT has expired, and call DELETE /auth/refresh-token when user requests a logout (and then delete the JWT token from localStorage).
<?php public function actionRefreshToken() { $refreshToken = Yii::$app->request->cookies->getValue('refresh-token', false); if (!$refreshToken) { return new \yii\web\UnauthorizedHttpException('No refresh token found.'); } $userRefreshToken = \app\models\UserRefreshToken::findOne(['urf_token' => $refreshToken]); if (Yii::$app->request->getMethod() == 'POST') { // Getting new JWT after it has expired if (!$userRefreshToken) { return new \yii\web\UnauthorizedHttpException('The refresh token no longer exists.'); } $user = \app\models\User::find() //adapt this to your needs ->where(['userID' => $userRefreshToken->urf_userID]) ->andWhere(['not', ['usr_status' => 'inactive']]) ->one(); if (!$user) { $userRefreshToken->delete(); return new \yii\web\UnauthorizedHttpException('The user is inactive.'); } $token = $this->generateJwt($user); return [ 'status' => 'ok', 'token' => (string) $token, ]; } elseif (Yii::$app->request->getMethod() == 'DELETE') { // Logging out if ($userRefreshToken && !$userRefreshToken->delete()) { return new \yii\web\ServerErrorHttpException('Failed to delete the refresh token.'); } return ['status' => 'ok']; } else { return new \yii\web\UnauthorizedHttpException('The user is inactive.'); } } ?>
  • Adapt findIdentityByAccessToken() in your user model to find the authenticated user via the uid claim from the JWT:
<?php public static function findIdentityByAccessToken($token, $type = null) { return static::find() ->where(['userID' => (string) $token->getClaim('uid') ]) ->andWhere(['<>', 'usr_status', 'inactive']) //adapt this to your needs ->one(); } ?>
  • Also remember to purge all RefreshTokens for the user when the password is changed, eg. in afterSave() in your user model:
<?php public function afterSave($isInsert, $changedOldAttributes) { // Purge the user tokens when the password is changed if (array_key_exists('usr_password', $changedOldAttributes)) { \app\models\UserRefreshToken::deleteAll(['urf_userID' => $this->userID]); } return parent::afterSave($isInsert, $changedOldAttributes); } ?>
  • Make a page where user can delete his RefreshTokens. List the records from user_refresh_tokens that belongs to the given user and allow him to delete the ones he chooses.

kaabar-jwt/yii2-jwt 适用场景与选型建议

kaabar-jwt/yii2-jwt 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 28.29k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2026 年 01 月 04 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「extension」 「yii2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 28.29k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 18
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-04