// +---------------------------------------------------------------------- declare (strict_types = 1); namespace app\admin\middleware; use Closure; use think\Config; use think\Request; use think\Response; use Firebase\JWT\Key; use Firebase\JWT\JWT; /** * 跨域请求支持 */ class AllowCrossDomain { protected $cookieDomain; protected $jwtOpen; protected $jwtSalt; protected $header = [ 'Access-Control-Allow-Origin' =>'*', // 'Access-Control-Allow-Origin' =>'127.0.0.1', 'Access-Control-Allow-Credentials' => 'true', 'Access-Control-Max-Age' => 1800, 'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE', 'Access-Control-Allow-Headers' => 'Accept,token, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With', ]; public function __construct(Config $config) { $this->cookieDomain = $config->get('cookie.domain', ''); $this->jwtOpen = $config->get('develop.jwt_open', ''); $this->jwtSalt = $config->get('develop.jwt_salt', ''); } /** * 允许跨域请求 * @access public * @param array * @param Closure $next * @param array $header * @return Response */ public function handle($request, Closure $next, ? array $header = []) { $header = !empty($header) ? array_merge($this->header, $header) : $this->header; if (!isset($header['Access-Control-Allow-Origin'])) { $origin = $request->header('origin'); if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) { $header['Access-Control-Allow-Origin'] = $origin; } else { $header['Access-Control-Allow-Origin'] = '*'; } } if($this->jwtOpen && $request->isPost()){ $input = $request->getInput(); $input = str_replace("\"",'',$input); if(count(explode('.',$input))==3){ $input = $request->param('jwtData'); $salt = hash('sha256',$this->jwtSalt); $data = JWT::decode($input, new Key($salt, 'HS256'),array('HS256')); $data = json_decode(json_encode($data,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),true); } }elseif($request->isGet()){ $input = $request->get(); $data = $input; }else{ $input = $request->getInput(); $data = !empty($input)?json_decode($input,true):[]; } if(!empty($data)){ if($request->isPost()){ $request->withPost($data); }elseif($request->isGet()){ $request->withGet($data); } } return $next($request)->header($header); } }