laravel11: 给接口增加签名验证

一,添加controller/中间件/路由

1,添加中间件

liuhongdi@lhdpc:/web/api$ php artisan make:middleware ApiSign

   INFO  Middleware [app/Http/Middleware/ApiSign.php] created successfully. 

2,添加路由:

在routes/api.php文件中

Route::controller(VirtualController::class)->group(function () {
    Route::get('/virtual/info', 'info')->middleware([ApiSign::class]);
});

二,代码

1,中间件:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\extend\result\Result;


class ApiSign
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $post_data = $request->all();
        if (!$this->getSign($post_data)) {
            return Result::ErrorCode(1,'接口签名验证错误');
        } else {
            return $next($request);
        }
    }

    private function getSign(array $params): bool
    {
        //从配置文件中得到secret
        $app_secret = config("client.my_secret");
        if (empty($params)) {
            return false;
        }
        if (!isset($params['sign'])) {
            return false;
        }
        $sign = $params['sign'];
        unset($params['sign']);
        ksort($params);
        $strParams = [];
        foreach ($params as $k => $v) {
            if (preg_match('/\/\S+\/\S+/', $k) != 0 || preg_match('/\S+\/\S+/', $k) != 0) {
                continue;
            }
            $strParams[] = "$k_$v";
        }
        $inputStr = implode('&', $strParams)."&secret_".$app_secret;
        $creSign = md5($inputStr);
        return $creSign !== $sign  ? false : true ;
    }

}

 

2,controller:

class VirtualController extends Controller
{
    //测试接口签名验证
    public function info(Request $request) {
        $data = ['name'=>'老张'];
        return Result::Success($data);
    }
}

 

三,测试效果

用postman提交参数:

 

posted @ 2024-07-17 17:27  刘宏缔的架构森林  阅读(85)  评论(0编辑  收藏  举报