cindyullmann/laminas-cors 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

cindyullmann/laminas-cors

Composer 安装命令:

composer require cindyullmann/laminas-cors

包简介

Laminas module that let you deal with CORS requests

README 文档

README

Build Status Scrutinizer Quality Score Coverage Status Latest Stable Version

LaminasCors is a simple Laminas module that helps you to deal with Cross-Origin Resource Sharing (CORS).

What is LaminasCors ?

LaminasCors is a Laminas Framework module that allow to easily configure your Laminas application so that it automatically builds HTTP responses that follow the CORS documentation.

Installation

Install the module by typing (or add it to your composer.json file):

$ php composer.phar require cindyullmann/laminas-cors

Then, enable it by adding "LaminasCors" in your application.config.php file.

By default, LaminasCors is configured to deny every CORS requests. To change that, you need to copy the config/laminas_cors.global.php.dist file to your autoload folder (remove the .dist extension), and modify it to suit your needs.

Documentation

What is CORS ?

CORS is a mechanism that allows to perform cross-origin requests from your browser.

For instance, let's say that your website is hosted in the domain http://example.com. By default, user agents won't be allowed to perform AJAX requests to another domain for security reasons (for instance http://funny-domain.com).

With CORS, you can allow your server to reply to such requests.

You can find better documentation on how CORS works on the web:

Event registration

LaminasCors registers the LaminasCors\Mvc\CorsRequestListener with the MvcEvent::EVENT_ROUTE event, with a priority of -1. This means that this listener is executed AFTER the route has been matched.

Configuring the module

As by default, all the various options are set globally for all routes:

  • allowed_origins: (array) List of allowed origins. To allow any origin, you can use the wildcard (*) character. If multiple origins are specified, LaminasCors will automatically check the "Origin" header's value, and only return the allowed domain (if any) in the "Allow-Access-Control-Origin" response header. To allow any sub-domain, you can prefix the domain with the wildcard character (i.e. *.example.com). Please note that you don't need to add your host URI (so if your website is hosted as "example.com", "example.com" is automatically allowed.
  • allowed_methods: (array) List of allowed HTTP methods. Those methods will be returned for the preflight request to indicate which methods are allowed to the user agent. You can even specify custom HTTP verbs.
  • allowed_headers: (array) List of allowed headers that will be returned for the preflight request. This indicates to the user agent which headers are permitted to be sent when doing the actual request.
  • max_age: (int) Maximum age (seconds) the preflight request should be cached by the user agent. This prevents the user agent from sending a preflight request for each request.
  • exposed_headers: (array) List of response headers that are allowed to be read in the user agent. Please note that some browsers do not implement this feature correctly.
  • allowed_credentials: (boolean) If true, it allows the browser to send cookies along with the request.

If you want to configure specific routes, you can add LaminasCors\Options\CorsOptions::ROUTE_PARAM to your route configuration:

<?php

return [
    'laminas_cors' => [
        'allowed_origins' => ['*'],
        'allowed_methods' => ['GET', 'POST', 'DELETE'],
    ],
    'router' => [
        'routes' => [
            'readOnlyRoute' => [
                'type' => 'literal',
                'options' => [
                    'route' => '/foo/bar',
                    'defaults' => [
                        // This will replace allowed_methods configuration to only allow GET requests
                        // and only allow a specific origin instead of the wildcard origin
                        LaminasCors\Options\CorsOptions::ROUTE_PARAM => [
                            'allowed_origins' => ['http://example.org'],
                            'allowed_methods' => ['GET'],
                        ],
                    ],
                ],
            ],
            'someAjaxCalls' => [
                'type' => 'literal',
                'options' => [
                    'route' => '/ajax',
                    'defaults' => [
                        // This overrides the wildcard origin
                        LaminasCors\Options\CorsOptions::ROUTE_PARAM => [
                            'allowed_origins' => ['http://example.org'],
                        ],
                    ],
                ],
                'may_terminate' => false,
                'child_routes' => [
                    'blog' => [
                        'type' => 'literal',
                        'options' => [
                            'route' => '/blogpost',
                            'defaults' => [
                                // This would only allow `http://example.org` to GET this route
                                \LaminasCors\Options\CorsOptions::ROUTE_PARAM => [
                                    'allowed_methods' => ['GET'],
                                ],
                            ],
                        ],
                        'may_terminate' => true,
                        'child_routes' => [
                            'delete' => [
                                'type' => 'segment',
                                'options' => [
                                    'route' => ':id',
                                    // This would only allow origin `http://example.org` to apply DELETE on this route
                                    'defaults' => [
                                        \LaminasCors\Options\CorsOptions::ROUTE_PARAM => [
                                            'allowed_methods' => ['DELETE'],
                                        ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ],
];

Preflight request

If LaminasCors detects a preflight CORS request, a new HTTP response will be created, and LaminasCors will send the appropriate headers according to your configuration. The response will be always sent with a 200 status code (OK).

Please note that this will also prevent further MVC steps from being executed, since all subsequent MVC steps are skipped till Laminas\Mvc\MvcEvent::EVENT_FINISH, which is responsible for actually sending the response.

Actual request

When an actual request is made, LaminasCors first checks it the origin is allowed. If it is not, then a new response with a 403 status code (Forbidden) is created and sent.

Please note that this will also prevent further MVC steps from being executed, since all subsequent MVC steps are skipped till Laminas\Mvc\MvcEvent::EVENT_FINISH, which is responsible for actually sending the response.

If the origin is allowed, LaminasCors will just add the appropriate headers to the request produced by Laminas\Mvc.

Security concerns

Don't use this module to secure your application! You must use a proper authorization module.

LaminasCors only allows to accept or refuse a cross-origin request.

Custom schemes

Internally, LaminasCors uses Laminas\Uri\UriFactory class. If you are using custom schemes (for instance if you are testing your API with some Google Chrome extensions), you need to add support for those schemes by adding them to the UriFactory config (please refer to the doc).

Example

To register the chrome-extension custom scheme in your API, simply add:

UriFactory::registerScheme('chrome-extension', 'Laminas\Uri\Uri');

to the onBootstrap() method in module/Application/Module.php. Do note that, if your IDE doesn't resolve this automatically, you should add the following use definition to the same file:

use Laminas\Uri\UriFactory;

Registering the chrome-extension custom scheme like this allows you to use Google Chrome extensions for testing your API.

cindyullmann/laminas-cors 适用场景与选型建议

cindyullmann/laminas-cors 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.7k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2022 年 07 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「rest」 「cors」 「cross origin sharing resource」 「laminas」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 cindyullmann/laminas-cors 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 cindyullmann/laminas-cors 我们能提供哪些服务?
定制开发 / 二次开发

基于 cindyullmann/laminas-cors 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 4.7k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 17
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 39
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-07-18