nelsonota / cakephp-cors
CakePHP(3.3.x)插件,用于在您的应用程序中激活跨源域并设置安全策略
Requires
- php: >=7.2.0
- cakephp/cakephp: ^4.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- cakephp/cakephp-codesniffer: ^4.0
- phpunit/phpunit: ~8.5.0
This package is auto-updated.
Last update: 2024-09-20 18:23:44 UTC
README
一个用于在您的应用程序中通过中间件激活跨源域的 CakePHP(4+)插件。
对于 cake 3.3+,请使用分支 cake-3
要求
- PHP 版本 7.2 或更高
- CakePhp 4.0 或更高
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。
安装 composer 包的推荐方法是
composer require ozee31/cakephp-cors
快速开始
加载插件
// In src/Application.php public function bootstrap(): void { // code ... $this->addPlugin('Cors'); }
默认情况下,插件授权所有来源、所有方法和所有头部的 CORS,并将所有内容缓存一天。
配置
默认配置
<?php [ 'AllowOrigin' => true, // accept all origin 'AllowCredentials' => true, 'AllowMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], // accept all HTTP methods 'AllowHeaders' => true, // accept all headers 'ExposeHeaders' => false, // don't accept personal headers 'MaxAge' => 86400, // cache for 1 day 'exceptionRenderer' => 'Cors\Error\AppExceptionRenderer', // Use ExeptionRenderer class of plugin
更改配置
在 app.php
中添加
'Cors' => [ // My Config ]
AllowOrigin (Access-Control-Allow-Origin)
返回的资源可能有一个 Access-Control-Allow-Origin 头,其语法如下
'Cors' => [ // Accept all origins 'AllowOrigin' => true, // OR 'AllowOrigin' => '*', // Accept one origin 'AllowOrigin' => 'http://flavienbeninca.fr' // Accept many origins 'AllowOrigin' => ['http://flavienbeninca.fr', 'http://google.com'] ]
AllowCredentials (Access-Control-Allow-Credentials)
Access-Control-Allow-Credentials 头指示当凭证标志为 true 时,是否可以暴露对请求的响应。当作为对预检请求的响应的一部分使用时,这表示是否可以使用凭证实际发起请求。请注意,简单的 GET 请求不会被预检,因此如果请求带有凭证的资源,如果此头未与资源一起返回,则浏览器会忽略该响应,并将其返回给网络内容。
'Cors' => [ 'AllowCredentials' => true, // OR 'AllowCredentials' => false, ]
AllowMethods (Access-Control-Allow-Methods)
'Cors' => [ // string 'AllowMethods' => 'POST', // OR array 'AllowMethods' => ['GET', 'POST'], ]
AllowHeaders (Access-Control-Allow-Headers)
Access-Control-Allow-Headers 头用于对预检请求的响应,指示在发起实际请求时可以使用哪些 HTTP 头。
'Cors' => [ // accept all headers 'AllowHeaders' => true, // accept just authorization 'AllowHeaders' => 'authorization', // accept many headers 'AllowHeaders' => ['authorization', 'other-header'], ]
ExposeHeaders (Access-Control-Expose-Headers)
Access-Control-Expose-Headers 头允许服务器白名单浏览器允许访问的头。例如
'Cors' => [ // nothing 'ExposeHeaders' => false, // string 'ExposeHeaders' => 'X-My-Custom-Header', // array 'ExposeHeaders' => ['X-My-Custom-Header', 'X-Another-Custom-Header'], ]
MaxAge (Access-Control-Max-Age)
Access-Control-Max-Age 头指示预检请求的结果可以被缓存多久。有关预检请求的示例,请参阅上面的示例。
'Cors' => [ // no cache 'MaxAge' => false, // 1 hour 'MaxAge' => 3600, // 1 day 'MaxAge' => 86400, ]
exceptionRenderer
此选项在 app.php
中覆盖默认 exceptionRenderer
。
默认情况下,此类扩展自 Error.exceptionRenderer
以添加 CORS 头
如果您不想覆盖 exceptionRenderer,则必须编写
'Cors' => [ 'exceptionRenderer' => false ]