AllowOriginMiddleware.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\middleware;
  12. use app\Request;
  13. use think\exception\HttpResponseException;
  14. use think\facade\Config;
  15. use think\Response;
  16. /**
  17. * 跨域中间件
  18. * Class AllowOriginMiddleware
  19. * @package app\http\middleware
  20. */
  21. class AllowOriginMiddleware extends BaseMiddleware
  22. {
  23. /**
  24. * header头
  25. * @var array
  26. */
  27. protected $header = [
  28. 'Access-Control-Allow-Origin' => '*',
  29. 'Access-Control-Allow-Headers' => 'X-Token, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With,Form-type,Referer,Connection,Content-Length,Host,Origin,Authorization,Authori-zation,Accept,Accept-Encoding',
  30. //,Host,Origin,Authorization,Authori-zation,Accept,Accept-Encoding
  31. //'Access-Control-Allow-Headers' => '*',
  32. 'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS',
  33. 'Access-Control-Max-Age' => '1728000'
  34. ];
  35. public function before(Request $request)
  36. {
  37. $cookieDomain = Config::get('cookie.domain', '');
  38. $origin = $request->header('origin');
  39. if ($origin && $cookieDomain && strpos($origin, $cookieDomain))
  40. $this->header['Access-Control-Allow-Origin'] = $origin;
  41. if ($request->method(true) == 'OPTIONS') {
  42. throw new HttpResponseException(Response::create()->code(200)->header($this->header));
  43. }
  44. }
  45. public function after(Response $response)
  46. {
  47. $response->header($this->header);
  48. }
  49. }