Add Content-Security-Policy headers for PSR-7 requests. Uses the csp-builder library paragonie/csp-builder.

1.0 2022-11-22 23:58 UTC

This package is auto-updated.

Last update: 2022-11-22 23:59:52 UTC


Build Status Total Downloads Latest Stable Version codecov

CSP Middleware

Add Content-Security-Policy headers using PSR-7 requests. Uses the paragonie/csp-builder package.


Adding the middleware is as simple as:

$app->add(new \Pavlakis\Middleware\Csp\CspMiddleware($container->get('csp'));

Where $container->get('csp') returns an instance of CSPBuilder with a CSP configuration.

There is a second parameter $reportOnly. It is a boolean and set to true by default and it will add the CSP header as Content-Security-Policy-Report-Only. This is important so you don't break your application accidentally.

To enable it, pass false

Use a json file with the csp policies.


  "report-only": false,
  "report-uri": "/csp/enforce",
  "base-uri": [],
  "default-src": [],
  "child-src": {
    "self": false
  "connect-src": {},
  "font-src": {
    "self": true
  "form-action": {
    "self": true
  "frame-ancestors": [],
  "img-src": {
    "self": true
  "media-src": [],
  "object-src": [],
  "plugin-types": [],
  "script-src": {
    "allow": [
    "self": true,
    "unsafe-inline": false,
    "unsafe-eval": false
  "style-src": {
    "self": true,
    "unsafe-inline": false
  "upgrade-insecure-requests": true

Example in Slim3

Dependencies (dependencies.php)

$container['csp'] = function ($c) {
    $csp = CSPBuilder::fromFile(__DIR__ . '/configs/csp.json');
    return $csp;

Application Middleware (middleware.php)

$app->add(new \Pavlakis\Middleware\Csp\CspMiddleware($container->get('csp'));


Useful resources for CSP