Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions docs/development/csp.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# Content security policy

The bundle sets pretty strict CSP headers on every response out-of-the-box. This prevents a large portion of XSS attacks on applications built with the framework.
The bundle sets pretty strict CSP headers on every response out-of-the-box. This prevents a large portion of XSS attacks
on applications built with the framework.

For more information, read https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

## Base rules

```php
// The default rule and fallback: only allow content from our own domain
"default-src 'self';" .
Expand All @@ -19,18 +21,25 @@ For more information, read https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
```

## Extending the headers
In some cases, you might have to allow external CSS and/or JS in your project. To do so, you'll have to allow the domain on which the resource is hosted.

You can either tweak the CSP header inside a specific controller (where you already have a Response object), or add an event listener on the kernel response event and tweak the headers there (globally).
In some cases, you might have to allow external CSS and/or JS in your project. To do so, you'll have to allow the domain
on which the resources are hosted.

You can either tweak the CSP header inside a specific controller (where you already have a Response object), or add an
event listener on the kernel response event and tweak the headers there (globally).

Note that you need to include the existing CSP headers.

services.yaml

```yaml
App\EventListener\ResponseListener:
App\EventListener\ResponseListener:
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse, priority: -5 }
```

ResponseListener.php

```php
<?php

Expand All @@ -40,11 +49,21 @@ use Symfony\Component\HttpKernel\Event\ResponseEvent;

class ResponseListener
{
public function onKernelResponse(ResponseEvent $event)
public function onKernelResponse(ResponseEvent $event): void
{
$event->getResponse()->headers->set('Content-Security-Policy',
"script-src https://your-cdn.com/your-script.js",
false // Passing false here will add the new headers instead of overwrite
// allow Google Maps to be loaded
$headers = [
'default-src \'self\'',
'style-src \'self\' https://fonts.googleapis.com \'unsafe-inline\'',
'font-src \'self\' https://fonts.gstatic.com',
'frame-src \'none\'',
'script-src \'self\' \'nonce-FOR725\' maps.googleapis.com',
'img-src \'self\' data: maps.gstatic.com *.googleapis.com *.ggpht.com maps.google.com',
];

$event->getResponse()->headers->set(
'Content-Security-Policy',
implode('; ', $headers)
);
}
}
Expand Down