PHPackages                             leezj/laravel-jwt-api - 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. [API Development](/categories/api)
4. /
5. leezj/laravel-jwt-api

ActiveLibrary[API Development](/categories/api)

leezj/laravel-jwt-api
=====================

Laravel-JWT-API

1.2.0(5y ago)082MITPHPPHP &gt;=7.1

Since Nov 16Pushed 5y ago1 watchersCompare

[ Source](https://github.com/joey2017/laravel-jwt-api)[ Packagist](https://packagist.org/packages/leezj/laravel-jwt-api)[ RSS](/packages/leezj-laravel-jwt-api/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (1)Versions (13)Used By (0)

[![Laravel-JWT-API开发包](https://camo.githubusercontent.com/07b13f6cda35d2bca4be66f4fcffe2f775fb76931e0e0b914b56f9cccfc2ea1e/68747470733a2f2f73322e617831782e636f6d2f323031392f30332f32372f41616a6c67782e6d642e706e67)](https://camo.githubusercontent.com/07b13f6cda35d2bca4be66f4fcffe2f775fb76931e0e0b914b56f9cccfc2ea1e/68747470733a2f2f73322e617831782e636f6d2f323031392f30332f32372f41616a6c67782e6d642e706e67)

[![Software license](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)[![Build](https://camo.githubusercontent.com/6b62a0378e5cb0654bbc8855ba38e66fa8680b599b549c5a42d9261d6bebedc1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275696c642d70617373696e672d302e737667)](https://camo.githubusercontent.com/6b62a0378e5cb0654bbc8855ba38e66fa8680b599b549c5a42d9261d6bebedc1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275696c642d70617373696e672d302e737667)[![dependencies](https://camo.githubusercontent.com/af5f885b1dd64b141209e1c1c9c7149368cc56c5bd7922b1a17e367c89dfe197/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f646570656e64656e636965732d7570253230746f253230646174652d627269676874677265656e2e737667)](https://camo.githubusercontent.com/af5f885b1dd64b141209e1c1c9c7149368cc56c5bd7922b1a17e367c89dfe197/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f646570656e64656e636965732d7570253230746f253230646174652d627269676874677265656e2e737667)[![stars](https://camo.githubusercontent.com/9d22a4a4684d6ce1644734356fcba3424a5c005fbb0d10773040d29969a94b39/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f73746172732d2545322539382538352545322539382538352545322539382538352545322539382538352545322539382538352d627269676874677265656e2e737667)](https://camo.githubusercontent.com/9d22a4a4684d6ce1644734356fcba3424a5c005fbb0d10773040d29969a94b39/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f73746172732d2545322539382538352545322539382538352545322539382538352545322539382538352545322539382538352d627269676874677265656e2e737667)[![php](https://camo.githubusercontent.com/d19bb0d74be3b9fd25af173c54777d94c24a7c0fc7e6532755774e84fd637bfa/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230372e312d626c756576696f6c65742e737667)](https://camo.githubusercontent.com/d19bb0d74be3b9fd25af173c54777d94c24a7c0fc7e6532755774e84fd637bfa/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230372e312d626c756576696f6c65742e737667)[![mysql](https://camo.githubusercontent.com/b539160ebeab7fe11e4b4574083142d8ba7fa542990a493d572c80998ace88db/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d7973716c2d253345253344253230352e352d696e666f726d6174696f6e616c2e737667)](https://camo.githubusercontent.com/b539160ebeab7fe11e4b4574083142d8ba7fa542990a493d572c80998ace88db/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d7973716c2d253345253344253230352e352d696e666f726d6174696f6e616c2e737667)[![laravel](https://camo.githubusercontent.com/16b169678449c7e752316132fab563080d1e56c2c3902deef45a2c9a7d57b2b4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d253345253344253230352e352d7265642e737667)](https://camo.githubusercontent.com/16b169678449c7e752316132fab563080d1e56c2c3902deef45a2c9a7d57b2b4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d253345253344253230352e352d7265642e737667)

Laravel-JWT-API开发包
==================

[](#laravel-jwt-api开发包)

*\[将Laravel框架进行一些配置处理，让其在开发API时更得心应手\]*

---

背景
--

[](#背景)

随着前后端完全分离，`PHP`也基本告别了`view`模板嵌套开发，转而专门写资源接口。`Laravel`是PHP框架中`最优雅的框架`，国内也越来越多人告别`ThinkPHP`选择了`Laravel`。Laravel框架本身对`API`有支持，但是感觉再工作中还是需要再做一些处理。`Lumen`用起来不顺手，有些包不能很好地支持。所以，将Laravel框架进行一些配置处理，让其在开发API时更得心应手。

---

环境和程序要求
-------

[](#环境和程序要求)

程序版本PHP`>= 7.1`MySQL`>= 5.5`laravel/laravel`>= 5.5`tymon/jwt-auth`1.0.0-rc.4.*`---

功能
--

[](#功能)

> - 统一Response响应处理
> - Laravel Api-Resource资源 分页返回统一响应
> - jwt-auth用户认证与无感知自动刷新
> - 单一设备登陆
> - 异常捕获，http状态码统一

---

安装
--

[](#安装)

- 通过composer，这是推荐的方式，可以使用composer.json 声明依赖，或者直接运行下面的命令。

```
 composer require leezj/laravel-jwt-api
```

- 放入composer.json文件中

```
"require": {
    "Leezj/laravel-jwt-api": "*"
}
```

然后运行

```
composer update
```

---

使用
--

[](#使用)

添加服务提供商

```
'providers' => [
    ...
    Leezj\LaravelApi\ApiServiceProvider::class,
]

```

2.发布配置文件

```
php artisan vendor:publish --provider="Leezj\LaravelApi\ApiServiceProvider"
```

> 此命令会在 config 目录下生成一个 `leezj.php` 配置文件，你可以在此进行自定义配置。
>
> - `response` 是配置资源响应格式
> - `exception` 是配置需要拦截的异常

### 1.统一Response响应处理

[](#1统一response响应处理)

> 所有请求都返回`json`格式,返回字段格式也是统一标准化 格式如下

```
{
  "message": "string",
  "code": xxx,
  "data": [] // 数组或对象
}

```

> 默认`success`返回的`http`状态码是`200`，`error`返回的状态码是`400`

1. 新建Api控制器基类 或者 继承Api控制器基类
2. `use ApiResponse;`
3. 代码使用

```
// 成功返回 第一个参数可接受item和resource
return $this->success($user,$meta);
// 只返回信息无内容
return $this->setHttpCode(201)->message('用户创建成功...');
// 错误返回
return $this->error('用户登录失败',401);
```

4.返回

```
// 成功完整返回
{
    "message": "Success",
    "code": 200,
    "data": [
        {
            "id": 1,
            "name": "jack"
        },
        {
            "id": 2,
            "name": "tony"
        }
    ],
    "meta": {
        "page_info": {
            "current_page": 1,
            "last_page": 20,
            "per_page": 15,
            "total": 500
        }
    }
}

// 错误返回
{
  "message": "Error",
  "code": 401,
  "data": []
}

```

### 2.Api-Resource资源 分页返回统一响应

[](#2api-resource资源-分页返回统一响应)

1. 在Resource资源文件中引入
2. `use PaginatedCollection;`示例代码

```
namespace App\Http\Resources;

use App\Traits\PaginatedCollection;
use Illuminate\Http\Resources\Json\JsonResource;

class Company extends JsonResource
{
    use PaginatedCollection;

}
```

3.使用示例

```
 return \App\Http\Resources\Company::collection($company);
```

4.返回同上成功返回示例

> 关于分页返回的字段，你可以在配置文件中指定：`config('leezj.response.page_info')`默认是`current_page`、`last_page`、`per_page`、`total` 4个

### 3.异常自定义处理

[](#3异常自定义处理)

1.修改 `app/Exceptions` 目录下的 `Handler.php` 文件

```
use LaravelApi\Response\ExceptionReport;

public function render($request, Exception $exception)
{
    // 将方法拦截到自己的ExceptionReport
    $reporter = ExceptionReport::make($exception);

    if ($reporter->shouldReturn()) {
        return $reporter->report();
    }

    return parent::render($request, $exception);
}
```

2.可自定义错误的异常设置 配置文件`leezj.php`，在`exception.do_report`加入需要拦截的异常，示例：

```
'exception' => [
    'do_report'=>[
        UnauthorizedHttpException::class => [
            'msg' => '未授权或Token签名失效', // message显示的消息
            'http_code' => 401 // http状态码，不填则获取异常类的状态码，如果获取不到则500
        ],
        AuthenticationException::class => [
            'msg' => '未授权或Token签名失效',
            'http_code' => 401 // 响应体中code代码,可用于业务标识
        ]
    ]
]

```

### 4.jwt-auth

[](#4jwt-auth)

> jwt-auth的详细介绍分析可以看 [JWT超详细分析](https://learnku.com/articles/17883) 这篇文章，具体使用可以看 [JWT完整使用详解](https://learnku.com/articles/10885/full-use-of-jwt) 这篇文章。

1.打开 config 目录下的 app.php文件，添加服务提供者

```
'providers' => [
    ...
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

```

2.发布配置文件

```
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
```

> 此命令会在 config 目录下生成一个 `jwt.php` 配置文件，你可以在此进行自定义配置。

3.生成密钥

```
php artisan jwt:secret
```

> 此命令会在你的 `.env` 文件中新增一行 `JWT_SECRET=secret`。以此来作为加密时使用的秘钥。

4.配置 Auth guard. 打开 `config` 目录下的 `auth.php`文件，修改api的驱动为`jwt`。这样，我们就能让api的用户认证变成使用jwt。

```
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

```

5.更改 User Model 如果需要使用`jwt-auth`作为用户认证，我们需要对我们的 User模型进行一点小小的改变，实现一个接口，变更后的`User`模型如下

```
class User extends Authenticatable implements JWTSubject
{
    ...

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    public function getJWTCustomClaims()
    {
        return [];
    }
}
```

### 5.自动刷新用户认证 &amp;&amp; 单一设备登陆

[](#5自动刷新用户认证--单一设备登陆)

为了保证安全性，用户的token都会定期自动刷新为全新的，用旧的token请求不会通过。当刷新了token，能否不要重新登录，就算重新登录也是一周甚至一个月之后呢？给用户一种无感知的体验。

1.增加中间件别名 打开 app/Http 目录下的 Kernel.php 文件，添加如下一行

```
protected $routeMiddleware = [
    ......
    'api.refresh'=>\Leezj\LaravelApi\Middleware\RefreshTokenMiddleware::class,
];

```

2.路由器修改

```
Route::middleware('api.refresh:api')->group(function () {
    // api看守器登陆授权
    ...
});

```

3.登录控制器引入`LoginActionTrait`

```
class LoginController extends Controller
{
    use LoginActionTrait;
    ...
}

```

4.原理

- 自动刷新用户认证

> - 捕获到了 token 过期所抛出的 TokenExpiredException异常
> - 刷新用户的 token `$token = $this->auth->refresh();`
> - 使用一次性登录以保证此次请求的成功 注意需要设置config jwt宽限时间
> - `Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);`
> - 在响应头中返回新的 token `$this->setAuthenticationHeader($next($request), $token);`

- 单一设备登陆

> - 我们将`token`都存到**缓存中**。在登陆接口，获取到`last_token`里的值，将其加入黑名单。
> - 这样，只要我们无论在哪里登陆，之前的`token`一定会被拉黑失效，必须重新登陆，我们的目的也就达到了。

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~46 days

Recently: every ~121 days

Total

12

Last Release

1858d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/61181de62b9231e06c4057c90074e93fa33576b381e9e63d0c47f96aad959a3c?d=identicon)[joey2017](/maintainers/joey2017)

---

Top Contributors

[![zongerli](https://avatars.githubusercontent.com/u/171768495?v=4)](https://github.com/zongerli "zongerli (6 commits)")

---

Tags

apilaravel

### Embed Badge

![Health badge](/badges/leezj-laravel-jwt-api/health.svg)

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

PHPackages © 2026

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