PHPackages                             tinywan/jwt - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. tinywan/jwt

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

tinywan/jwt
===========

JSON Web Token (JWT) for webman plugin

v1.15.0(2mo ago)6549.3k↓18.5%25[15 issues](https://github.com/Tinywan/webman-jwt/issues)20MITPHPPHP ^7.1||^8.0CI failing

Since Feb 21Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/Tinywan/webman-jwt)[ Packagist](https://packagist.org/packages/tinywan/jwt)[ RSS](/packages/tinywan-jwt/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (49)Used By (20)

🚀 JSON Web Token (JWT)
======================

[](#--json-web-token-jwt)

[![Latest Version on Packagist](https://camo.githubusercontent.com/05b59538680b0702c72978a2d3e0c8f8c577b6c2aeb7d33cfe8a19c549636e85/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74696e7977616e2f6a77742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tinywan/jwt)[![Total Downloads](https://camo.githubusercontent.com/c6584480deeabd1eb25fd0714589036d314c8bd7cddd20f4a88afdc1e5da26d3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f74696e7977616e2f6a77742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tinywan/jwt)[![License](https://camo.githubusercontent.com/315dbd490c565b273c1d7c2de1b12966ac8f84d1e21feadd639764f7c67675f6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f74696e7977616e2f6a77742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tinywan/jwt)[![PHP Version](https://camo.githubusercontent.com/9c2f8ad80d34105266a94c4c06234f8ed18c968d3595039c2d9a7becd1e71c8b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e342d626c75652e737667)](https://www.php.net)[![zread](https://camo.githubusercontent.com/dbe8f5e3362d3184b37aab59634ca4d4b1fe396197913e176c81d9b4b2601c45/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f41736b5f5a726561642d5f2e7376673f7374796c653d666c617426636f6c6f723d303062306161266c6162656c436f6c6f723d303030303030266c6f676f3d64617461253341696d616765253246737667253242786d6c25334262617365363425324350484e325a79423361575230614430694d5459694947686c6157646f644430694d54596949485a705a58644362336739496a41674d4341784e6941784e6949675a6d6c7362443069626d39755a53496765473173626e4d39496d6830644841364c79393364336375647a4d7562334a6e4c7a49774d44417663335a6e496a344b50484268644767675a443069545451754f5459784e5459674d5334324d444178534449754d6a51784e545a444d5334344f446778494445754e6a41774d5341784c6a59774d545532494445754f4467324e6a51674d5334324d4445314e6941794c6a49304d4446574e4334354e6a4178517a45754e6a41784e5459674e53347a4d544d314e6941784c6a67344f4445674e5334324d444178494449754d6a51784e5459674e5334324d444178534451754f5459784e545a444e53347a4d5455774d6941314c6a59774d4445674e5334324d4445314e6941314c6a4d784d7a5532494455754e6a41784e5459674e4334354e6a4178566a49754d6a51774d554d314c6a59774d545532494445754f4467324e6a51674e53347a4d5455774d6941784c6a59774d4445674e4334354e6a45314e6941784c6a59774d4446614969426d615778735053496a5a6d5a6d496938253242436a78775958526f49475139496b30304c6a6b324d545532494445774c6a4d354f546c494d6934794e4445314e6b4d784c6a67344f4445674d5441754d7a6b354f5341784c6a59774d545532494445774c6a59344e6a51674d5334324d4445314e6941784d5334774d7a6b35566a457a4c6a63314f546c444d5334324d4445314e6941784e4334784d544d30494445754f4467344d5341784e43347a4f546b35494449754d6a51784e5459674d5451754d7a6b354f5567304c6a6b324d545532517a55754d7a45314d4449674d5451754d7a6b354f5341314c6a59774d545532494445304c6a45784d7a51674e5334324d4445314e6941784d7934334e546b35566a45784c6a417a4f546c444e5334324d4445314e6941784d4334324f445930494455754d7a45314d4449674d5441754d7a6b354f5341304c6a6b324d545532494445774c6a4d354f546c614969426d615778735053496a5a6d5a6d496938253242436a78775958526f49475139496b30784d7934334e546730494445754e6a41774d5567784d5334774d7a6730517a45774c6a59344e5341784c6a59774d4445674d5441754d7a6b344e4341784c6a67344e6a5930494445774c6a4d354f4451674d6934794e444178566a51754f5459774d554d784d43347a4f546730494455754d7a457a4e5459674d5441754e6a6731494455754e6a41774d5341784d5334774d7a6730494455754e6a41774d5567784d7934334e546730517a45304c6a45784d546b674e5334324d444178494445304c6a4d354f4451674e53347a4d544d314e6941784e43347a4f546730494451754f5459774d5659794c6a49304d4446444d5451754d7a6b344e4341784c6a67344e6a5930494445304c6a45784d546b674d5334324d4441784944457a4c6a63314f4451674d5334324d444178576949675a6d6c736244306949325a6d5a69497650676f38634746306143426b50534a4e4e4341784d6b77784d694130544451674d544a614969426d615778735053496a5a6d5a6d496938253242436a78775958526f49475139496b303049444579544445794944516949484e30636d39725a54306949325a6d5a694967633352796232746c4c5864705a48526f505349784c6a556949484e30636d39725a5331736157356c5932467750534a79623356755a43497650676f384c334e325a7a344b266c6f676f436f6c6f723d666666666666)](https://zread.ai/Tinywan/webman-jwt)

JWT 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准（(RFC 7519)，该token被设计为紧凑且安全的，特别适用于分布式站点的单点登录（SSO）场景。

> 注：从 `1.14.0` 版本开始，出于安全考虑新增了密钥长度验证。`1.14.0` 以下版本，基本不检查长度。`1.14.0` 及以上版本：强制检查。

安装
--

[](#安装)

```
composer require tinywan/jwt
```

使用
--

[](#使用)

### 生成令牌

[](#生成令牌)

```
use Tinywan\Jwt\JwtToken;

$user = [
    'id'  => 2022,
    'name'  => 'Tinywan',
    'email' => 'Tinywan@163.com'
];
$token = JwtToken::generateToken($user);
var_dump(json_encode($token));
```

**输出（json格式）**

```
{
    "token_type": "Bearer",
    "expires_in": 36000,
    "access_token": "eyJ0eXAiOiJAUR-Gqtnk9LUPO8IDrLK7tjCwQZ7CI...",
    "refresh_token": "eyJ0eXAiOiJIEGkKprvcccccQvsTJaOyNy8yweZc..."
}
```

**响应参数**

参数类型描述示例值token\_typestringToken 类型Bearerexpires\_inint凭证有效时间，单位：秒36000access\_tokenstring访问凭证XXXXXXXXXXXXXXXXXXXXrefresh\_tokenstring刷新凭证（访问凭证过期使用 ）XXXXXXXXXXXXXXXXXXXX支持函数列表
------

[](#支持函数列表)

1、获取当前`id`

```
$id = Tinywan\Jwt\JwtToken::getCurrentId();
```

2、获取所有字段

```
$email = Tinywan\Jwt\JwtToken::getExtend();
```

3、获取自定义字段

```
$email = Tinywan\Jwt\JwtToken::getExtendVal('email');
```

4、刷新令牌（通过刷新令牌获取访问令牌）

```
$refreshToken = Tinywan\Jwt\JwtToken::refreshToken();
```

5、获令牌有效期剩余时长

```
$exp = Tinywan\Jwt\JwtToken::getTokenExp();
```

6、单设备登录。默认是关闭，开启请修改配置文件`config/plugin/tinywan/jwt`

```
'is_single_device' => true,
```

> 单设备登录支持定义客户端 `client` 字段，自定义客户端单点登录（默认为`WEB`，即网页端），如：`MOBILE`、`APP`、`WECHAT`、`WEB`、`ADMIN`、`API`、`OTHER`等等

```
$user = [
    'id'  => 2022,
    'name'  => 'Tinywan',
    'client' => 'MOBILE',
];
$token = Tinywan\Jwt\JwtToken::generateToken($user);
var_dump(json_encode($token));
```

7、获取当前用户信息（模型）需要插件大于版本 `>=1.2.4`

```
$user = Tinywan\Jwt\JwtToken::getUser();
```

该配置项目`'user_model'`为一个匿名函数，默认返回空数组，可以根据自己项目ORM定制化自己的返回模型

**ThinkORM** 配置

```
'user_model' => function($uid) {
// 返回一个数组
return \think\facade\Db::table('resty_user')
	->field('id,username,create_time')
	->where('id',$uid)
	->find();
}
```

**LaravelORM** 配置

```
'user_model' => function($uid) {
// 返回一个对象
return \support\Db::table('resty_user')
	->where('id', $uid)
	->select('id','email','mobile','create_time')
	->first();
}
```

8、令牌清理

```
$res = Tinywan\Jwt\JwtToken::clear();
```

> 只有配置项 `is_single_device`为`true` 才会生效。可选参数：`MOBILE`、`APP`、`WECHAT`、`WEB`、`ADMIN`、`API`、`OTHER`等等

9、自定义终端`client`

```
// 生成WEB令牌
$user = [
    'id'  => 2022,
    'name'  => 'Tinywan',
    'client' => JwtToken::TOKEN_CLIENT_WEB
];
$token = JwtToken::generateToken($user);

// 生成移动端令牌
$user = [
    'id'  => 2022,
    'name'  => 'Tinywan',
    'client' => JwtToken::TOKEN_CLIENT_MOBILE
];
$token = JwtToken::generateToken($user);
```

默认是`WEB`端

10、自定义访问令牌和刷新令牌过期时间

```
$extend = [
    'id'  => 2024,
    'access_exp'  => 7200,  // 2 小时
];
$token = Tinywan\Jwt\JwtToken::generateToken($extend);
```

11、各个算法的最小长度要求（`HS*` 系列最常见）。插件大于版本 `>=1.14.0` 强制要求

算法最低密钥长度（字节）字符数参考（UTF-8）推荐生成方式HS25632 字节≥32 字符`bin2hex(random_bytes(32))` → 64 hex 字符HS38448 字节≥48 字符`random_bytes(48)`HS51264 字节≥64 字符`random_bytes(64)`12、令牌过期错误码

- 访问令牌
    - 身份验证令牌无效：`401011`
    - 身份验证令牌尚未生效：`401012`
    - 身份验证会话已过期，请重新登录！：`401013`
    - 获取的扩展字段不存在：`401014`
    - 访问令牌未知错误：`401015`
- 刷新令牌
    - 刷新令牌无效：`401021`
    - 刷新令牌尚未生效：`401022`
    - 刷新令牌会话已过期，请再次登录！：`401023`
    - 刷新令牌获取的扩展字段不存在：`401024`
    - 刷新令牌未知错误：`401025`

签名算法
----

[](#签名算法)

JWT 最常见的几种签名算法(JWA)：`HS256(HMAC-SHA256)` 、`RS256(RSA-SHA256)` 还有 `ES256(ECDSA-SHA256)`

### JWT 算法列表如下

[](#jwt-算法列表如下)

```
+--------------+-------------------------------+--------------------+
| "alg" Param  | Digital Signature or MAC      | Implementation     |
| Value        | Algorithm                     | Requirements       |
+--------------+-------------------------------+--------------------+
| HS256        | HMAC using SHA-256            | Required           |
| HS384        | HMAC using SHA-384            | Optional           |
| HS512        | HMAC using SHA-512            | Optional           |
| RS256        | RSASSA-PKCS1-v1_5 using       | Recommended        |
|              | SHA-256                       |                    |
| RS384        | RSASSA-PKCS1-v1_5 using       | Optional           |
|              | SHA-384                       |                    |
| RS512        | RSASSA-PKCS1-v1_5 using       | Optional           |
|              | SHA-512                       |                    |
| ES256        | ECDSA using P-256 and SHA-256 | Recommended+       |
| ES384        | ECDSA using P-384 and SHA-384 | Optional           |
| ES512        | ECDSA using P-521 and SHA-512 | Optional           |
| PS256        | RSASSA-PSS using SHA-256 and  | Optional           |
|              | MGF1 with SHA-256             |                    |
| PS384        | RSASSA-PSS using SHA-384 and  | Optional           |
|              | MGF1 with SHA-384             |                    |
| PS512        | RSASSA-PSS using SHA-512 and  | Optional           |
|              | MGF1 with SHA-512             |                    |
| none         | No digital signature or MAC   | Optional           |
|              | performed                     |                    |
+--------------+-------------------------------+--------------------+

The use of "+" in the Implementation Requirements column indicates
that the requirement strength is likely to be increased in a future
version of the specification.
```

> 可以看到被标记为 Recommended 的只有 RS256 和 ES256。

### 对称加密算法

[](#对称加密算法)

> 插件安装默认使用`HS256 `对称加密算法。

HS256 使用同一个`「secret_key」`进行签名与验证。一旦 `secret_key `泄漏，就毫无安全性可言了。因此 HS256 只适合集中式认证，签名和验证都必须由可信方进行。

### 非对称加密算法

[](#非对称加密算法)

> RS256 系列是使用 RSA 私钥进行签名，使用 RSA 公钥进行验证。

公钥即使泄漏也毫无影响，只要确保私钥安全就行。RS256 可以将验证委托给其他应用，只要将公钥给他们就行。

> 以下为RS系列算法生成命令，仅供参考

### RS512

[](#rs512)

```
ssh-keygen -t rsa -b 4096 -E SHA512 -m PEM -P "" -f RS512.key
openssl rsa -in RS512.key -pubout -outform PEM -out RS512.key.pub
```

### RS384

[](#rs384)

```
ssh-keygen -t rsa -b 4096 -E SHA354 -m PEM -P "" -f RS384.key
openssl rsa -in RS384.key -pubout -outform PEM -out RS384.key.pub
```

### RS256

[](#rs256)

```
ssh-keygen -t rsa -b 4096 -E SHA256 -m PEM -P "" -f RS256.key
openssl rsa -in RS256.key -pubout -outform PEM -out RS256.key.pub
```

🚀 视频地址
------

[](#-视频地址)

> 不懂的同学可以了解一下视频，会有详细的说明哦

- 如何使用 JWT 认证插件：
- 如何使用 JWT 认证插件（算法篇）：

安全性
---

[](#安全性)

### 概念

[](#概念)

有许多方法可以处理安全性、身份认证和授权等问题。而且这通常是一个复杂而「困难」的话题。在许多框架和系统中，仅处理安全性和身份认证就会花费大量的精力和代码（在许多情况下，可能占编写的所有代码的 50％ 或更多）。

Jwt 可帮助你以标准的方式轻松、快速地处理安全性，而无需研究和学习所有的安全规范。

### 场景

[](#场景)

假设您在某个域中拥有后端API。并且您在另一个域或同一域的不同路径（或移动应用程序）中有一个前端。并且您希望有一种方法让前端使用用户名和密码与后端进行身份验证。我们可以使用OAuth2通过JWT来构建它。

### 认证流程

[](#认证流程)

- 用户在前端输入`username`和`password`，然后点击Enter。
- 前端（在用户的浏览器中运行）发送一个`username`和`password`我们的API在一个特定的URL（以申报`tokenUrl="token"`）。
- API 检查username和password，并用“令牌”响应（我们还没有实现任何这些）。“令牌”只是一个包含一些内容的字符串，我们稍后可以使用它来验证此用户。通常，令牌设置为在一段时间后过期。因此，用户稍后将不得不再次登录。如果代币被盗，风险就小了。它不像一个永久有效的密钥（在大多数情况下）。 前端将该令牌临时存储在某处。
- 用户单击前端以转到前端 Web 应用程序的另一部分。
- 前端需要从 API 获取更多数据。但它需要对该特定端点进行身份验证。因此，为了使用我们的 API 进行身份验证，它会发送`Authorization`一个值为`Bearer`加上令牌的标头。如果令牌包含`foobar`，则`Authorization`标头的内容将为：`Bearer foobar`。`注意：中间是有个空格`。

认证&amp;授权流程
-----------

[](#认证授权流程)

[![image](https://user-images.githubusercontent.com/14959876/159104533-f51f0a57-e085-44ab-84d7-363a4bb1eda9.png)](https://user-images.githubusercontent.com/14959876/159104533-f51f0a57-e085-44ab-84d7-363a4bb1eda9.png)

签名流程
----

[](#签名流程)

1. 用户使用用户名和口令到认证服务器上请求认证。
2. 认证服务器验证用户名和口令后，以服务器端生成JWT Token，这个token的生成过程如下：
    - 认证服务器还会生成一个 Secret Key（密钥）
    - 对JWT Header和JWT Payload分别求Base64。在Payload可能包括了用户的抽象ID和的过期时间。
    - 用密钥对JWT签名 `HMAC-SHA256(SecretKey, Base64UrlEncode(JWT-Header)+'.'+Base64UrlEncode(JWT-Payload))`
3. 然后把 `base64(header).base64(payload).signature` 作为 JWT token返回客户端。
4. 客户端使用JWT Token向应用服务器发送相关的请求。这个JWT Token就像一个临时用户权证一样。

###  Health Score

59

—

FairBetter than 99% of packages

Maintenance82

Actively maintained with recent releases

Popularity45

Moderate usage in the ecosystem

Community32

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 87.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~31 days

Recently: every ~45 days

Total

48

Last Release

82d ago

Major Versions

v0.0.3 → v1.0.02022-02-24

PHP version history (2 changes)v0.0.1PHP &gt;=7.4

v1.2.4PHP ^7.1||^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/b0042e0b68ff6a731ef382a03eecd211736c2d619acc55b2b326988085f72bfb?d=identicon)[Tinywan](/maintainers/Tinywan)

---

Top Contributors

[![Tinywan](https://avatars.githubusercontent.com/u/14959876?v=4)](https://github.com/Tinywan "Tinywan (115 commits)")[![houaiai](https://avatars.githubusercontent.com/u/25687708?v=4)](https://github.com/houaiai "houaiai (4 commits)")[![kylin987](https://avatars.githubusercontent.com/u/26080774?v=4)](https://github.com/kylin987 "kylin987 (2 commits)")[![Rodots](https://avatars.githubusercontent.com/u/50762123?v=4)](https://github.com/Rodots "Rodots (2 commits)")[![youziyouzishu](https://avatars.githubusercontent.com/u/48539892?v=4)](https://github.com/youziyouzishu "youziyouzishu (2 commits)")[![tx9991](https://avatars.githubusercontent.com/u/30764689?v=4)](https://github.com/tx9991 "tx9991 (1 commits)")[![kyour-cn](https://avatars.githubusercontent.com/u/38110013?v=4)](https://github.com/kyour-cn "kyour-cn (1 commits)")[![je8903042009](https://avatars.githubusercontent.com/u/44671978?v=4)](https://github.com/je8903042009 "je8903042009 (1 commits)")[![jeis4n](https://avatars.githubusercontent.com/u/112980298?v=4)](https://github.com/jeis4n "jeis4n (1 commits)")[![EagriSiol](https://avatars.githubusercontent.com/u/36779913?v=4)](https://github.com/EagriSiol "EagriSiol (1 commits)")[![Microwan0928](https://avatars.githubusercontent.com/u/32860272?v=4)](https://github.com/Microwan0928 "Microwan0928 (1 commits)")

---

Tags

jwtjwt-authenticationjwt-tokenphpphp-librarytinywanwebmanworkerman

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tinywan-jwt/health.svg)

```
[![Health](https://phpackages.com/badges/tinywan-jwt/health.svg)](https://phpackages.com/packages/tinywan-jwt)
```

###  Alternatives

[google/auth

Google Auth Library for PHP

1.4k272.7M162](/packages/google-auth)[thenetworg/oauth2-azure

Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2509.6M48](/packages/thenetworg-oauth2-azure)[stevenmaguire/oauth2-keycloak

Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2275.9M27](/packages/stevenmaguire-oauth2-keycloak)[robsontenorio/laravel-keycloak-guard

🔑 Simple Keycloak Guard for Laravel

5161.1M3](/packages/robsontenorio-laravel-keycloak-guard)[patrickbussmann/oauth2-apple

Sign in with Apple OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1132.5M6](/packages/patrickbussmann-oauth2-apple)[wp-graphql/wp-graphql-jwt-authentication

JWT Authentication for WPGraphQL

361118.4k1](/packages/wp-graphql-wp-graphql-jwt-authentication)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
