I have a problem with Content Security Policy. Whenever I trying to include the JavaScript into my project, I get an content-security-policy error.
<!DOCTYPE html>
<html>
<head>
<title>Symfony</title>
<script src="{{ asset('myscript.js') }}"></script>
</head>
<body>
// ...
</body>
</html>
What am I doing wrong?
I've already tried with:
- .htaccess:
Header set Content-Security-Policy "script-src 'self';"
- html:
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
- /
I have a problem with Content Security Policy. Whenever I trying to include the JavaScript into my project, I get an content-security-policy error.
<!DOCTYPE html>
<html>
<head>
<title>Symfony</title>
<script src="{{ asset('myscript.js') }}"></script>
</head>
<body>
// ...
</body>
</html>
What am I doing wrong?
I've already tried with:
- .htaccess:
Header set Content-Security-Policy "script-src 'self';"
- html:
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
- https://ikvasnica./blog/how-to-protect-php-application-from-xss-attacks-csp-3-nonce/
- which version of symfony do you use ? Can you copy/paste your configuration ? does your assets url is under https ? Documentation (symfony./blog/…) – Romain Norberg Commented Feb 14, 2018 at 18:58
- I use the version 3.4 of Symfony and all urls are under http. The configurations are the same as after the installation. – Artur Commented Feb 14, 2018 at 22:04
1 Answer
Reset to default 6Okay, I found a solution. I added to my code an event subscriber, which sets the "Content-Security-Policy" header.
<?php
namespace AppBundle\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class ResponseSubscriber
* @package AppBundle\Subscriber
*/
class ResponseSubscriber implements EventSubscriberInterface
{
/** @inheritdoc */
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => 'onResponse'
];
}
/**
* Callback function for event subscriber
* @param FilterResponseEvent $event
*/
public function onResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
$policy = "default-src 'self' 'unsafe-inline';"
. "script-src 'self' 'unsafe-inline'";
$response->headers->set("Content-Security-Policy", $policy);
$response->headers->set("X-Content-Security-Policy", $policy);
$response->headers->set("X-WebKit-CSP", $policy);
}
}
and
# app/config/services.yml
services:
# ...
app.responseSubscriber:
class: AppBundle\Subscriber\ResponseSubscriber
autowire: true