AllowCrossDomain.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // +----------------------------------------------------------------------
  12. // | 跨域请求支持
  13. // +----------------------------------------------------------------------
  14. declare (strict_types = 1);
  15. namespace app\common\middleware;
  16. use Closure;
  17. use think\exception\HttpResponseException;
  18. use think\facade\Config;
  19. use think\Request;
  20. use think\Response;
  21. class AllowCrossDomain
  22. {
  23. //是否允许所有请求头
  24. protected $allowAllHeaders = true;
  25. protected $header = [
  26. 'Access-Control-Allow-Credentials' => 'true',
  27. 'Access-Control-Max-Age' => 1800,
  28. 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
  29. 'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
  30. ];
  31. /**
  32. * 允许跨域请求
  33. * @access public
  34. * @param Request $request
  35. * @param Closure $next
  36. * @param array $header
  37. * @return Response
  38. */
  39. public function handle(Request $request, Closure $next, array $header = []): Response
  40. {
  41. $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
  42. $origin = $request->header('origin');
  43. if ($origin && !isset($header['Access-Control-Allow-Origin'])) {
  44. $info = parse_url($origin);
  45. $domainArr = explode(',', Config::get('yzn.cors_request_domain'));
  46. $domainArr[] = $request->host(true);
  47. if (in_array("*", $domainArr) || in_array($origin, $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
  48. $header['Access-Control-Allow-Origin'] = $origin;
  49. } else {
  50. $response = Response::create('跨域检测无效', 'html', 403);
  51. throw new HttpResponseException($response);
  52. }
  53. }
  54. if ($request->isOptions()) {
  55. if ($this->allowAllHeaders) {
  56. $header['Access-Control-Allow-Headers'] = (string) $request->header('Access-Control-Request-Headers');
  57. }
  58. $response = Response::create('', 'html', 204)->header($header);
  59. throw new HttpResponseException($response);
  60. }
  61. return $next($request)->header($header);
  62. }
  63. }