middlewares / csp
Middleware to add the Content-Security-Policy header to the response
Installs: 6 808
Dependents: 0
Suggesters: 0
Security: 0
Stars: 15
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: ^7.2 || ^8.0
- paragonie/csp-builder: ^2.4
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^2.3
- middlewares/utils: ^3.0
- oscarotero/php-cs-fixer-config: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^8|^9
- squizlabs/php_codesniffer: ^3.0
Suggests
- psr/log-implementation: Can be used to log the CSP reporting
README
Middleware to add the Content-Security-Policy header to the response using paragonie/csp-builder library.
Requirements
- PHP >= 7.2
- A PSR-7 http library
- A PSR-15 middleware dispatcher
Installation
This package is installable and autoloadable via Composer as middlewares/csp.
composer require middlewares/csp
Example
use ParagonIE\CSPBuilder\CSPBuilder; $csp = CSPBuilder::fromFile('/path/to/source.json'); Dispatcher::run([ new Middlewares\Csp($csp) ]);
Usage
Set the CSP builder to the constructor. See paragonie/csp-builder for more info. If it's not provided, create a generic one with restrictive directives.
legacy
To generate legacy CSP headers for old browsers (X-Content-Security-Policy
and X-Webkit-CSP
). By default is true
but you can disabled it:
$middleware = (new Middlewares\Csp($csp))->legacy(false);
Helpers
createFromFile
Shortcut to create instances using a json file:
Dispatcher::run([ Middlewares\Csp::createFromFile(__DIR__.'/csp-config.json') ]);
createFromData
Shortcut to create instances using an array with data:
Dispatcher::run([ Middlewares\Csp::createFromData([ 'script-src' => ['self' => true], 'object-src' => ['self' => true], 'frame-ancestors' => ['self' => true], ]) ]);
Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.
The MIT License (MIT). Please see LICENSE for more information.