// +---------------------------------------------------------------------- namespace app\common\middleware; use app\Request; use crmeb\exceptions\AuthException; use think\exception\ValidateException; use think\Response; use Throwable; class SignMiddleware extends BaseMiddleware { /** * @param Request $request * @throws Throwable * @author xaboy * @day 2020-04-10 */ public function before(Request $request) { try { $appid = $request->header('appid'); $timestamp = $request->header('timestamp'); $sign = $request->header('sign'); // 中台系统secret $appSecret = 'St@tF!8r@fgjCu88fJB9eo4PTRHxsntC'; $this->verifySign(['appid'=>$appid,'timestamp'=>$timestamp,'sign'=>$sign], $appSecret); } catch (AuthException $e) { $eArray = ($e->getResponse())->getData(); throw new AuthException($eArray['message'] ?? '非法签名'); return; } catch (Throwable $e) { throw new AuthException('非法请求'); return; } } public function after(Response $response) { } private function makeSign($data, $appSecret) { ksort($data); $string = ""; foreach ($data as $k => $v) { if ($k == "sign" || is_array($v)) { continue; } $string .= $k . "=" . $v . "&"; } $string = trim($string, "&"); $string = $string . "&key=" . $appSecret; $string = md5(md5($string)); return strtolower($string); } private function verifySign($data, $appSecret) { // 验证请求, 10秒钟失效 if (time() - ($data['timestamp'] ?? 0) > 10) { throw new AuthException('签名已失效'); } // 比对签名 $clientSign = $data['sign'] ?? ''; $serverSign = $this->makeSign($data, $appSecret); if ($clientSign != $serverSign) { throw new AuthException('签名校验失败'); } } }