Files
dafuweng-buildadmin/dafuweng-webman/app/common/middleware/AllowCrossDomain.php
2026-03-07 19:42:22 +08:00

56 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\common\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;
/**
* 跨域请求支持Webman 迁移版)
* 安全起见,只支持配置中的域名
*/
class AllowCrossDomain implements MiddlewareInterface
{
protected array $header = [
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '1800',
'Access-Control-Allow-Methods' => '*',
'Access-Control-Allow-Headers' => '*',
];
public function process(Request $request, callable $handler): Response
{
$path = trim($request->path(), '/');
if (!str_starts_with($path, 'api/') && !str_starts_with($path, 'admin/')) {
return $handler($request);
}
$header = $this->header;
$origin = $request->header('origin');
if ($origin) {
$info = parse_url($origin);
$corsDomain = explode(',', config('buildadmin.cors_request_domain', ''));
$corsDomain[] = $request->host(true);
if (
in_array('*', $corsDomain)
|| in_array($origin, $corsDomain)
|| (isset($info['host']) && in_array($info['host'], $corsDomain))
) {
$header['Access-Control-Allow-Origin'] = $origin;
}
}
if ($request->method() === 'OPTIONS') {
return response('', 204, $header);
}
$response = $handler($request);
return $response->withHeaders($header);
}
}