定制 token/jwt 二次开发

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

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

token/jwt

Composer 安装命令:

composer require token/jwt

包简介

A simple library to work with JSON Web Token and JSON Web Signature.

关键字:

README 文档

README

A simple library to work with JSON Web Token and JSON Web Signature based on the RFC 7519.

GitHub Tag Total Downloads Packagist Version Packagist PHP Version Support Packagist License

Installation

You can install the package via Composer:

composer require token/jwt

Documentation

The documentation is available at https://dependencies-packagist.github.io/jwt/zh/.

Supported Algorithms

This library supports signing and verifying tokens with both symmetric and asymmetric algorithms. Encryption is not yet supported.

Each algorithm will produce signature with different length. If you have constraints regarding the length of the issued tokens, choose the algorithms that generate shorter output (HS256, RS256, and ES256).

Symmetric algorithms

Symmetric algorithms perform signature creation and verification using the very same key/secret. They're usually recommended for scenarios where these operations are handled by the very same component.

Name Description Class Key length req.
HS256 HMAC using SHA-256 \Token\JWT\Signature\Hmac\HS256 >= 256 bits
HS384 HMAC using SHA-384 \Token\JWT\Signature\Hmac\HS384 >= 384 bits
HS512 HMAC using SHA-512 \Token\JWT\Signature\Hmac\HS512 >= 512 bits

Asymmetric algorithms

Asymmetric algorithms perform signature creation with private/secret keys and verification with public keys. They're usually recommended for scenarios where creation is handled by a component and verification by many others.

Name Description Class Key length req.
ES256 ECDSA using P-256 and SHA-256 \Token\JWT\Signature\Ecdsa\ES256 == 256 bits
ES384 ECDSA using P-384 and SHA-384 \Token\JWT\Signature\Ecdsa\ES384 == 384 bits
ES512 ECDSA using P-521 and SHA-512 \Token\JWT\Signature\Ecdsa\ES512 == 521 bits
RS256 RSASSA-PKCS1-v1_5 using SHA-256 \Token\JWT\Signature\Rsa\RS256 >= 2048 bits
RS384 RSASSA-PKCS1-v1_5 using SHA-384 \Token\JWT\Signature\Rsa\RS384 >= 2048 bits
RS512 RSASSA-PKCS1-v1_5 using SHA-512 \Token\JWT\Signature\Rsa\RS512 >= 2048 bits
EdDSA EdDSA signature algorithms \Token\JWT\Signature\Eddsa >= 256 bits

none algorithm

The none algorithm as described by JWT standard is intentionally not implemented and not supported. The risk of misusing it is too high, and even where other means guarantee the token validity a symmetric algorithm shouldn't represent a computational bottleneck with modern hardware.

Usage

Issuing tokens

use Token\JWT\Builder;
use Token\JWT\Encoding\ChainedFormatter;
use Token\JWT\Encoding\JoseEncoder;
use Token\JWT\Signature\Hmac\HS256;
use Token\JWT\Key;

$algorithm  = new HS256();
$signingKey = Key::plainText(random_bytes(32));

$now     = new DateTimeImmutable();
$builder = new Builder(new JoseEncoder(), ChainedFormatter::default());
$token   = $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('4f1g23a12aa')
    // 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('+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($algorithm, $signingKey);

var_dump($token->toString());

Parsing tokens

To parse a token you must create a new parser and ask it to parse a string:

use Token\JWT\Parser;
use Token\JWT\Encoding\JoseEncoder;

$parser = new Parser(new JoseEncoder());

$token = $parser->parse(
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.'
    . 'eyJzdWIiOiIxMjM0NTY3ODkwIn0.'
    . '2gSBz9EOsQRN9I-3iSxJoFt7NtgV6Rm0IL6a8CAwl3Q'
);

var_dump($token->headers()); // Retrieves the token headers
var_dump($token->claims()); // Retrieves the token claims

Validating tokens

This method goes through every single constraint in the set, groups all the violations, and throws an exception with the grouped violations:

use Token\JWT\Encoding\JoseEncoder;
use Token\JWT\Exceptions\RequiredConstraintsViolated;
use Token\JWT\Parser;
use Token\JWT\Validation\Constraint\RelatedTo;
use Token\JWT\Validation\Validator;

$parser = new Parser(new JoseEncoder());

$token = $parser->parse(
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.'
    . 'eyJzdWIiOiIxMjM0NTY3ODkwIn0.'
    . '2gSBz9EOsQRN9I-3iSxJoFt7NtgV6Rm0IL6a8CAwl3Q'
);

$validator = new Validator();

try {
    // $validator->assert($token, new RelatedTo('1234567891'));// throw an exception
    $validator->assert($token, new RelatedTo('1234567890'));
} catch (RequiredConstraintsViolated $e) {
    // list of constraints violation exceptions:
    var_dump($e->violations());
}

var_dump($token->toString());

Available constraints

This library provides the following constraints:

  • Token\JWT\Validation\Constraint\IdentifiedBy: verifies if the claim jti matches the expected value
  • Token\JWT\Validation\Constraint\IssuedBy: verifies if the claim iss is listed as expected values
  • Token\JWT\Validation\Constraint\PermittedFor: verifies if the claim aud contains the expected value
  • Token\JWT\Validation\Constraint\RelatedTo: verifies if the claim sub matches the expected value
  • Token\JWT\Validation\Constraint\SignedWith: verifies if the token was signed with the expected signer and key
  • Token\JWT\Validation\Constraint\ValidAt: verifies the claims iat, nbf, and exp (supports leeway configuration)

Acknowledgements

This project is heavily inspired by and refactored from @lcobucci's excellent work on lcobucci/jwt.

We appreciate the clean architecture and thoughtful design of the original implementation, which made it much easier to build upon and extend with our own features.

Original Project License: BSD-3-Clause license
Please refer to the original repository for detailed history and contributions.

License

Nacosvel Contracts is made available under the MIT License (MIT). Please see License File for more information.

token/jwt 适用场景与选型建议

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

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-04-14