laravel框架基础建设:接口验签封装

我们提供接口给到外部(后端)调用的时候,为保证接口安全,需要在接口中进行验签校验(目前验签规则很多种,具体根据每个公司而定)
1.创建中间件:php artisan make:middleware ApiCheckSign.php,Kernel.php添加中间件
2.实现



namespace App\Http\Middleware;

use App\common\SystemCode;
use App\common\SystemMessage;
use App\common\tools\response\RespResult;
use Closure;
use Illuminate\Http\Request;

class ApiCheckSign
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $params = $request->all();
        $token = $request->header("token");
        $timeStamp = $request->header("timestamp");
        $appId = $request->header("appId");
        if (empty($token) || empty($timeStamp) || empty($appId)){
            throw new \Exception(SystemMessage::SYSTEM_ERROR_API_PARAMS_NULL,SystemCode::SYSTEM_ERROR_API_PARAMS_NULL);//测试抛出异常
        }
        ksort($params);//将参数进行排序
        $paramsJson = json_encode($params,256);
        $appSecrect = function () use ($appId){//通过appid动态获取相关appSecrect
            $data = [//模拟通过数据库用appid获取appSecrect
                "1"=>"0a0ed22b8d8e5de466fca2e2e6d33137",
                "2"=>"0a0ed22b8d8e5de466fca2e2e6d33137",
                "3"=>"0a0ed22b8d8e5de466fca2e2e6d33137",
                "4"=>"0a0ed22b8d8e5de466fca2e2e6d33137",
                "5"=>"0a0ed22b8d8e5de466fca2e2e6d33137",
            ];
            $appSecrect = isset($data[$appId])?$data[$appId]:'';
            if ($appSecrect === ''){
                throw new \Exception(SystemMessage::SYSTEM_ERROR_APPID,SystemCode::SYSTEM_ERROR_APPID);//测试抛出异常
            }
            return $data[$appId];
        };
        $checkToken = md5($appId.$appSecrect().$paramsJson.$timeStamp);//签名
        if($token != $checkToken){
            return RespResult::result(SystemCode::SYSTEM_ERROR_TOKEN_VERIF_FAIL,SystemMessage::SYSTEM_ERROR_TOKEN_VERIF_FAIL,[]);
        }
        //验签通过
        return $next($request);
    }
}

3.使用方法

Route::patch('demo/emailFile',[\App\Http\Controllers\DemoController::class,'emailFile'])->middleware("Validate")->middleware("ApiCheckSign");

你可能感兴趣的:(laravel,laravel,php,开发语言)