AuthRequestMiddleWare.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. declare (strict_types=1);
  3. namespace app\api\middleware;
  4. use app\Request;
  5. use interfaces\MiddlewareInterface;
  6. use think\facade\Config;
  7. use think\Response;
  8. /**
  9. * 跨域中间件
  10. * Class AuthRequestMiddleWare
  11. * @package app\middleware
  12. */
  13. class AuthRequestMiddleWare implements MiddlewareInterface
  14. {
  15. /**
  16. * 允许跨域的域名
  17. * @var string
  18. */
  19. protected $cookieDomain;
  20. /**
  21. * @param Request $request
  22. * @param \Closure $next
  23. * @return Response
  24. */
  25. public function handle (Request $request, \Closure $next)
  26. {
  27. $this->cookieDomain = Config::get('cookie.domain', '');
  28. $header = Config::get('cookie.header');
  29. $origin = $request->header('origin');
  30. if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain)))
  31. $header['Access-Control-Allow-Origin'] = $origin;
  32. if ($request->method(true) == 'OPTIONS') {
  33. $response = Response::create('ok')->code(200)->header($header);
  34. } else {
  35. $response = $next($request)->header($header);
  36. }
  37. $request->filter(['strip_tags', 'addslashes', 'trim']);
  38. // $c = $request->controller();
  39. // $a = $request->action();
  40. // $str = trim($c . '/' . $a);
  41. // $auth_api = ['v1.Withdrawal/executeAdmin', 'v1.Pay/adminPay'];
  42. // if (in_array($str, $auth_api) && false) { // 需要检测签名
  43. // $sign = $request->header('sign');
  44. // if (empty($sign))
  45. // return app('json')->json_error('签名不存在');
  46. // if ($this->createApiSign($request->param()) != $sign)
  47. // return app('json')->json_error('签名验证失败');
  48. // }
  49. return $response;
  50. }
  51. /**
  52. * 获取接口签名
  53. * @param array $params
  54. * @return string
  55. */
  56. // protected function createApiSign (array $params): string
  57. // {
  58. // unset($params['sign']);
  59. //
  60. // //签名步骤一:按字典序排序数组参数
  61. // ksort($params);
  62. // $string = $this->toUrlParams($params);
  63. // //签名步骤二:在string后加入KEY
  64. // $app_key = env('app.app_key');
  65. // $string = trim($string . "&key=" . $app_key);
  66. // //签名步骤三:MD5加密
  67. // $string = md5($string);
  68. // //签名步骤四:所有字符转为大写
  69. // $result = strtoupper($string);
  70. // return $result;
  71. // }
  72. /**
  73. * 将参数拼接为url: key=value&key=value
  74. * @param $params
  75. * @return string
  76. */
  77. protected function toUrlParams ($params)
  78. {
  79. $string = '';
  80. if (!empty($params)) {
  81. $array = array();
  82. foreach ($params as $key => $value) {
  83. $array[] = $key . '=' . $value;
  84. }
  85. $string = implode("&", $array);
  86. }
  87. return $string;
  88. }
  89. }