diff --git a/app/Middleware/Auth/ApiMiddleware.php b/app/Middleware/Auth/ApiMiddleware.php new file mode 100644 index 0000000..de2a720 --- /dev/null +++ b/app/Middleware/Auth/ApiMiddleware.php @@ -0,0 +1,99 @@ +container = $container; + $this->response = $response; + $this->request = $request; + } + + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + + if (env('APP_ENV') == 'dev') { + return $handler->handle($request); + } + + // 签名校验 + + # 获取参数 + $params = $this->request->all(); + + # 必须参数,签名、时间戳、随机数 + if (!(isset($params['sign'])&&isset($params['timestamp'])&&isset($params['rand']))) { + + $content = [ + "status" => 'ok', + "code" => 9001, + "result" => [], + "message" => '接口验签失败:缺少参数' + ]; + + return $this->response->json($content); + } + + if (!$this->checkSign($params)) { + + $content = [ + "status" => 'ok', + "code" => 9002, + "result" => [], + "message" => '接口验签失败:签名错误或已失效' + ]; + + return $this->response->json($content); + } + + return $handler->handle($request); + } + + private function checkSign($params) + { + $sign = $params['sign']; + unset($params['sign']); + $timestamp = $params['timestamp']; + + if (empty($sign) || ($timestamp+config('autoload.auth.api.sign.expire')) < time()) { + return false; + } + + ksort($params); + $params = http_build_query($params); + + return $sign == $this->signature($params); + } + + private function signature($http_query) + { + return sha1(md5($http_query).config('autoload.auth.api.sign.secret_key')); + } +} \ No newline at end of file diff --git a/config/autoload/auth.php b/config/autoload/auth.php new file mode 100644 index 0000000..89bafcf --- /dev/null +++ b/config/autoload/auth.php @@ -0,0 +1,14 @@ + [ + 'sign' => [ + 'secret_key' => 'lanzu@123', + 'expire_time' => 200 + ] + ], +]; \ No newline at end of file diff --git a/config/autoload/middlewares.php b/config/autoload/middlewares.php index 81b1887..8a27adf 100644 --- a/config/autoload/middlewares.php +++ b/config/autoload/middlewares.php @@ -11,5 +11,6 @@ declare(strict_types=1); */ return [ 'http' => [ + \App\Middleware\Auth\ApiMiddleware::class ], ];