From 8fe78e0c1b51bfda751285385abe27c8bab506f5 Mon Sep 17 00:00:00 2001 From: weigang Date: Sat, 18 Jul 2020 19:06:08 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=B8=AD=E9=97=B4=E4=BB=B6?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E6=8E=A5=E5=8F=A3=E8=AF=B7=E6=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Middleware/Auth/ApiMiddleware.php | 99 +++++++++++++++++++++++++++ config/autoload/auth.php | 14 ++++ config/autoload/middlewares.php | 1 + 3 files changed, 114 insertions(+) create mode 100644 app/Middleware/Auth/ApiMiddleware.php create mode 100644 config/autoload/auth.php 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 ], ];