前言
签名是api开发的必不可缺少的一环,
实操:
一, 创建中间件php文件
有两种方法,
方法一,是由手动创建 在目录App/Http/Middleware
中创建一个自定义中间件 叫做ApiSgin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use App\Models\Task as TaskModels;
class ApiSgin
{
public function handle(Request $request, Closure $next)
{
$input = $request->all();
//签名验证具体实现略
//。。。
if ($input['sgin'] != '004e5444e9262496921566aea68784a8') {
return failed('签名错误');
//failed自定义封装助手行数 类似 return '{"code":-1,"msg":"error"}';
}
//中间件执行代码没有问题想要继续深度执行业务,
//使用 $request 调用 $next 回调
return $next($request);
}
}
方法二,使用laravel自带的artisan
工具执行一键创建命令
php artisan make:middleware ApiSgin
二,设置路由中间件路径
可以设置多个地方
在App/Http/Kernel.php 中
可以填写在
protected $middleware = []; //注册全局中间件
protected $middlewareGrops=[]; //设置中间件组
protected $routeMiddleware = []; //中间件分配给路由
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [],
'api' => [],
'sgin' => [
\App\Http\Middleware\ApiSgin::class,
]
];
//或者在路由设置中间映射
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
//sgin签名验证
'sgin'=> \App\Http\Middleware\ApiSgin::class,
];
三,路由中注册中间件
在 Routes/api.php
//需要验证签名
Route::middleware(['sgin'])->group(function () {
//....
}
有多种设置方式。
在laravel手册中介绍的好多种方式,我觉得路由组使用同一个中间件很方便,当然要根据实际业务来使用不同方式的中间件。
评论