agielks/yii2-jwt
Composer 安装命令:
composer require agielks/yii2-jwt
包简介
JWT based on Icobucci version 4.1
README 文档
README
This extension provides the JWT integration for the Yii framework 2.0 (requires PHP 8.0+). It includes basic HTTP authentication support.
Table of contents
Instalation
Package is available on Packagist, you can install it using Composer.
composer require agielks/yii2-jwt ~1.0
or add to the require section of your composer.json file.
"agielks/yii2-jwt": "~1.0"
Dependencies
- PHP 8.0+
- OpenSSL Extension
- Sodium Extension
- lcobucci/jwt 4.1
Basic Usage
Add jwt component to your configuration file,
'components' => [ 'jwt' => [ 'class' => \agielks\yii2\jwt\Jwt::class, // 'singer' => new \Lcobucci\JWT\Signer\Hmac\Sha256(), 'signer' => 'HS256', // 'key' => \Lcobucci\JWT\Signer\Key\InMemory::plainText('my-key'), 'key' => 'my-key', , ], ],
Important: If you don't provide the signer and the key it will use unsecured signer
Configure the authenticator behavior as follows.
namespace app\controllers; class SiteController extends \yii\rest\Controller { /** * @inheritdoc */ public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => \agielks\yii2\jwt\JwtBearerAuth::class, ]; return $behaviors; } }
Also you can use it with CompositeAuth reffer to a doc.
Create Token
/* @var $jwt \agielks\yii2\jwt\Jwt */ $now = new DateTimeImmutable(); $jwt = Yii::$app->get('jwt'); $token = $jwt ->builder() // Configures the issuer (iss claim) ->issuedBy('http://example.com') // Configures the audience (aud claim) ->permittedFor('http://example.org') // Configures the id (jti claim) ->identifiedBy('62cbfaca6bf7e') // Configures the time that the token was issue (iat claim) ->issuedAt($now) // Configures the time that the token can be used (nbf claim) required for StrictValidAt constraint ->canOnlyBeUsedAfter($now) // Configures the expiration time of the token (exp claim) ->expiresAt($now->modify('+1 hour')) // Configures a new claim, called "uid" ->withClaim('uid', '62cbfaca6bf7e') // Configures a new header, called "foo" ->withHeader('foo', 'bar') // Builds a new token ->getToken($jwt->signer(), $jwt->key()); // Retrieves all headers $token->headers()->all(); // Retrives typ from headers $token->headers()->get('typ'); // Print typ from headers print_r($token->headers()->get('typ')); // Retrieves all claims $token->claims()->all(); // Retrieves jti from claims $token->claims()->get('jti'); // Print jti from claims print_r($token->claims()->get('jti'));
Parse Token From String
/* @var $jwt \agielks\yii2\jwt\Jwt */ $now = new DateTimeImmutable(); $jwt = Yii::$app->get('jwt'); $token = $jwt ->builder() // ... ->expiresAt($now->modify('+1 hour')) ->getToken($jwt->signer(), $jwt->key()) ->toString(); // Parse without validation $data = $jwt->config()->parser()->parse($token); // Parse with validation $data = $jwt->load($token); // Print all headers print_r($data->headers()->all()); // Print all claims print_r($data->claims()->all()); // Validate token var_dump($data->isExpired($now)); var_dump($data->isExpired($now->modify('+2 hour')));
Validate Token
You can configure your own validation with simple configuration in your component
use \agielks\yii2\jwt\Jwt; use \Lcobucci\JWT\Signer\Hmac\Sha256; use \Lcobucci\JWT\Signer\Key\InMemory; use \Lcobucci\JWT\Validation\Constraint\LooseValidAt; use \Lcobucci\JWT\Validation\Constraint\SignedWith; use \Lcobucci\JWT\Validation\Constraint\IdentifiedBy; use \Lcobucci\Clock\SystemClock; 'components' => [ 'jwt' => [ 'class' => Jwt::class, 'signer' => new Sha256(), 'key' => InMemory::plainText('my-key'), 'constraints' => [ new LooseValidAt(SystemClock::fromSystemTimezone()), new SignedWith( new Sha256(), InMemory::plainText('my-key') ), new IdentifiedBy('my-identity'), ], ], ],
Login Example
Basic scheme
- Client send credentials. For example, login + password
- App validate the credentials
- If credentials is valid client receive token
- Client store token for the future requests
Step by step usage
- Install component
composer require agielks/yii2-jwt ~1.0
- Update your components configuration
'components' => [ // other components here... 'jwt' => [ 'class' => \agielks\yii2\jwt\Jwt::class, // 'singer' => new \Lcobucci\JWT\Signer\Hmac\Sha256(), 'signer' => 'HS256', // 'key' => \Lcobucci\JWT\Signer\Key\InMemory::plainText('my-key'), 'key' => 'my-key', , ], // ... ],
- Change method
User::findIdentityByAccessToken()
/** * {@inheritdoc} * @param \Lcobucci\JWT\Token $token */ public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['id' => $token->claims()->get('uid')]); }
If you want to use auth_key as key, update method as follows
/** * {@inheritdoc} * @param \Lcobucci\JWT\Token $token */ public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['auth_key' => $token->claims()->get('auth_key')]); }
- Create controller
use agielks\yii2\jwt\JwtBearerAuth; // Use your own login form use common\models\LoginForm; use DateTimeImmutable; use Yii; use yii\base\InvalidConfigException; use yii\filters\Cors; use yii\rest\Controller; use yii\web\Response; /** * Class SiteController */ class SiteController extends Controller { /** * {@inheritdoc} */ public function behaviors() { $behaviors = parent::behaviors(); $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON; $behaviors['corsFilter'] = ['class' => Cors::class]; $behaviors['authenticator'] = [ 'class' => JwtBearerAuth::class, 'optional' => [ 'login', ], ]; return $behaviors; } /** * {@inheritdoc} */ protected function verbs() { return [ 'login' => ['OPTIONS', 'POST'], ]; } /** * @return array|LoginForm * @throws InvalidConfigException */ public function actionLogin() { $model = new LoginForm(); if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) { /* @var $jwt \agielks\yii2\jwt\Jwt */ $now = new DateTimeImmutable(); $jwt = Yii::$app->get('jwt'); $user = $model->getUser(); return $jwt ->builder() // Configures the issuer (iss claim) ->issuedBy('http://example.com') // Configures the audience (aud claim) ->permittedFor('http://example.org') // Configures the id (jti claim) ->identifiedBy($user->id) // 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) // Configures the expiration time of the token (exp claim) ->expiresAt($now->modify('+1 hour')) // Configures a new claim, called "uid" ->withClaim('uid', $user->id) // Configures a new claim, called "auth_key" ->withClaim('auth_key', $user->auth_key) // Returns a signed token to be used ->getToken($jwt->signer(), $jwt->key()) // Convert token to string ->toString(); } $model->validate(); return $model; } /** * Test authentication */ public function actionTest() { return ['auth' => 'success']; } }
agielks/yii2-jwt 适用场景与选型建议
agielks/yii2-jwt 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.42k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 07 月 13 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「jwt」 「yii2」 「yii 2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 agielks/yii2-jwt 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 agielks/yii2-jwt 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 agielks/yii2-jwt 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A custom URL rule class for Yii 2 which allows to create translated URL rules
Yii2 LightBox image galary widget uses Lightbox v2.10.0 by Lokesh Dhakar
A simple library to decode and parse Apple Sign In client tokens.
JWT API authentication driver (Guard) for Laravel.
Priveate for SkeekS CMS
Laravel JWT auth service package
统计信息
- 总下载量: 3.42k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 15
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2022-07-13