eugene-manuilov / phalcon-csp
该软件包已被废弃,不再维护。未建议替代软件包。
PhalconPHP 框架的内容安全策略 (CSP) 插件。
1.0.1
2016-08-24 21:47 UTC
Requires (Dev)
- fzaninotto/faker: ^1.6
- phpunit/phpunit: ^5.5
This package is not auto-updated.
Last update: 2020-01-22 06:13:36 UTC
README
此插件允许您将 CSP 策略添加到基于 Phalcon 的网站中。内容安全策略 (CSP) 是一种安全标准,用于防止跨站脚本 (XSS)、点击劫持和其他代码注入攻击。有关更多详细信息,请参阅 内容安全策略简介 文章。
安装
仅使用 composer 安装即可
$ composer require eugene-manuilov/phalcon-csp
使用
要在您的网站上使用 CSP 插件,您只需将其添加到依赖注入容器,并将其注册为事件监听器。
<?php use Phalcon\Plugin\CSP\ContentSecurityPolicy; // register CSP service $di->set( 'csp', function() { $csp = new ContentSecurityPolicy(); return $csp; }, true ); // register application and add CSP to event manager try { $csp = $di->getShared( 'csp' ); $eventsManager = new \Phalcon\Events\Manager(); $eventsManager->attach( 'application:beforeSendResponse', $csp ); $application = new Application($di); $application->setEventsManager( $eventsManager ); $response = $application->handle(); $response->send(); } catch (\Exception $e) { echo $e->getMessage(); }
现在所有策略都将编译成 Content-Security-Policy
标头,并添加到响应实例中。要添加新策略,您需要调用 addPolicy()
函数,该函数接受策略名称和值
<?php use Phalcon\Plugin\CSP\ContentSecurityPolicy as CSP; class IndexController extends \Phalcon\Mvc\Controller { public function indexAction() { // whitelist Google fonts origin $this->csp->addPolicy( CSP::DIRECTIVE_FONT_SRC, 'https://fonts.gstatic.com' ); } }
如果您想指定用于报告所有违规行为的报告 URL,则需要调用 setReportURI()
函数。
$di->set( 'csp', function() { $csp = new ContentSecurityPolicy(); $csp->setReportURI( '/path/to/report/endpoint' ); return $csp; }, true );
使用内容安全策略 (CSP) 标头,您还可以告诉浏览器您希望将所有不安全的请求升级为使用其安全版本。为此,您需要使用 setUpgradeInsecureRequests()
函数。
$di->set( 'csp', function() { $csp = new ContentSecurityPolicy(); $csp->setUpgradeInsecureRequests(); return $csp; }, true );
资产管理器
此插件还提供了一个资产管理系统类,该类扩展了标准资产管理器类,并自动收集使用它添加的脚本和样式的来源。它还为内联脚本和样式生成非ces。
<?php $di->set( 'assets', function() { $manager = new \Phalcon\Plugin\CSP\Assets\Manager(); return $manager; }, true );
之后,您可以使用它作为标准的资产管理器类来添加您的脚本和样式文件以及内联块。