bizley/jwt
Composer 安装命令:
composer require bizley/jwt
包简介
JWT integration for Yii 2
关键字:
README 文档
README
JWT Integration For Yii 2
This extension provides the JWT integration for Yii 2 framework.
This is a fork of sizeg/yii2-jwt package
Available versions
| bizley/yii2-jwt | lcobucci/jwt | php |
|---|---|---|
^4.0 |
^5.0 |
>=8.1 |
^3.0 |
^4.0 |
>=7.4 |
^2.0 |
^3.0 |
>=7.1 |
See lcobucci/jwt repo for details about the version.
Installation
Add the package to your composer.json:
{
"require": {
"bizley/jwt": "^4.0"
}
}
and run composer update or alternatively run composer require bizley/jwt:^4.0
Basic usage
Add jwt component to your configuration file.
If your application is both the issuer and the consumer of JWT (the common case, a.k.a. Standard version)
use bizley\jwt\Jwt component:
[
'components' => [
'jwt' => [
'class' => \bizley\jwt\Jwt::class,
'signer' => ... // Signer ID, or signer object, or signer configuration, see "Available signers" below
'signingKey' => ... // Secret key string or path to the signing key file, see "Keys" below
// ... any additional configuration here
],
],
],
If your application just needs some special JWT tools (like validator or parser, a.k.a. Toolset version)
use bizley\jwt\JwtTools component:
[
'components' => [
'jwt' => [
'class' => \bizley\jwt\JwtTools::class,
// ... any additional configuration here
],
],
],
Of course, if you are already using the Standard version component, you don't need to define the Toolset version component, since the former already provides all the tools.
If you are struggling with the concept of API JWT, here is an EXAMPLE of how to quickly put all pieces together.
Available signers
Symmetric:
- HMAC (HS256, HS384, HS512)
Asymmetric:
- RSA (RS256, RS384, RS512)
- ECDSA (ES256, ES384, ES512)
- EdDSA (since 3.1.0)
- BLAKE2B (since 3.4.0)
Signer IDs are available as constants (like Jwt::HS256).
You can also provide your own signer, either as an instance of Lcobucci\JWT\Signer or by adding its config to signers
and algorithmTypes and using its ID for signer.
As stated in
lcobucci/jwtdocumentation: Although BLAKE2B is fantastic due to its performance, it's not JWT standard and won't necessarily be offered by other libraries.
Note on signers and minimum bits requirement
Since lcobucci/jwt 4.2.0 signers require the minimum key length to make sure those are properly secured, otherwise
the InvalidKeyProvided is thrown.
Keys
For symmetric signers signingKey is required. For asymmetric ones you also need to set verifyingKey. Keys can be
provided as simple strings, configuration arrays, or instances of Lcobucci\JWT\Signer\Key.
Configuration array can be as the following:
[
'key' => /* key content */,
'passphrase' => /* key passphrase */,
'method' => /* method type */,
]
- key (
bizley\jwt\Jwt::KEY) - string, default'', start it with@if it's Yii alias, - passphrase (
bizley\jwt\Jwt::PASSPHRASE) - string, default'', - method (
bizley\jwt\Jwt::METHOD) - string, defaultbizley\jwt\Jwt::METHOD_PLAIN, available:bizley\jwt\Jwt::METHOD_PLAIN,bizley\jwt\Jwt::METHOD_BASE64,bizley\jwt\Jwt::METHOD_FILE(see https://lcobucci-jwt.readthedocs.io/en/latest/configuration/)
Simple string keys are shortcuts to the following array configs:
-
key starts with
@orfile://:[ 'key' => /* given key itself */, 'passphrase' => '', 'method' => \bizley\jwt\Jwt::METHOD_FILE, ]Detecting
@at the beginning assumes Yii alias has been provided, so it will be resolved withYii::getAlias(). -
key doesn't start with
@norfile://:[ 'key' => /* given key itself */, 'passphrase' => '', 'method' => \bizley\jwt\Jwt::METHOD_PLAIN, ]
Issuing a token example:
Standard version:
$now = new \DateTimeImmutable(); /** @var \Lcobucci\JWT\Token\UnencryptedToken $token */ $token = Yii::$app->jwt->getBuilder() // Configures the issuer (iss claim) ->issuedBy('http://example.com') // Configures the audience (aud claim) ->permittedFor('http://example.org') // Configures the id (jti claim) ->identifiedBy('4f1g23a12aa') // Configures the time that the token was issued (iat claim) ->issuedAt($now) // Configures the time that the token can be used (nbf claim) ->canOnlyBeUsedAfter($now->modify('+1 minute')) // Configures the expiration time of the token (exp claim) ->expiresAt($now->modify('+1 hour')) // Configures a new claim, called "uid" ->withClaim('uid', 1) // Configures a new header, called "foo" ->withHeader('foo', 'bar') // Builds a new token ->getToken( Yii::$app->jwt->getConfiguration()->signer(), Yii::$app->jwt->getConfiguration()->signingKey() ); $tokenString = $token->toString();
The same in Toolset version:
$now = new \DateTimeImmutable(); /** @var \Lcobucci\JWT\Token\UnencryptedToken $token */ $token = Yii::$app->jwt->getBuilder() ->issuedBy('http://example.com') ->permittedFor('http://example.org') ->identifiedBy('4f1g23a12aa') ->issuedAt($now) ->canOnlyBeUsedAfter($now->modify('+1 minute')) ->expiresAt($now->modify('+1 hour')) ->withClaim('uid', 1) ->withHeader('foo', 'bar') ->getToken( Yii::$app->jwt->buildSigner(/* signer definition */), Yii::$app->jwt->buildKey(/* signing key definition */) ); $tokenString = $token->toString();
See https://lcobucci-jwt.readthedocs.io/en/latest/issuing-tokens/ for more info.
Parsing a token
/** @var non-empty-string $jwt */ /** @var \Lcobucci\JWT\Token $token */ $token = Yii::$app->jwt->parse($jwt);
See https://lcobucci-jwt.readthedocs.io/en/latest/parsing-tokens/ for more info.
Validating a token
You can validate a token or perform an assertion on it (see https://lcobucci-jwt.readthedocs.io/en/latest/validating-tokens/).
For validation use:
/** @var \Lcobucci\JWT\Token | non-empty-string $token */ /** @var bool $result */ $result = Yii::$app->jwt->validate($token);
For assertion use:
/** @var \Lcobucci\JWT\Token | string $token */ Yii::$app->jwt->assert($token);
You MUST provide at least one constraint, otherwise Lcobucci\JWT\Validation\NoConstraintsGiven exception will be
thrown. There are several ways to provide constraints:
-
directly (Standard version only):
Yii::$app->jwt->getConfiguration()->setValidationConstraints(/* constaints here */);
-
through component configuration:
[ 'validationConstraints' => /* array of instances of Lcobucci\JWT\Validation\Constraint or array of configuration arrays that can be resolved as Constraint instances or anonymous function that can be resolved as array of Constraint instances with signature `function(\bizley\jwt\Jwt|\bizley\jwt\JwtTools $jwt)` where $jwt will be an instance of used component */, ]
Note: By default, this package is not adding any constraints out-of-the-box, you must configure them yourself like in the examples above.
Using component for REST authentication
Configure the authenticator behavior in the controller.
class ExampleController extends Controller { public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => \bizley\jwt\JwtHttpBearerAuth::class, ]; return $behaviors; } }
There are special options available:
- jwt - string ID of component (default with
'jwt'), component configuration array, or an instance ofbizley\jwt\Jwtorbizley\jwt\JwtTools, - auth - callable or
null(default) - anonymous function with signaturefunction (\Lcobucci\JWT\Token $token)that should return identity of user authenticated with the JWT payload information. If $auth is not provided methodyii\web\User::loginByAccessToken()will be called instead. - throwException - bool (default
true) - whether the filter should throw an exception i.e. if the token has an invalid format. If there are multiple auth filters (CompositeAuth) it can make sense to "silent fail" and pass the validation process to the next filter on the composite auth list.
For other configuration options refer to the Yii 2 Guide.
JWT Usage
Please refer to the lcobucci/jwt Documentation.
JSON Web Tokens
bizley/jwt 适用场景与选型建议
bizley/jwt 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 472.98k 次下载、GitHub Stars 达 69, 最近一次更新时间为 2018 年 11 月 03 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「Authentication」 「token」 「jwt」 「JWS」 「yii2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 bizley/jwt 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 bizley/jwt 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 bizley/jwt 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Automatically logs-in users if they are already authenticated by a remote source. (e.g. environment variable REMOTE_USER)
GraphQL authentication for your headless Craft CMS applications.
A simple library to decode and parse Apple Sign In client tokens.
A package for validating Google Cloud's JWT provided by webhooks
JSON Web Token Authentication for Laravel and Lumen
Laravel middleware to restrict a site or specific routes using HTTP basic authentication
统计信息
- 总下载量: 472.98k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 69
- 点击次数: 16
- 依赖项目数: 3
- 推荐数: 3
其他信息
- 授权协议: Apache-2.0
- 更新时间: 2018-11-03