PHPackages                             chumoe/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. chumoe/jwt

ActiveThink-extend[Authentication &amp; Authorization](/categories/authentication)

chumoe/jwt
==========

JSON Web Token (JWT) for ThinkPHP6 plugin

v1.0.7(4y ago)125MITPHPPHP &gt;=7.2.5

Since Apr 19Pushed 4y agoCompare

[ Source](https://github.com/chumoe/think-jwt)[ Packagist](https://packagist.org/packages/chumoe/jwt)[ RSS](/packages/chumoe-jwt/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (7)Dependencies (1)Versions (8)Used By (0)

JSON Web Token (JWT) for ThinkPHP6 plugin
=========================================

[](#json-web-token-jwt-for-thinkphp6-plugin)

[![Latest Stable Version](https://camo.githubusercontent.com/67ba4b06c41f36d68cda9088c284be99ff564b90c9ee8c39452e7f3d8791fa6c/687474703a2f2f706f7365722e707567782e6f72672f6368756d6f652f6a77742f76)](https://packagist.org/packages/chumoe/jwt)[![Total Downloads](https://camo.githubusercontent.com/dd8e7afc1df3e59e5300a71a892996ea68a18ba7158fdbf4ea5f65ca79d4c456/687474703a2f2f706f7365722e707567782e6f72672f6368756d6f652f6a77742f646f776e6c6f616473)](https://packagist.org/packages/chumoe/jwt)[![Latest Unstable Version](https://camo.githubusercontent.com/2524b7eea9ccfae5b0de00f56a7180b4f79deee218b63ca3d5900cdafda80058/687474703a2f2f706f7365722e707567782e6f72672f6368756d6f652f6a77742f762f756e737461626c65)](https://packagist.org/packages/chumoe/jwt)[![License](https://camo.githubusercontent.com/c9a4212af82a890f3f6b76075c08c5ea9844256875c505b54d4f03d25f172817/687474703a2f2f706f7365722e707567782e6f72672f6368756d6f652f6a77742f6c6963656e7365)](https://packagist.org/packages/chumoe/jwt)[![PHP Version Require](https://camo.githubusercontent.com/68551dddb3d1326501d2fb5a67793519e129896d32e30be7ff5988e373de99a4/687474703a2f2f706f7365722e707567782e6f72672f6368756d6f652f6a77742f726571756972652f706870)](https://packagist.org/packages/chumoe/jwt)

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

JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息，以便于从资源服务器获取资源，也可以增加一些额外的其它业务逻辑所必须的声明信息，该token也可直接被用于认证，也可被加密。

认证&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(SecertKey, Base64UrlEncode(JWT-Header)+'.'+Base64UrlEncode(JWT-Payload))`
3. 然后把 base64(header).base64(payload).signature 作为 JWT token返回客户端。
4. 客户端使用JWT Token向应用服务器发送相关的请求。这个JWT Token就像一个临时用户权证一样。

安装
--

[](#安装)

```
composer require chumoe/jwt
```

使用
--

[](#使用)

### 生成令牌

[](#生成令牌)

```
use chumoe\jwt\JwtToken;

$user = [
    'uid'  => 2022,
    'name'  => 'chumoe',
    'email' => 'chumoe@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刷新凭证（访问凭证过期使用 ）XXXXXXXXXXXXXXXXXXX支持函数列表
------

[](#支持函数列表)

> 1、获取当前`uid`

```
$uid = JwtToken::getCurrentId();
```

> 2、获取所有字段

```
$email = JwtToken::getExtend();
```

> 3、获取自定义字段

```
$email = JwtToken::getExtendVal('email');
```

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

```
$refreshToken = JwtToken::refreshToken();
```

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

```
$exp = JwtToken::getTokenExp();
```

签名算法
----

[](#签名算法)

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

**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
```

### RS512

[](#rs512-1)

```
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
```

安全性
---

[](#安全性)

### 概念

[](#概念)

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

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 64.3% 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 ~0 days

Total

7

Last Release

1487d ago

PHP version history (2 changes)v1.0.0PHP &gt;=7.1.0

v1.0.3PHP &gt;=7.2.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/6c7ed1473b7a6a10e7e9b376450d1bdd81c260ffa1a985269658ee7dc8662cc2?d=identicon)[chumoe](/maintainers/chumoe)

---

Top Contributors

[![Tinywan](https://avatars.githubusercontent.com/u/14959876?v=4)](https://github.com/Tinywan "Tinywan (45 commits)")[![chumoe](https://avatars.githubusercontent.com/u/50536453?v=4)](https://github.com/chumoe "chumoe (25 commits)")

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/chumoe-jwt/health.svg)](https://phpackages.com/packages/chumoe-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)
