PHPackages                             tinywan/think-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/think-jwt

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

tinywan/think-jwt
=================

JSON Web Token (JWT) for Think plugin

v1.5.2(9mo ago)121.8k↑50%6[1 issues](https://github.com/Tinywan/think-jwt/issues)1MITPHPPHP ^7.1||^8.0CI failing

Since Sep 17Pushed 9mo ago1 watchersCompare

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

READMEChangelog (5)Dependencies (2)Versions (19)Used By (1)

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

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

[![Latest Stable Version](https://camo.githubusercontent.com/76c162690f6c4b1f1f8c490ac92f6a151382c6535405e788774732ef04069bf5/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d6a77742f76)](https://packagist.org/packages/tinywan/think-jwt)[![Total Downloads](https://camo.githubusercontent.com/cbe68660d20db857946c6b79c913fe36d945091d8bc6d958b41ef6e41f7d6c9e/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d6a77742f646f776e6c6f616473)](https://packagist.org/packages/tinywan/think-jwt)[![Daily Downloads](https://camo.githubusercontent.com/b91dc25685ffdca57a9bfeb3ca712e99a6295c388dd04db491b2edbb0f18d19a/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d6a77742f642f6461696c79)](https://packagist.org/packages/tinywan/think-jwt)[![Latest Unstable Version](https://camo.githubusercontent.com/bc3acd28a6d921a1893bec2377cdd0f4524e55884311fd8e2a40e0b562f02f5a/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d6a77742f762f756e737461626c65)](https://packagist.org/packages/tinywan/think-jwt)[![License](https://camo.githubusercontent.com/0360511678c6f9711b5fb1a8865f2fa1c5c6b8375ce01348f78d5512f0953cd2/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d6a77742f6c6963656e7365)](https://packagist.org/packages/tinywan/think-jwt)[![PHP Version Require](https://camo.githubusercontent.com/8565d4308b2bf41604d4c406326879fddabc9686ff12cc8483271dd262b00a22/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d6a77742f726571756972652f706870)](https://packagist.org/packages/tinywan/think-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 tinywan/think-jwt

```

使用
--

[](#使用)

### 生成令牌

[](#生成令牌)

```
$user = [
    'uid'  => 2022,
    'name'  => 'Tinywan',
    'email' => 'Tinywan@163.com'
];
$token = \tinywan\JWT::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 = \tinywan\JWT::getCurrentId();
```

> 2、获取所有字段

```
$email = \tinywan\JWT::getExtend();
```

> 3、获取自定义字段

```
$email = \tinywan\JWT::getExtendVal('email');
```

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

```
$refreshToken = \tinywan\JWT::refreshToken();
```

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

```
$exp = \tinywan\JWT::getTokenExp();
```

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

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

> 7、获取当前用户信息（模型）

```
$user = \tinywan\JWT::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();
}
```

签名算法
----

[](#签名算法)

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

43

—

FairBetter than 91% of packages

Maintenance56

Moderate activity, may be stable

Popularity28

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 84.4% 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 ~62 days

Recently: every ~216 days

Total

18

Last Release

277d ago

### 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 (27 commits)")[![fdcwh](https://avatars.githubusercontent.com/u/8169676?v=4)](https://github.com/fdcwh "fdcwh (3 commits)")[![licyril](https://avatars.githubusercontent.com/u/23089397?v=4)](https://github.com/licyril "licyril (1 commits)")[![zhigge](https://avatars.githubusercontent.com/u/17754665?v=4)](https://github.com/zhigge "zhigge (1 commits)")

### Embed Badge

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

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