定制 bizley/jwt 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

bizley/jwt

Composer 安装命令:

composer require bizley/jwt

包简介

JWT integration for Yii 2

README 文档

README

Latest Stable Version Total Downloads License Mutation testing badge

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/jwt documentation: 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, default bizley\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 @ or file://:

    [
        '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 with Yii::getAlias().

  • key doesn't start with @ nor file://:

    [
        '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 of bizley\jwt\Jwt or bizley\jwt\JwtTools,
  • auth - callable or null (default) - anonymous function with signature function (\Lcobucci\JWT\Token $token) that should return identity of user authenticated with the JWT payload information. If $auth is not provided method yii\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 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 69
  • Watchers: 1
  • Forks: 89
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2018-11-03