asm89/stack-cors

跨域资源共享库和中间件

v2.2.0 2023-11-14 13:51 UTC

README

为您的 http-{基础,内核} 应用程序启用跨域资源共享的库和中间件。它试图实现W3C 建议的跨域资源共享。

构建状态: .github/workflows/run-tests.yml

安装

使用 composer 安装 asm89/stack-cors

用法

此包可以作为库或作为stack 中间件使用。

选项

allowedMethodsallowedHeaders 选项不区分大小写。

您无需同时提供 allowedOriginsallowedOriginsPatterns。如果传递的字符串之一匹配,则被认为是有效的源。

如果将 ['*'] 提供给 allowedMethodsallowedOriginsallowedHeaders,则允许所有方法/源/头部。

如果 supportsCredentialstrue,则必须为任何不属于 CORS 安全列表的头部显式设置 allowedHeaders

示例:使用库

<?php

use Asm89\Stack\CorsService;

$cors = new CorsService([
    'allowedHeaders'         => ['x-allowed-header', 'x-other-allowed-header'],
    'allowedMethods'         => ['DELETE', 'GET', 'POST', 'PUT'],
    'allowedOrigins'         => ['http://localhost'],
    'allowedOriginsPatterns' => ['/localhost:\d/'],
    'exposedHeaders'         => false,
    'maxAge'                 => 600,
    'supportsCredentials'    => true,
]);

$cors->addActualRequestHeaders(Response $response, $origin);
$cors->handlePreflightRequest(Request $request);
$cors->isActualRequestAllowed(Request $request);
$cors->isCorsRequest(Request $request);
$cors->isPreflightRequest(Request $request);

示例:使用中间件

<?php

use Asm89\Stack\Cors;

$app = new Cors($app, [
    // you can use ['*'] to allow any headers
    'allowedHeaders'      => ['x-allowed-header', 'x-other-allowed-header'],
    // you can use ['*'] to allow any methods
    'allowedMethods'      => ['DELETE', 'GET', 'POST', 'PUT'],
    // you can use ['*'] to allow requests from any origin
    'allowedOrigins'      => ['localhost'],
    // you can enter regexes that are matched to the origin request header
    'allowedOriginsPatterns' => ['/localhost:\d/'],
    'exposedHeaders'      => false,
    'maxAge'              => 600,
    'supportsCredentials' => false,
]);