AllowOriginMiddleware.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\http\middleware;
  12. use app\Request;
  13. use crmeb\interfaces\MiddlewareInterface;
  14. use think\facade\Config;
  15. use think\Response;
  16. /**
  17. * 跨域中间件
  18. * Class AllowOriginMiddleware
  19. * @package app\http\middleware
  20. */
  21. class AllowOriginMiddleware implements MiddlewareInterface
  22. {
  23. /**
  24. * 允许跨域的域名
  25. * @var string
  26. */
  27. protected $cookieDomain;
  28. /**
  29. * @param Request $request
  30. * @param \Closure $next
  31. * @return Response
  32. */
  33. public function handle(Request $request, \Closure $next)
  34. {
  35. $this->cookieDomain = Config::get('cookie.domain', '');
  36. $header = Config::get('cookie.header');
  37. $origin = $request->header('origin');
  38. if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain)))
  39. $header['Access-Control-Allow-Origin'] = $origin;
  40. if ($request->method(true) == 'OPTIONS') {
  41. $response = Response::create('ok')->code(200)->header($header);
  42. } else {
  43. $response = $next($request)->header($header);
  44. }
  45. // $request->filter(['strip_tags', 'addslashes', 'trim']);
  46. return $response;
  47. }
  48. }