AllowCrossDomain.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\common\middleware;
  13. use Closure;
  14. use think\Request;
  15. use think\Response;
  16. use think\facade\Config;
  17. /**
  18. * 跨域请求支持
  19. * 安全起见,只支持了配置中的域名
  20. */
  21. class AllowCrossDomain
  22. {
  23. protected $header = [
  24. 'Access-Control-Allow-Credentials' => 'true',
  25. 'Access-Control-Max-Age' => 1800,
  26. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
  27. 'Access-Control-Allow-Headers' => 'think-lang, server, ba-user-token, batoken, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
  28. ];
  29. /**
  30. * 跨域请求检测
  31. * @access public
  32. * @param Request $request
  33. * @param Closure $next
  34. * @param array|null $header
  35. * @return Response
  36. */
  37. public function handle(Request $request, Closure $next, ?array $header = []): Response
  38. {
  39. $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
  40. $origin = $request->header('origin');
  41. if ($origin) {
  42. $info = parse_url($origin);
  43. // 获取跨域配置
  44. $corsDomain = explode(',', Config::get('buildadmin.cors_request_domain'));
  45. $corsDomain[] = $request->host(true);
  46. if (in_array("*", $corsDomain) || in_array($origin, $corsDomain) || (isset($info['host']) && in_array($info['host'], $corsDomain))) {
  47. header("Access-Control-Allow-Origin: " . $origin);
  48. }
  49. }
  50. return $next($request)->header($header);
  51. }
  52. }