AllowOriginMiddleware.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace app\http\middleware;
  3. use app\Request;
  4. use crmeb\interfaces\MiddlewareInterface;
  5. use think\facade\Config;
  6. use think\Response;
  7. /**
  8. * 跨域中间件
  9. * Class AllowOriginMiddleware
  10. * @package app\http\middleware
  11. */
  12. class AllowOriginMiddleware implements MiddlewareInterface
  13. {
  14. /**
  15. * header头
  16. * @var array
  17. */
  18. protected $header = [
  19. 'Access-Control-Allow-Origin' => '*',
  20. 'Access-Control-Allow-Headers' => 'UID, Authori-zation, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
  21. 'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
  22. 'Access-Control-Max-Age' => '1728000'
  23. ];
  24. /**
  25. * 允许跨域的域名
  26. * @var string
  27. */
  28. protected $cookieDomain;
  29. /**
  30. * @param Request $request
  31. * @param \Closure $next
  32. * @return Response
  33. */
  34. public function handle(Request $request, \Closure $next)
  35. {
  36. $this->cookieDomain = Config::get('cookie.domain', '');
  37. $header = $this->header;
  38. $origin = $request->header('origin');
  39. if ($origin && ('' != $this->cookieDomain && strpos($origin, $this->cookieDomain)))
  40. $header['Access-Control-Allow-Origin'] = $origin;
  41. if ($request->method(true) == 'OPTIONS') {
  42. $response = Response::create('ok')->code(200)->header($header);
  43. } else {
  44. $response = $next($request)->header($header);
  45. }
  46. $request->filter(['htmlspecialchars', 'strip_tags', 'addslashes', 'trim']);
  47. return $response;
  48. }
  49. }