makise-co/stack-cors

跨源资源共享库和中间件

v2.0.7 2021-11-29 22:25 UTC

This package is auto-updated.

Last update: 2024-09-29 05:49:30 UTC


README

https://github.com/asm89/stack-cors 的分支,允许在 Makise 框架中使用原始包。

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

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

安装

使用 composer 安装 makise-co/stack-cors

使用

  • 在您的配置目录中创建 cors.php 配置文件
  • CorsServiceProvider 添加到 config/app.php 的 "providers" 部分
  • CorsMiddleware 添加到 config/http.php 的 "middleware" 部分

选项

allowedMethodsallowedHeaders 选项不区分大小写。

您不需要同时提供 allowedOriginsallowedOriginsPatterns。如果传入的字符串之一匹配,则认为是一个有效的来源。

如果向 allowedMethodsallowedOriginsallowedHeaders 提供了 array('*'),则允许所有方法/来源/头。

示例:允许所有路径上的 CORS 的配置

return [

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => ['*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowedMethods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowedOrigins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowedOriginsPatterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowedHeaders' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposedHeaders' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'maxAge' => 600,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supportsCredentials' => true,

];

示例:使用库

<?php

use Asm89\Stack\CorsService;

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

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