3

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:

Artur
  • 131
  • 2
  • 7
  • which version of symfony do you use ? Can you copy/paste your configuration ? does your assets url is under https ? Documentation (https://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#configuration-changes) – Romain Norberg Feb 14 '18 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 Feb 14 '18 at 22:04

1 Answers1

6

Okay, 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
Artur
  • 131
  • 2
  • 7
  • 1
    Note: from SF4.3, `FilterResponseEvent` has been renamed to `ResponseEvent`. Also, the deprecated `X-*` headers should be avoided – the_nuts Nov 29 '19 at 16:50